How to Create StyleCop Custom Rule

This article gives simple step-by-step guide which could be useful for learning how to create own StyleCop rules.

Consider downloading the complete Visual Studio project if needed.

Step 1. Create a project

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

1.png

Step 2. Add references

Add references to the following binaries (can be found in StyleCop installation folder):
  • StyleCop
  • StyleCop.CSharp

2.png

Step 3. Add analyzer class

After adding references, create a new class for StyleCop analyzer.

3.png

Analyzer could be understood as an "engine" containing several rules with similar behavior.
There could be several analyzers in one custom rules assembly.

Put the following code into your analyzer class:

using StyleCop;
using StyleCop.CSharp;

namespace MyCustomRules
{
	/// <summary>
	/// Custom analyzer for demo purposes.
	/// </summary>
	[SourceAnalyzer(typeof(CsParser))]
	public class MyCustomAnalyzer : SourceAnalyzer
	{
		/// <summary>
		/// Extremely simple analyzer for demo purposes.
		/// </summary>
		public override void AnalyzeDocument(CodeDocument document)
		{
			CsDocument doc = (CsDocument)document;

			// skipping wrong or auto-generated documents
			if (doc.RootElement == null || doc.RootElement.Generated)
				return;

			// check all class entries
			doc.WalkDocument(CheckClasses);
		}

		/// <summary>
		/// Checks whether specified element conforms custom rule CR0001.
		/// </summary>
		private bool CheckClasses(
			CsElement element,
			CsElement parentElement,
			object context)
		{
			// if current element is not a class then continue walking
			if (element.ElementType != ElementType.Class)
				return true;

			// check whether class name contains "a" letter
			Class classElement = (Class)element;
			if (classElement.Declaration.Name.Contains("a"))
			{
				// add violation
				// (note how custom message arguments could be used)
				AddViolation(
					classElement,
					classElement.Location,
					"AvoidUsingAInClassNames",
					classElement.FriendlyTypeText);
			}

			// continue walking in order to find all classes in file
			return true;
		}
	}
}

Step 4. Add analyzer definition file

Each analyzer should be provided with an XML file containing rule definition.
Create a new XML file:
  • named exactly as analyzer class
  • specify build action as "Embedded Resource"

4.png

Put the following content into your analyzer definition file:

<?xml version="1.0" encoding="utf-8" ?>
<SourceAnalyzer Name="My Custom Rule">
	<Description>
		Custom rule for demo purposes.
	</Description>
	<Rules>
		<Rule Name="AvoidUsingAInClassNames" CheckId="CR0001">
			<Context>Do not use 'a' letter in {0} names.</Context>
			<Description>Fires when 'a' letter is used in class name.</Description>
		</Rule>
	</Rules>
</SourceAnalyzer>

Step 5. Build and deploy

You custom rules are almost ready.
Build the library, and copy output file to the StyleCop installation directory.

5.png

Step 6. Check how it works

Exit Visual Studio and run it again.
Now your custom rules should be loaded and could be seen in StyleCop settings editor.

6.png

You can also make sure that rules are actually executed.

7.png

Last edited Mar 18, 2012 at 5:28 PM by shuruev, version 8

Comments

MAK1987 Jun 10 at 5:42 AM 
Hi,

I have implemented custom rules for few of my company defined standards when it comes to namespace or methods or class.

However i have a requirement something like, a custom rule should warn user when
Code contains commenting like “/../”
Code Contains a //TODO statement.
Have anyone implemented it or anybody can guide me on the same?

NickyPhun Jul 12, 2012 at 5:43 AM 
Hi! i am using C# Visual 2010 Express, however i tried the step on above, the custom rules doesn't show on the Stylecop V4.7 Setting List, even i changed the XML to embeded. kindly advice is there any other ways to resolve this?

shuruev Apr 4, 2012 at 6:21 AM 
For now, yes that is true.

savirpe Apr 3, 2012 at 9:47 AM 
Hi ! It seems that it works only with .NET 3.5 not 4.0 ?