October 2013

Volume 28 Number 10

ALM Rangers - Implementing Static Code Analysis with StyleCop

By Hamid Shahid | October 2013

How often have you encountered code that’s incomprehensible? Usually, it’s inconsistent formatting, invalid comments and lack of naming conventions that make code unreadable. Such inconsistencies are often overlooked as petty anomalies, but they can make a big difference in the overall maintainability of code.

StyleCop is a great tool to maintain style and format consistency in your source code. Like Visual Studio Code Analysis, StyleCop performs static code analysis. However, unlike Visual Studio Code Analysis, it scans through source code files rather than managed code. Moreover, StyleCop only validates for style inconsistencies and doesn’t perform code optimization and performance checks.

In this article, I’ll introduce StyleCop, show you how it works and discuss what factors you should consider when adopting it in your project. Finally, I’ll demonstrate how to include StyleCop execution in your Visual Studio Team Foundation Server (TFS) build.

StyleCop Essentials

StyleCop (stylecop.codeplex.com) is an open source tool that performs static code analysis on C# source files. It’s integrated with Visual Studio and appears in the context menu, giving you the option to scan the current file or any selected files or projects. Figure 1 shows StyleCop options available on the context menu for a Visual Studio project.

StyleCop Context Menu Options
Figure 1 StyleCop Context Menu Options

When you select the Run StyleCop or the Run StyleCop (Rescan All) option, StyleCop parses all the C# files and validates them for the designated StyleCop rules. If there are violations, a warning appears in the Error List window. 

The StyleCop Settings File This is where StyleCop keeps all its configuration options. This file contains information such as selected rules; vocabulary information such as custom words or acronyms; and whether to merge the settings file with the settings file in the parent directories, if there are any.

Given that StyleCop recursively looks for the settings file in the source file’s parent directory, it’s a best practice to keep a single version of the Settings.StyleCop file. Maintaining one file and storing it at the root of the team project ensures you use the same set of rules across the whole team project.

Custom Dictionary File In addition to allowing adding words and acronyms to the Settings file, StyleCop also works with a CustomDictionary.xml file that uses the same format as the Visual Studio Code Analysis dictionary. This lets you use the same dictionary file for both. Figure 2displays the format of the dictionary file.

Figure 2 The Custom Dictionary File

<Dictionary>
  <Words>
    <Unrecognized>
      <Word/>
    </Unrecognized>
    <Recognized>
      <Word/>
    </Recognized>
    <Deprecated>
      <Term PreferredAlternate=""/>
    </Deprecated>
    <Compound>
      <Term CompoundAlternate=""/>
    </Compound>
    <DiscreteExceptions>
      <Term />
    </DiscreteExceptions>
  </Words>
  <Acronyms>
    <CastingException>
      <Acronym />
    </CastingException>
  </Acronyms>
</Dictionary>

Having explained the purpose and basics of StyleCop, I’ll now go through what’s involved in making it an integral part of your development team’s working practice.

StyleCop Rules This is a check that StyleCop performs on a code file. There are a number of rules available out of the box, and you have the option of writing your own custom rules if you wish. The StyleCop wiki details how to write your own StyleCop rules (see bit.ly/12P665L).

The first step in using StyleCop is deciding which StyleCop rules to use. I strongly advise using all the StyleCop rules. However, development teams often have their own coding standards, and there might be a strong push-back on the adoption of certain StyleCop rules. You have to balance the long-term benefits of consistently styled, maintainable code against the small inconvenience it might cause. Like so many good practices, once you get into the habit of using StyleCop, it becomes second nature. In any case, it’s essential to agree on the StyleCop rules your team will use across the board.

StyleCop rules fall in the following seven categories:

  1. Documentation Rules: Validate the suitability of documentation elements in the source files.
  2. Layout Rules: Validate layout and line spacing in the source files.
  3. Maintainability Rules: Validate the source files for maintainability aspects such as an unwanted parenthesis or the existence of multiple classes in a single file.
  4. Naming Rules: Validate the substitutability of method and variable names.
  5. Ordering Rules: Validate the code content is ordered correctly.
  6. Readability Rules: Validate the code is properly formatted and readable.
  7. Spacing Rules: Validate the spacing in the code content is valid and appropriate.

You can read more about the StyleCop categories and their respective rules in the StyleCop rules documentation at bit.ly/191GgiQ.

Adding StyleCop to Your Team Build

It’s all well and good to have StyleCop rules selected and stored in a settings file, but the only way to ensure StyleCop is executed consistently for all source code is to run it as part of the build process.

There are two ways to do this:

  1. Integrate StyleCop with the C# project’s MSBuild file so that it’s executed whenever the project is compiled. The StyleCop documentation (bit.ly/13ZX2xL) describes how to do so.
  2. Add StyleCop to your continuous integration Team Build so that it’s executed for every check-in.

