Exercise 2: Suppressing Code Analysis Warnings

In this exercise, you will learn how to suppress Code Analysis warnings at the project and source level.

  1. In the Error List window, select the first three warnings that appear which are associated with the project. Note that they are not associated with a file by looking in the File column. Imagine that we do not want to address the selected issues and no longer want them to appear when Code Analysis executes.
  2. Right-click on the selected warnings and select Supress Message(s) | In Project Suppression File from the context menu that appears. This will add assembly level metadata to a project level GlobalSuppressions.cs file.

    Figure 1

    Suppressing specific code analysis rules at the project level

  3. Open the GlobalSuppressions.cs file to view the added code.

    Figure 2

    Suppressed rules are crossed out and GlobalSuppressions.cs changes

  4. Take a look at the next Code Analysis warning that is listed, CA1726, which suggests changing the type name ‘Cancelled’ with the preferred alternate ‘Canceled’. Double-click on it to go to the correct source location for the fix.
  5. Right-click on the class name ‘Cancelled’ and select Refactor | Rename… from the context menu that appears.

    Figure 3

    Renaming class to fix spelling

  6. In the Rename window, change ‘Cancelled’ to ‘Canceled’ and select the OK button to continue.
  7. In the Preview Changes – Rename window, review the proposed changes and select the Apply button to complete the refactoring process.
  8. Move on to the next Code Analysis warning by selecting it. Imagine that we want to suppress this specific rule, but this time we only want applied to this particular source file. Right-click on the warning and select Suppress Message(s) | In Source from the context menu that appears. This applies a SuppressMessage attribute to the delegate for which the Code Analysis rule was identifying.

    Figure 4

    Suppressing a Code Analysis rule at the source code level

  9. Select Analyze | Run Code Analysis on Tailspin.Model from the main menu and verify that more of the warnings have been successfully addressed.
  10. At this point, there are additional Code Analysis warnings that we could address, but imagine that we simply want to ignore the remaining items for now. Return to the Code Analysis section of the project properties and select the ‘Microsoft Minimum Recommended Rules’ option.
  11. Select Analyze | Run Code Analysis on Tailspin.Model from the main menu and verify that the number of warnings has dramatically been reduced. The warnings that appear as the result of using this rule set are more likely to be problematic during runtime.

To give feedback please write to VSKitFdbk@Microsoft.com

Copyright © 2010 by Microsoft Corporation. All rights reserved.