Visual Studio 2013 Static Code Analysis in depth: What? When and How?

In this post I'll illustrate in details the following points


What is static code analysis?

Static Code Analysis feature of Visual Studio performs static code analysis on code to help developers identify potential design, globalization, interoperability, performance, security, and a lot of other categories of potential problems according to Microsoft's rules that mainly targets best practices in writing code, and there is a large set of those rules included with Visual Studio grouped into different categorized targeting specific coding issues like security, design, Interoperability, globalizations and others.

Static here means analyzing the source code without executing it and this type of analysis can be performed through automated tools (like Visual Studio 2013 Code Analysis Tool) or manually through Code Review which already supported in Visual Studio 2012 and 2013 (check Using Code Review to Improve Quality video on Channel9)

There is also Dynamic analysis which performed on executing programs using software testing techniques such as Code Coverage for example.

When to use?

Running Code analysis tool at regular intervals during your development process can enhance the quality of your software, examines your code for a set of common defects and violations is always a good programming practice.

Adding that Code analysis can also find defects in your code that are difficult to discover through testing allowing you to achieve first level quality gate for you application during development phase before you release it to the testing team.

Supported platforms

  • .NET Framework, native (C and C++)
  • Database applications.

Support Visual Studio versions

  • All version of Visual Studio starting Visual Studio 2013 (except Visual Studio Test Professional) check Feature comparisons
  • Create and modify a custom rule set required Visual Studio Premium or Ultimate.

How to use?

Code Analysis can be run manually at any time from within the Visual Studio IDE, or even setup to automatically run as part of a Team Build or check-in policy for Team Foundation Server.

Run Code Analysis Manually

  • To run code analysis manually on a project, on the Analyze menu, click Run Code Analysis on your project or simply right click on the project name on the Solution Explorer choose Run Code Analysis from the context menu

clip_image002

clip_image004

Run Code Analysis Automatically

  • To run code analysis each time that you build a project, you select Enable Code Analysis on Build on the project's Property Page

clip_image006

Run Code Analysis while check-in source code to TFS version control (TFSVC)

  • Team Foundation Version Control (TFVC) provides a way for organizations to enforce practices that lead to better code and more efficient group development through Check-in policies which are rules that are set at the team project level and enforced on developer computers before code is allowed to be checked in. (This is available only if you're using Team Foundation Server)
  • Require permissions on Team Foundation Server: you must have the Edit project-level information permission set to Allow typically your account must be part of Project Administrators, Project Collection Administrators, for more information about Team Foundation permissions check https://msdn.microsoft.com/en-us/library/ms252587(v=vs.120).aspx
  • In Team Explorer, right-click the team project name, point to Team Project Settings, and then click Source Control.
  • In the Source Control dialog box, select the Check-in Policy tab.
  • Click Add to create a new check-in policy.
  • Double-click the existing Code Analysis item in the Policy Type list to change the policy.

clip_image008

  • Check or Uncheck the policy option based on the configurations you need to perform as illustrated below:
    • Enforce check-in to only contain files that are part of current solution: code analysis can run only on files specified in solution and project configuration files. This policy guarantees that all code that is part of a solution is analyzed.
    • Enforce C/C++ Code Analysis (/analyze) : Requires that all C or C++ projects be built with the /analyze compiler option to run code analysis before they can be checked in.
    • Enforce Code Analysis for Managed Code: Requires that all managed projects run code analysis and build before they can be checked in.

Check Code analysis rule set reference on MSDN

clip_image010

  • What is Rule Set? Rule Set is a group of code analysis rules like the example below where Microsoft.Design is the rule set name where "Do not declare static members on generic types" is the code analysis rule

clip_image011[4]

  • Once you configured the Analysis rule the policy will be enabled for all the team member in this project whenever a team member check-in any source code to the TFSVC the policy section will highlight the Code Analysis policy as below

clip_image013

Run Code Analysis as part of Team Build

  • With Team Foundation Build (TFBuild), you can create and manage build processes that automatically compile and test your applications, and perform other important functions.
  • Code Analysis can be enabled in the Build Definition file by selecting the correct value for the build process parameter "Perform Code Analysis"

clip_image015

  • Once configure, Kick-off your build definition to queue a new build, Code Analysis will run as part of build workflow and you will be able to see code analysis warning as part of build report

clip_image017

Understand the Code Analysis results & learn how to fix them

Now after you went through Code Analysis configurations and the different ways of running it, we will go through the Code Analysis result how to understand them and how to resolve them.

Code Analysis window in Visual Studio will show all the analysis results based on the rule sets you configured in the project file properties, let's dig deep into what each result item contains:

clip_image019

1

Check ID

The unique identifier for the rule. CheckId and Category are used for in-source suppression of a warning.      

2

Title

The title of warning message      

3

Description

A description of the problem or suggested fix

4

File Name

File name and the line of code number which violate the code analysis rule set

5

Category

The code analysis category for this error

6

Warning /Error

Depend on how you configure it in the rule set the default is Warning level

7

Action

Copy: copy the warning information to the clipboard

Create Work Item: If you're connected to Team Foundation Server you can create a work item most probably you may create a Task or Bug and assign it for a developer to fix certain code analysis warning

Suppress Message: There are times when you might decide not to fix a code analysis warning. You might decide that resolving the warning requires too much recoding in relation to the probability that the issue will arise in any real-world implementation of your code. Or you might believe that the analysis that is used in the warning is inappropriate for the particular context. You can suppress individual warnings so that they no longer appear in the Code Analysis window.

Two options available:

In Source inserts a SuppressMessage attribute in the source file above the method that generated the warning. This makes the suppression more discoverable.

In Suppression File adds a SuppressMessage attribute to the GlobalSuppressions.cs file of the project. This can make the management of suppressions easier. Note that the SuppressMessage attribute added to GlobalSuppression.cs also targets the method that generated the warning. It does not suppress the warning globally.      

Visual Studio makes it very easy to fix Code analysis warning, all you have to do is clicking on the Check Id hyperlink if you are not aware how to fix the warring and you'll be directed to MSDN online or local copy based on the configuration you did while installing Visual Studio and you will find all the information about the warring including how to fix it.

clip_image021

Create a Custom Code Analysis Rule Set

  • The Microsoft standard rule sets provide groups of rules that are organized by function and depth. For example, the Microsoft Basic Design Guidelines Rules and the Microsoft Extended Design Guidelines Rules contain rules that focus on usability and maintainability issues, with added emphasis on naming rules in the Extended rule set, you can create and modify a custom rule set to meet specific project needs associated with code analysis. To create a custom rule set, you open one or more standard rule sets in the rule set editor.
  • Create and modify a custom rule set required Visual Studio Premium or Ultimate.
  • You can check How to: Create a Custom Rule Set on MSDN for more details https://msdn.microsoft.com/en-us/library/dd264974.aspx

Q & A

References