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:
- Installation location of StyleCop will be under Program Files.
- Make a reference to the dll named StyleCop.dll from the installed location of StyleCop.
- Make another reference to the dll named StyleCop.CSharp.dll from the installation location of StyleCop.
- 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:
- Make sure you close Test project that you created in Part 1 of this post series.
- Copy newly created custom dll (StyleCopRuleExtension.dll) to StyleCop folder. It will be under “Drive Label:\Program file\StyleCop 4.7” folder.
- Open the Test project mentioned in step 1 above.
- 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.
- Build the project. You must get 2 additional errors for hard-coded strings.
Happy Coding.
1 comment