Copyright 2008-2009, Paul Jackson, all rights reserved
Since manual code reviews for style and formatting are a huge time waster, I jumped all over this for use in my shop. Unfortunately, my coworkers can't just accept doing things the Microsoft way; they have to be a bit different, so I started investigating what was involved in creating custom rules.
The first step is to download and install the Source Analyzer from: http://code.msdn.microsoft.com/sourceanalysis/Release/ProjectReleases.aspx
The default install will go to "C:\Program Files\Microsoft Source Analysis Tool for C#" and add context-menu options to the Solution Explorer in Visual Studio 2008:
Source Analyzer uses Reflection to examine every DLL in its install directory to find custom rules, so all we'll need to do is create a class library with the right classes and attributes and Source Analyzer will automatically load our new rules.
Create a new ClassLibrary project, then add references to the Microsoft.SourceAnalysis and Microsoft.SourceAnalysis.CSharp assemblies:
Then add a new class and an XML file with the same name. Set the Properties of the XML file to be an Embedded Resource and not copy to the output directory:
The XML file should contain the following:
<?xml version="1.0" encoding="utf-8" ?>
<SourceAnalyzer Name="Custom Rules">
Custom rules added to analyzer.
<RuleGroup Name="Custom Rules Group">
<Rule Name="MyCustomRule" CheckId="CR0001">
<Context>This is a custom rule.</Context>
<Description>This is a custom rule description.</Description>
public class SampleAddInRules : SourceAnalyzer
public override void AnalyzeDocument(CodeDocument document)
CsDocument document2 = (CsDocument)document;
if ((document2.RootElement != null) && !document2.RootElement.Generated)
AddViolation(document2.RootElement, "MyCustomRule", new object);
Build the project and copy its DLL to the Source Analysis install directory. Now, when you run Source Analysis on a project, you should get a warning about the custom rule for every file in the project:
One of the differences between the standards where I work and Microsoft's is that we require private fields to start with an underscore ("_"), while the Microsoft rules provided by StyleCop require they start with a lower-case letter and contain no underscores. So I'll be turning off the two Microsoft rules (SA1306 and SA1309) and creating a custom rule to enforce our standards.