Friday, June 1, 2012

SuppressMessage attribute not working, FxCop

FxCop 1.35+ versions have the ability to suppress messages in code using ‘SuppressMessage’ attribute. This attribute Suppresses reporting of a specific static analysis tool rule violation, allowing multiple suppressions on a single code artifact.

For example: Suppose you have a class

public class UtilityFunctions
       [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
       public string GetMachineCurrentLocation()
          // logic to fetch location using GetUserGeoID & GetUserDefaultLCID etc
           return machineLocation;
In the above example, we've suppressed the UsePropertiesWhereAppropriate violation for the GetMachineCurrentLocation method so that FxCop no longer will raise it. Some advantages of using this:
1. Other developers in your team can quickly see that an obvious violation has been suppressed.
2. Unlike in-project suppressions, changes to the namespace, type or signature of a member (ie name, return type, etc) do not require the SuppressMessage attribute to be updated.

Issue: Using Suppress Message first time won't work in fxcop. Even after adding suppress message, violation errors are still logged in FxCop.

Fix: While using in-code violation suppression first time, it can be confusing as to why FxCop seems to ignore these attributes. The SuppressMessage attribute is what is called a 'conditional' attribute. A conditional attribute is an attribute that is only included in metadata of your assembly if a certain compilation symbol is defined at compile time. 
The SuppressMessage attribute itself requires the CODE_ANALYSIS symbol to be present and by default, this is not included in non-team system projects. That's why FxCop continues to report errors.

To define this symbol, do the following in Visual Studio:
  1. In Solution Explorer, right-click your project and choose Properties.
  2. In the Properties window, choose the Build tab.
  3. In the Conditional compilation symbols text box, enter CODE_ANALYSIS

Hope this will fix your issue.

1 comment: