How to Set Up StyleCop and Code Analysis on an Assembly

Coding style standards are a key essential to a team’s productivity. A well defined coding style paired with frequent peer reviews allow team members to swarm issues across multiple different modules where teams without those practices require individuals only solving problems in the modules they are accustomed to work in.

There is no doubt the effort required to manage a ubiquitous coding style grows exponentially as the team size increases. It also becomes harder to settle on a coding style, as each individual prefers certain styles over others. The decisions on style and managing style can be a daunting task. It would be asinine to rely on a single individual to be solely responsible for policing such a task; however, I have seen teams operate this way. It doesn’t have to be this way. Adopting and maintaining a coding style doesn’t have to be difficult, as there are many tools out there to assist teams in migrating towards establishing and maintaining a styled code base. A couple of months ago, Erik Dietrich wrote about the pitfalls of using a manual-only process for peer review, and how teams need to adopt tools into their day to day process to automate the peer reviewing for an increased code quality. One such tool to help solve this problem is StyleCop.

StyleCop integrates with Visual Studio, and provides a fully customizable, and reasonably-sized rule set for analyzing. Unlike its predecessor FxCop, StyleCop analyzes the actual source code instead of the compiled assembly object code, so a more thorough analysis can be obtained. StyleCop was originally developed by Microsoft. In 2010, Microsoft decided to make it open source and eventually stopped support for it. The open source community has since picked up its development. StyleCop integration now comes in a few different flavors, although it seems development is halting on all of them except the StyleCop.Analyzers project. This is the distribution my development team uses, the StyleCop.Analyzers project developed by Sam Harwell.

What’s great about StyleCop.Analyzers, is it is built right on top of Code Analysis, another tool I encourage my colleagues to use. Code Analysis options used to be rather buried in older versions of Visual Studio. In Visual Studio 2017, it is reasonably easy to get StyleCop and Code Analysis set up for a project. Let’s build a new C# project from scratch and take a look at what it can do.

Installing the StyleCop.Analyzers NuGet Package

I created a new project called CodingOnCaffeine in a new solution called CodingOnCaffeine. The first thing we need to do is install the StyleCop.Analyzers NuGet package. To do this, right-click the CodingOnCaffeine project in Solution Explorer, then click the Manage NuGet Packages… option in the context menu.

right click project - click manage nuget packages

The NuGet Package Manager will be displayed. From here, click the Browse option, and type “StyleCop.Analyzers” in the search box.

02 - click browse - type stylecop

Select the StyleCop.Analyzers package from the list, then click the Install button on the right side of the window.

03

The Visual Studio Output window should display something like the following during the installation process.


Attempting to gather dependency information for package 'StyleCop.Analyzers.1.0.2' with respect to project 'CodingOnCaffeine', targeting '.NETFramework,Version=v4.6.1'
Gathering dependency information took 144.06 ms
Attempting to resolve dependencies for package 'StyleCop.Analyzers.1.0.2' with DependencyBehavior 'Lowest'
Resolving dependency information took 0 ms
Resolving actions to install package 'StyleCop.Analyzers.1.0.2'
Resolved actions to install package 'StyleCop.Analyzers.1.0.2'
Retrieving package 'StyleCop.Analyzers 1.0.2' from 'nuget.org'.
GET https://api.nuget.org/v3-flatcontainer/stylecop.analyzers/1.0.2/stylecop.analyzers.1.0.2.nupkg
OK https://api.nuget.org/v3-flatcontainer/stylecop.analyzers/1.0.2/stylecop.analyzers.1.0.2.nupkg 118ms
Installing StyleCop.Analyzers 1.0.2.
Adding package 'StyleCop.Analyzers.1.0.2', which only has tools group, to project 'CodingOnCaffeine'
Adding package 'StyleCop.Analyzers.1.0.2' to folder 'C:\Users\jason\source\repos\CodingOnCaffeine\packages'
Added package 'StyleCop.Analyzers.1.0.2' to folder 'C:\Users\jason\source\repos\CodingOnCaffeine\packages'
Added package 'StyleCop.Analyzers.1.0.2' to 'packages.config'
Executing script file 'C:\Users\jason\source\repos\CodingOnCaffeine\packages\StyleCop.Analyzers.1.0.2\tools\install.ps1'...
Successfully installed 'StyleCop.Analyzers 1.0.2' to CodingOnCaffeine
Executing nuget actions took 5.01 sec
Time Elapsed: 00:00:05.3422233
========== Finished ==========