I’ll explain how to run StyleCop in your continuous integration Team Build. If you’re using gated builds, executing StyleCop will ensure any code files with violations aren’t checked in. If not used in gated builds, the broken build will still prompt you to fix the violations when you check in code.

In order to run StyleCop in Team Build, the process must be invoked from an activity in the build workflow. I’ll use the StyleCop activity from an open source project called Community TFS Build Extensions (tfsbuildextensions.codeplex.com). The Community TFS Build Extensions is a set of libraries containing a number of reusable workflow activities that you can simply drag and drop into your Team Build process template.

Build Controller Changes The first thing you need to do before customizing the Team Build is set the custom assemblies path of your build controller. This is the location from where the build agents load assemblies for any custom activities they find in the build workflow.

To add custom assemblies, create a new folder at an appropriate location in your Team Project. I named the new folder Custom Assemblies and created it below the BuildProcessTemplate just below the Team Project root folder. Now, check in the following assemblies:

  • StyleCop.dll
  • StyleCop.CSharp.dll
  • StyleCop.CSharp.Rules.dll
  • TFSBuildExtensions.Activities.dll
  • TFSBuildExtensions.Activities.StyleCop.dll

The next step is to configure your build controller to use these assemblies. To do so:

  1. Click on the build link in Team Explorer. Click Actions and select Manage Build Controllers.
  2. From the dialog box that appears, select your build controller and click on the Properties button.
  3. In the Build Controller Properties dialog box, set the “Version control path to custom assemblies” property to the Custom Assemblies folder that was created earlier in the Team Project, as shown in Figure 3.

Build Controller Properties
Figure 3 Build Controller Properties

Click OK and close the properties dialog box. At this point, the build controller is configured to load your custom activities. The next step is to customize your build’s template.

StyleCop Considerations

Here are some considerations of which to be aware:

  • Unlike Visual Studio Code Analysis, StyleCop doesn’t support Visual Basic .NET and can only be used for source files written in C#.
  • At the time of writing this article, StyleCop wasn’t yet available for Visual Studio 2013.
  • The Hosted Build Controller is a build controller hosted in the cloud by Visual Studio Team Foundation Service. The steps to configure this build controller are the same if you’re using an on-premises build server.
  • This article used Team Foundation Server (TFS) 2012. The steps are the same for TFS 2010 and TFS 2013. Make sure you’re using the correct version of TFS Build Extensions.

Custom Build Templates

For every new Team Project, TFS creates a number of build templates out of the box. These build templates are created in a folder called ProcessBuildTemplates that resides at the root of the Team Project. Start by taking a copy of the DefaultTemplate.11.1.xaml template and customizing it to add the StyleCop activity. I created a copy of the file DefaultTemplate.11.1.xaml and renamed it CustomTemplate.xaml.

To customize the build workflow, you’ll need to add the custom activities to your development environment. To do so, create a new workflow activity library project in Visual Studio. In the Add New Project dialog, make sure the Microsoft .NET Framework 4.5 is selected as the target platform. The next step is to add a link to the file CustomTem­plate.xaml in the newly created project. To do that, right-click on the project, select Add Existing Item, browse to the file CustomTemplate.xml and click the Add as Link button.

The last step in setting up your development environment is to add the StyleCop activity in the Toolbox window for allowing drag-and-drop. To do so, right-click the area below “activities” in your Toolbox window and select the option Add Tab. Name the new tab “TFS Build Extensions.” Right-click the tab name and select “Choose items.” Browse to the assembly TfsBuildExtensions.Activities.Stylecop.dll and click OK. You can now open the CustomTemplate.xaml file and drag the StyleCop activity on to it.

Build Template Customization You should run StyleCop early in the build process. This allows the build to fail quickly if any violations are encountered. Because StyleCop requires the source files to scan, the first place where StyleCop can be executed is after the Initialize Workspace sequence within the Run On Agent sequence, as shown in Figure 4.

StyleCop Activity Drop Location
Figure 4 StyleCop Activity Drop Location

Having determined the appropriate location in the build workflow to add StyleCop activity, the next step is to add a sequence activity. Rename the sequence activity to Run StyleCop. The final listing of my Run StyleCop sequence is shown in Figure 5.

The Run StyleCop Sequence
Figure 5 The Run StyleCop Sequence

Code Walk-ThroughFigure 6 details the variables defined in the Run StyleCop sequence, their types and their respective purposes.

Figure 6 Variables Defined in Run StyleCop Sequence

Variable Name Type Description
SourceCodeFiles IEnumerable<String> Stores the names of all files to be scanned by StyleCop.
IsSuccess Boolean Stores whether the StyleCop activity found any violations.
ViolationCount Int32 Stores the count of StyleCop violations.

