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)
   {
   this.AddViolation(csharpDocument.RootElement,
   tokenNode.Value.LineNumber,
   "CodeMustNotContainHardcodedStrings");
   }
 }

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

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

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.

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

Instead of starting with an introduction of StyleCop, I would like you to read “Why should we use StyleCop?“. There is enough help on how to integrate StyleCop with Visual Studio, one can be found here. This article is focused on step by step implementation to add custom rules that we used in our project.

Install StyleCop : http://stylecop.codeplex.com/ (Version 4.7)

Create a sample console project using Visual Studio. The idea here is to create a code base to test our custom rule. Code sample is as seen below :

using System;

namespace TestSampleStyleCopCustomRule
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write
              (combineTwoWordsWithSpace
              ("Vikram", "Shetty"));
            Console.ReadKey();
        }
        public static string
            combineTwoWordsWithSpace
             (string firstWord,
              string secondWord)
        {
               return firstWord + " "
                + secondWord;
        }
    }
}

Edit the .csproj you just created above and add the following line after last <Import Project=

  <Import Project="$(ProgramFiles)\MSBuild\StyleCop\v4.7\StyleCop.Targets" />

To treat StyleCop Warnings, as errors add the following line as a child of  PropertyGroup tag. Make sure you place it in PropertyGroup with Configuration|Platform=Debug. Mostly it will be on top as a first group:

<StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings>

Now once you build your solution you should get around 15 errors, The number of errors is not important here, just make a note of it because we will add a custom error in our Part 2 post, thus making sure our new custom rule works. If you want to make it more challenging fix all your errors.

Read next post of this step by step series here.