Once the install is completed, you can now go back to Solution Explorer, expand CodingOnCaffeine Project -> References -> Analyzers -> StyleCop Analyzers to see a complete list of rules that are now being enforced on the code base. In this view, you can even customize the severity, or completely turn off individual rules to accommodate your team’s style. I wouldn’t recommend doing this, however, until you have selected the set of Code Analysis rules you wish to target in the project.

04

At this point, the autogenerated Class1.cs file that was added to our CodingOnCaffeine project by default lights up with some green squiggly notifications, and our Error List window also populates with numerous StyleCop (SA) warnings.

05

These will be easy to fix, but we will save that exercise for a little later in this post. There are a couple more things that need to be done to make sure Code Analysis and StyleCop are ran on the project when the solution is built.

Setting Up Code Analysis to Run on Build

Right-click the project again in Solution Explorer. This time click the Properties context menu option. On the project properties view, select the Code Analysis option. You’ll want to select the build configurations and platforms you’ll run Code Analysis on at build time. I’ve selected All Configurations (Release and Debug) for the Any CPU platform. Check the Enable Code Analysis on Build checkbox, and select the set of rules you will run for Code Analysis. Although I recommend getting familiar with using the Mirosoft All Rules rule set, for this example I’ve chosen the Microsoft Managed Recommended Rules rule set.

11

The next section will cover customizing the rules with a json settings file.

Customizing StyleCop with the stylecop.json Settings File

The StyleCop.Analyzers addon provides a convenient way to add a stylecop.json file to the project. Hover over one of the green squiggle notifications in Class1.cs to get a Light Bulb context menu. Expand it and click the Add StyleCop settings file to the project menu option.
08
A stylecop.json file is added to the project, with the following contents:

{
  // ACTION REQUIRED: This file was automatically added to your project, but it
  // will not take effect until additional steps are taken to enable it. See the
  // following page for additional information:
  //
  // https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/EnableConfiguration.md

  "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
  "settings": {
    "documentationRules": {
      "companyName": "PlaceholderCompany"
    }
  }
}

The file allows teams to customize StyleCop’s settings to accommodate their own specific needs and styles. The documentation for this file can be found on StyleCop’s github. For now, we will just keep the default settings, which will enforce having “PlaceholderCompany” as the company name in our file headers.

Fixing StyleCop Warnings

If we go back to Class1.cs, we can start to fix the warnings listed in the Error List. For the SA1200 Using directive must appear within a namespace declaration warning, let’s move all the using statements inside the namespace CodingOnCaffeine. Next, we can add a file header to the file by hovering over the green squiggle notification, expanding the Light Bulb context menu and selecting the Add File Header menu option.

09

Notice the “PlaceholderCompany” is inserted to the header as the company name. If the header does not contain “PlaceholderCompany” as the company, a StyleCop warning will be generated.

At this point, we should only have one StyleCop warning left for Class1.cs, regarding enabling XML output. This is done through project properties. So once again, right-click the project and click Properties from the context menu. Navigate to the Build page, and for All Configurations make sure the XML documentation file option is checked.

10

Note that this caused two more StyleCop warnings to appear for Class1.cs in the Error List! Both of these are related to documenting the class with XML comments. Yes, StyleCop will even force documentation! Let’s type up a quick summary so StyleCop is satisfied.

 /// <summary>
 /// Defines a class used for testing StyleCop compliance.
 /// </summary>
 public class Class1
 {
 }

Finally, Class1.cs is StyleCop compliant. However it looks like AssemblyInfo.cs has a warning about a missing file header. Let’s use the same technique there and insert a header in that file as well. Now let’s do a rebuild. Should be squeaky clean with no warnings. Nice!

Conclusion

Because of its fluid integration with Visual Studio and the build process, StyleCop is a great tool for teams to utilize when they are looking for a way to automate code style enforcement. Tools like StyleCop and Code Analysis can be fully customized to accommodate a team’s style preferences. I hope this article was helpful in getting your team started on adopting and enforcing code styles through StyleCop.

Advertisements