A Code Quality Story – Using Code Analysis with Microsoft Rules

I wrote this article to help others and share my tech knowledge solutions using Visual Studio Enterprise 2017 test frameworks.

Running Code Analysis on your Visual Studio solution can help you discover issues before it is released. Code Analysis references “Rules” that can help catch bad design, unsecured code, spelling, and other violations. You can run this analysis on an as-needed basis or on every build (can be annoying). It’s also important to remember that EACH project in a solution has its own Code Analysis configuration. Also, a team leader can enforce check-in policies on developer work ensuring proper code analysis using the Microsoft TFS.

Note: This article keeps it simple and old school by using the Visual Studio built-in FxCop for Code Analysis.


Let’s dive in and get started with a Story.

Madame Future Seer decided to make a simple Fortune Teller program [Visual Studio Solution Here]. In a rush to deliver and showcase her product for release, she did not take time to test or inspect her code for problems. It compiled without errors, right? She manually tested all different user input scenarios (great job!) so why should she care about running Code Analysis on her project?

 

Let’s see and take a look at what could be problems…

She loads her project into Visual Studio Enterprise 2017:

Madame opens up her project properties (she only has one project in her solution, if she had more, she would configure each project) and clicks on the Code Analysis group. She selects the Rule Set “Microsoft All Rules”. Because she thinks it is annoying to see the Code Analysis results on every Build, she leaves that box unchecked and continues to suppress code analysis on auto generated code (of which she has no control over).

Madame was curious to discover what Rules Microsoft came up with to help her write better code, so she clicked “Open” to discover categories of rules like design, style, usage, and much more!

The next step after setup was to run Code Analysis by:

Menu –> Analyze –> Run Code Analysis –> On Solution

To her surprise there were 33 Violations! Maybe she should had enabled that Code Analysis when she was developing, and building her original Fortune Teller Console program in the first place? How bad could these violations be? Should she care? Would it affect her users and their fortune results?

Madame reads and investigates the violations, which were flagged as “warnings”. Clicking on the item opens up the MSDN article for the error or warning.

Let’s look at the first item on her list.

CA2210: Assemblies should have valid strong names:

The strong name protects clients from unknowingly loading an assembly that has been tampered with. Assemblies without strong names should not be deployed outside very limited scenarios. If you share or distribute assemblies that are not correctly signed, the assembly can be tampered with, the common language runtime might not load the assembly, or the user might have to disable verification on his or her computer.

Problem: It’s very important for her users to TRUST her Fortune Teller Console program!

Solution: Madame will definitely follow the guidelines to strongly name her Assembly and the MSDN article guides her on how to do it.

Let’s see what is next on her list!

CA1801: Review unused parameters

This warning pointed to a line of code where she clicked and saw it was the standard input argument parameters.

Problem: Madame did not think this was a major problem. In fact, she thought, hmm, maybe someday I will add a new feature to allow my users to bypass the main menu and get their fortune results ASAP simply by passing a few command arguments. But that was too far out in the future that Madame Seer could not See when she would have time to do it. So, what could she do to make this warning out of her Sight!?

Solution: Madame decides she is OK with not seeing this rule applied in her Code Analysis results window. There are a few options she could take to get rid of the problem and we’ll discuss that now.

Option 1: Suppress in Source

Code analysis warnings can be suppressed using SuppressMessage attribute in the code but only in the local scope of code to where it occurred.

In the Code Analysis violations window, Madame could right-click on the violation she would like to Suppress and do this:

Menu > “Actions” > Suppress Message > In Source

An Attribute custom to her scope of code and the Rule violation is added:

[System.Diagnostics.CodeAnalysis.SuppressMessage(“Microsoft.Usage”, “CA1801:ReviewUnusedParameters”, MessageId = “args”)]

Madame Seer, thought this was a great idea on how not to See these pesky violations, but she suffered from programmer’s OCD so she just could not stand to See all those attributes in her precious source code. There had to be an alternate method to hide the Rule violation.

Option 2: Suppress in Suppression File

The next option would to store the SuppressMessage attributes in a separate code file that would be in the assembly level.

In the Code Analysis violations window, Madame could right-click on the violation she would like to Suppress and do this:

Menu > “Actions” > Suppress Message > In Suppression File

It created a new source code file called GlobalSuppressions.cs for her project and very visible in her Solution Explorer.

Madame double-clicked on the file and found a new attribute was added:

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(“Microsoft.Usage”, “CA1801:ReviewUnusedParameters”, MessageId = “args”, Scope = “member”, Target = “FortuneTellerMadlib.Program.#Main(System.String[])”)]

Madame Seer liked that the suppression attributes were out of Sight and that her original source code for her program was back to normal. It was looking like how she coded it, without the generated attributes in her code, and all the Suppress attributes were nicely organized in one place and one file.

But something continued to bother her as she starred at the newly created source code file called “GlobalSuppressions.cs” that was visible in her Solution Explorer. Fear of complacency drove her to ask the question, “Could she do better?”. Could she do something else that would get rid of that file all together or reduce its contents to only Rule violations she cared deeply about?

Her eyes looked into her crystal ball where a cloudy image of another Code Analysis technique magically appeared. That’s It! She could create her own Rules set by taking the Microsoft Rules set, editing what Rules she cared to see, and making her own Code Analysis.

Option 3: Create new Rules set and Disable Warning

Madame once again opened her Project properties to the Code Analysis group. She then clicked “Open” Open the rules Set. Her crystal ball guided her to search on the pesky warning ID and then change the Rule action from Warning to None so that in the future Code Analysis this Rule would be ignored.

Clicking Save she found that a new Rule set was created just for her Fortune Teller Console program. Her crystal ball informed her that she could apply this Rule set to other projects in the future for her own personalized Code Analysis!


Every story has a happy ending. Madame Seer tackled all the items from her Code Analysis results, suppressed some warnings in her project, and created a custom company Rules set “Fortune Seer Enterprises” for her own preferences. She released her Fortune Teller Console program to her fans and made a fortune while her program users got theirs.