concept StyleCop in category .net

appears as: StyleCop, StyleCop
Continuous Integration in .NET

This is an excerpt from Manning's book Continuous Integration in .NET.

8.2. Analyzing C# with StyleCop

StyleCop is a static code-analysis tool that works with the actual C# source code, rather than assemblies. It checks for things like class, variable, and namespace naming; maintainability, readability, spacing, documentation, and ordering. Unfortunately, if you’re a VB.NET or F# developer, you’re out of luck, because StyleCop supports only C#.

StyleCop is a useful and complementary tool to FxCop. Together they’ll guard your code cleanliness like watchdogs. But beware! You may get into a clinch with those two tools. If you run two conflicting rules, one on your C# code and one on the intermediate language it produces, the issue will be difficult to fix. Keeping this in mind, let’s make StyleCop work.

If you’re using MSBuild as your build platform, you can use the StyleCopTask that comes with StyleCop. The usage isn’t complicated.

Listing 8.2. MSBuild project for StyleCop analysis
<Project DefaultTargets="Analyze;" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <UsingTask AssemblyFile="tools\StyleCop\Microsoft.StyleCop.dll" TaskName="StyleCopTask"/> <Target Name="Analyze"> <CreateItem Include="**\*.cs"> <Output TaskParameter="Include" ItemName="StyleCopFiles"/> </CreateItem> <StyleCopTask ProjectFullPath="$(MSBuildProjectFile)" SourceFiles="@(StyleCopFiles)" ForceFullAnalysis="true" TreatErrorsAsWarnings="false" OutputFile="StyleCopReport.xml" CacheResults="true" /> </Target> </Project>

To use the task that comes with StyleCop, you first have to import it. It takes the list of .cs files as input and produces a StyleCopReport.xml file.

Unfortunately, CCNet doesn’t come with a good XSL transformer for StyleCop. A better StyleCopReport.xsl file is provided with this book; copy it to the dashboard/ xsl folder on the CCNet server, and add this line to the <buildPlugins> tag in the d=Dashboard.config file:

8.2.1. Using StyleCop

StyleCop is a separate product that you need to download on its own (http://code.msdn.microsoft.com/sourceanalysis). It’s installed as a Visual Studio plug-in. Don’t forget to install the MSBuild files; you’ll use them to work with CCNet and TeamCity.

After installation, StyleCop is available from the Tools menu in Visual Studio. Let’s start with the settings. Choose StyleCop Settings from the project’s context menu in Solution Explorer. A window opens, like the one shown in figure 8.10.

Figure 8.10. You can choose which StyleCop rules to enforce on your project.

You can turn the rules to be used on and off by selecting the check boxes. When you’re finished, look inside the project folder. You’ll find a new file: Settings.Style-Cop. It’ll control how StyleCop performs on your local Visual Studio project or later on the server.