General > Tools >> StyleCop Views : 21192
Rate This Article :

Create custom rules using StyleCop

This article explains to create custom rules in stylecop with easy steps. In general, stylecop is used to identify issues in the written code (Technical) and refactor the code.

Step 1 - Creation of Project:

Create a new Visual Studio class library project targeting .NET 3.5/4.0.

DotNet.png

Step 2 – Adding StyleCop Reference:

·         StyleCop

·         StyleCop.CSharp

DotNet.png

 

Step 3 – Add Custom Analyzer Class:

Once the references are added, add your custom class for Stylecop analyzer. There can be many analyzer classes inside one assembly.

DotNet.png

 

Copy and Paste” the below code in your analyzer class.

namespace StyleCopNewRule

{

    using StyleCop;

    using StyleCop.CSharp;

 

    [SourceAnalyzer(typeof(CsParser))]

    public class MyOwnCustomAnalyzer : SourceAnalyzer

    {

        public override void AnalyzeDocument(CodeDocument currentCodeDocument)

        {

            var codeDocument = (CsDocument)currentCodeDocument;

            if (codeDocument.RootElement != null && !codeDocument.RootElement.Generated)

            {

                codeDocument.WalkDocument(new CodeWalkerElementVisitor<object>(this.InspectCurrentElement), null, null);

            }

        }

 

        private bool InspectCurrentElement(CsElement element, CsElement parentElement, object context)

        {

            if (element.ElementType == ElementType.Method)

            {

                bool boolIsTryFound = false;

                bool boolIsCatchFound = false;

 

                var tempDocument = (CsDocument)element.Document;

                var objReader = tempDocument.SourceCode.Read();

 

                string strCode;

                while ((strCode = objReader.ReadLine()) != null)

                {

                    if (strCode.Contains("try"))

                    {

                        boolIsTryFound = true;

                    }

 

                    if (boolIsTryFound)

                    {

                        if (strCode.Contains("catch"))

                        {

                            boolIsCatchFound = true;

                        }

                    }

                }

 

                if ((boolIsTryFound) && (boolIsCatchFound == false))

                {

                    this.AddViolation(parentElement, "MyOwnCustomRule", "CatchShouldBeImplemented");

                }

            }

            return true;

        }

 

    }

}

 

Step 4 - Add analyzer definition XML file:

Rule definition should be present for each analyzer file. Create XML file as mentioned below

·         It should have same name given for analyzer file.

·         Select “Build Action” as “Embedded Resource”

 

DotNet.png

 

Copy and Paste” the below content in the XML file:

<?xml version="1.0" encoding="utf-8" ?>

<SourceAnalyzer Name="My Own Custom Rule">

  <Description> Custom rules added to analyzer. </Description>

  <Rules>

    <RuleGroup Name="Implementation">

      <Rule Name="MyOwnCustomRule" CheckId="HE2222">

        <Context>Catch block Should be present.</Context>

        <Description>Catch block Should be present.</Description>

      </Rule>

    </RuleGroup>

  </Rules>

</SourceAnalyzer>

 

Step 5 - Build and Deployment:

 

Build the library, and place the output file inside the StyleCop installation directory.

 

DotNet.png

 

Step 6 - View the Custom File Settings:

 

Reopen your solution and you can see the custom file has been loaded in the “StyleCop Settings” Editor.

 

DotNet.png

 

Step 7: Check Custom Style Cop settings Works!

 

Create a method use “try” without using “Catch” block. The stylecop exception will be displayed as warning. The warning will have the information about your custom rule.

 

DotNet.png

This is an example on how to create own custom class in stylecop. You can write your own rules to align with your coding practice. Happy Learning!

About Author
Raj Kumar
Total Posts 57
Developer in .Net!
Comment this article
Name*
Email Address* (Will not be shown on this website.)
Comments*
Enter Image Text*
   
View All Comments
naoufel
this code works only on one method, if we add other methods to the class and lunch the test, it will not work ( if just one method didnt respect the rule a message is showed and said that all methods didnt respect this custom rule ).
Sachin pal
I put custom rules dll in stylecop4.7 folder but it stylecop setting it is not showing any custom rule checkbox. only default ruls are showing.. can u please tell me how to i add custom rules checkbox in stylecop setting popup window
Shadower
This rule will be analyzing the commented code also. How to exclude the commented code from the analysis?
Jürgen
Is there any way to disable a custom rule per default? (this rule should by unchecked in the settings file per default)
Raj
Yes, we can find the exact line by adding the count logic in the below line. int i = 0; while ((strCode = objReader.ReadLine()) != null) i++; Please check and revert back.
randula
How to show the exact line that containing a specific word. I modified this code. But it shows only the method containing that specific word. not exact line.
Tom
Is there a waz of creating a custom rule that checks content of xml comments? Thanks!
  Privacy   Terms Of Use   Contact Us
© 2016 Developerin.Net. All rights reserved.
Trademarks and Article Images mentioned in this site may belongs to Microsoft and other respective trademark owners.
Articles, Tutorials and all other content offered here is for educational purpose only and its author copyrights.