The workflow also contains a parameter called StyleCopSettingsFile of type String that stores the path of the StyleCop settings file.

The first activity in the Run StyleCop sequence is the FindMatchingFiles activity. The activity is contained in the Microsoft.TeamFoundation.Build.Workflow.dll assembly and returns the list of all files matching the given file pattern. Figure 7 describes how the properties of this activity are set.

Figure 7 FindMatchingFiles Activity Properties

Property Name Value
DisplayName FindMatchingFiles
IsSuccess String.Format(“{0}\**\*.cs”, BuildDirectory)
Result SourceCodeFiles

The activity is passed the pattern of finding all C# (*.cs) files in the Build Directory, and it returns the result in the SourceCodeFiles enumeration.

The next activity in the sequence is the ConvertWorkspaceItem activity, which resides in the assembly Microsoft.TeamFounda­tion.Build.Workflow.Activities.dll. The activity converts the server path of the given StyleCop Settings file—passed as a parameter—to a local path on the build server. The properties of this activity are shown in Figure 8.

Figure 8 Get Local Settings File Properties

Property Name Value
Direction ServerToLocal
DisplayName Get Local Settings File
Input StyleCopSettingsFile
Result StyleCopSettingsFileLocalPath
Workspace Workspace

Now that the source file names are retrieved and the location of the StyleCop settings is established, the next activity in the Run StyleCop sequence is the StyleCop activity. Figure 9 displays how the properties of the StyleCop activity are set.

Figure 9 Execute StyleCop Properties

Property Name Value
DisplayName Execute StyleCop
LogExceptionStack True
SettingsFile StyleCopSettingsFile
ShowOutput True
SourceFiles SourceCodeFiles.ToArray()
Result StyleCopSettingsFileLocalPath
Succeeded IsSuccess
TreatWarningsAsErrors True

The activity takes the enumeration SourceCodeFiles—converted to an array—as input and returns the result and violation counts in the IsSuccess and ViolationCount variables, respectively. It’s given the display name Execute StyleCop and is set to treat warnings as errors and to fail the build if any errors are encountered.

The final activity in the Run StyleCop sequence is the Write Build Message activity. The activity is set to display the result and violations count. Figure 10 displays how the properties of this activity are set.

Figure 10 Write Build Message Activity Properties

Property Name Value
DisplayName Completion Message
Importance Microsoft.TeamFoundation.Build.Client.BuildMessageImportance.Normal
Message String.Format(“StyleCop was completed with {0} violations”, StyleCopViolationsCount)

Your Custom build template is now ready for use. Save and check in the file CustomTemplate.xaml. To use the new build template, open your build definition, click process, expand Build Process Template and click the New button. In the New Process Template dialog box that’s shown, select the option “Select an existing XAML file” and browse to the CustomTemplate.xaml file.

Set the value of parameter StyleCopSettingsFile to the location of your Settings.StyleCop file. Click Save to save the build definition. Your build with StyleCop is now ready for use. It’s best to use this build template for your gated builds. This will ensure none of the source files checked in have any StyleCop violations.

Next Steps

I’ve demonstrated how you can use StyleCop to enforce static code analysis in your Team Build. Static code analysis promotes better coding standards, and it can run in your Team Build to ensure all checked-in code adheres to your standards. You can similarly enforce other best practices in your Team Build. Microsoft ALM Rangers have produced a number of useful build templates that you can use in the Team Foundation Build Customization Guide (vsarbuildguide.codeplex.com) project. Moreover, you have the option of writing your own activities or using the activities available in the Community TFS Build Extensions project.


Hamid Shahid is a Microsoft ALM Ranger and an independent consultant with more than 12 years of experience designing and developing enterprise software. He has keen interest in promoting best practices in Microsoft ALM technologies. He can be reached via his blog at hamidshahid.blogspot.com and can be followed on Twitter at twitter.com/hamid_shahid.

THANKS to the following ALM Rangers and technical experts for reviewing this article: Mike Fourie (independent consultant), Willy-Peter Schaub (Microsoft) and Patricia Wagner (Microsoft)
Mike Fourie is an independent consultant with more than 13 years of software development experience who specializes in build and deployment automation. He’s a Microsoft ALM MVP and Distinguished ALM Ranger. He can be reached via his blog at freetodev.com. You can also follow him on Twitter at twitter.com/mikefourie.

Willy-Peter Schaub is a senior program manager with the Visual Studio ALM Rangers at the Microsoft Canada Development Center. Since the mid-’80s, he’s been striving for simplicity and maintainability in software engineering. Read his blog at blogs.msdn.com/b/willy-peter_schaub and follow him on Twitter at twitter.com/wpschaub.