Using StyleCop With Visual Studio Express

StyleCop is a tool that enforces specific formatting guidelines on C# source code. Originally written by Microsoft for internal use, it has now been given to the programming community to maintain. StyleCop is not designed to find bugs in your software like FxCop (which will be covered in a later post). However, it will tend to force your code to be more readable, which makes it easier for you to find bugs and maintain your code. This is especially true when sharing your code with other programmers. Everybody tends to have different code formatting styles and they can each argue the merits of their own style. StyleCop is a set of standards that, when used, keep everybody on the same page.

Installation and Setup


The following instruction have been tested on Visual Studio 2010 and 2012 Express Editions but should work on all editions of Visual Studio 2008 and up.

1)  Download the latest version of StyleCop from stylecop.codeplex.com.

2)  Install StyleCop with the default settings.

3)  Navigate to any existing project that you wish to run StyleCop on or create a new Visual Studio project.

4)  Find the .csproj file (usually located at <Solution Name>\<Project Name>\<Project Name>.csproj) and open it in a text editor.

5)  Locate the existing <Import Project="..." ... > tags and add the following line after the <Import> tags:
<Import Project="$(ProgramFiles)\MSBuild\StyleCop\v4.7\StyleCop.targets" />

6)  Save the .csproj file and open the project in Visual Studio.

Unfortunately, steps 4-6 will need to be repeated on each project that will use StyleCop.

Usage


Compiling the project will now run StyleCop and show the results in the output window. Just like compilation errors and warnings, each StyleCop infraction can be double-clicked to take you to the offending code. There are also error codes (e.g. SA1600) that can be used to find more information online.




2 comments:

  1. Thanks for this - can't wait to get thousands of violation warnings. :P

    ReplyDelete
  2. Ha. It definitely helps if this is enabled at the start of a project. Cleaning up an existing project to match Microsoft's style guidelines can take quite awhile.

    ReplyDelete