Step by Step implement StyleCop custom rules with Visual Studio – Part 2

This is Part 2 of 2 Part series on implementing custom StyleCop rules. Please read Part 1 here, if you haven’t already read.

Now download the code of creating the custom rules from here. Make sure you perform following steps to build it, in case you are unable to build:

  1. Installation location of StyleCop will be under Program Files.
  2. Make a reference to the dll named StyleCop.dll from the installed location of StyleCop.
  3. Make another reference to the dll named StyleCop.CSharp.dll from the installation location of StyleCop.
  4. Note that the XML file in the project has same name as class file and in the property of XML file Build Action is set to Embedded Resource.

Once your solution builds successfully, copy below mentioned code in cs file StyleCopCustomRule.cs on line number 26 just below // Run your rules.

for(Node<CsToken> tokenNode
    = csharpDocument.Tokens.First;
 tokenNode != null; tokenNode = tokenNode.Next)
 if (tokenNode.Value.CsTokenType == CsTokenType.String)

Similarly copy below content of XML file in StyleCopCustomRule.xml between the rules tag.

<RuleGroup Name="String Rules">    
 <Rule Name="CodeMustNotContainHardcodedStrings"
     The code should not contain
     any hard-coded strings.      
     Validates that the code does not
     contain any hardcoded strings.    

Lets now test our new rule using the steps below:

  1. Make sure you close Test project that you created in Part 1 of this post series.
  2. Copy newly created custom dll (StyleCopRuleExtension.dll) to StyleCop folder. It will be under “Drive Label:\Program file\StyleCop 4.7” folder.
  3. Open the Test project mentioned in step 1 above.
  4. For some reason you may not getting any error on build. Edit the file by adding a space somewhere in one of the lines in your test project . It sounds funny but it works.
  5. Build the project. You must get 2 additional errors for hard-coded strings.

Happy Coding.


1 comment

Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: