Saturday 14 November 2009

All About StyleCop

To download StyleCop click here.

If you use Resharper, you can configure it to use StyleCop rules; click here to download.

To know more about setting up StyleCop with MSBuild integration click here.

Run StyleCop Automatically After a Project Build:
  1. Add all StyleCop files into your solution

1.1. Create a new folder called “Lib” inside your solution directory

1.2. From %Program Files%\MSBuild\Microsoft\StyleCop Copy all files to your “Lib” directory:

image

Why would you do that:

The reason you should copy the files into your solution is that:

  • You may want to customize the default StyleCop violation rules for your specific solution using Settings.StyleCop file
  • Other developers who would like to benefit from StyleCop, won’t need to install StyleCop locally. They can get the latest version from source control such as MSS or TFS

2. Open your project file(e.g. myProject.csproj) and import StyleCop project into it

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
...
<Import Project="$(SolutionDir)\Lib\StyleCop\v4.4\Microsoft.StyleCop.targets" />
...
</Project>

If you don't want to copy the file in your solution, you can point to the default location which is:

$(MSBuildExtensionsPath32)\Microsoft\StyleCop\v4.4\Microsoft.StyleCop.targets

Another way is to use this environmental variable: Project="$(MSBuildStyleCop)". This way, it will look at where your StyleCop has been installed in Windows.

Set Violations as Errors:

By default when StyleCop runs it gives you the violations as Warnings:
image

You can set the violations to appear as Errors:
  1. Open your project file in notepad e.g. myProject.csproj
  2. Add StyleCopTreatErrorsAsWarnings to the Debug PropertyGroup tag:

    <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    ...
    <StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings>
    </PropertyGroup>
    Then you will get violations as errors:
image

Customize StyleCop Violation Rules For Your Solution:

  1. Locate Settings.StyleCop file and double click on it
  2. Check or uncheck a rule

image

1 comment:

Sanjay said...

Hi,

Is it possible to set individual StyleCop rule as Error or Warning. My requirement is not to set all the rules either as Errors or Warnings. I want some rules should always appear as Errors.

Thanks in advance