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 (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.
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
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:
You can read more about the StyleCop categories and their respective rules in the StyleCop rules documentation at bit.ly/191GgiQ.
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:
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:
The next step is to configure your build controller to use these assemblies. To do so:
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.
Here are some considerations of which to be aware:
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 CustomTemplate.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.
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.
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
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
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.TeamFoundation.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
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
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
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.
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.
More MSDN Magazine Blog entries >
Browse All MSDN Magazines
Subscribe to MSDN Flash newsletter
Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.