Have your Custom CodeAnalysis rule integrate properly with Visual Studio

After porting the MSOCAF rules to FxCop 10, I noticed that you can't use the "Suppress in Source" option. Only the option "Suppress in Project suppression file" is available. Another problem with the global suppression is that it isn't scoped to a type or method, basically turning off that rule for the whole assembly. We don't want that!

As there is close to no documentation available on CodeAnalysis and FxCop, I looked at the difference between the MSOCAF rules and the standard Code Analysis rules that ship with Visual Studio 2010.

It turns out that to get the 'Suppress in Source' option to work, you must pass a Node to the Problem constructor. Setting the SourceContext manually or setting the filename and position won't allow you to suppress in Source.

This is how the MSOCAF rules supply context information by default:


if (!fullyQualifiedResolutionStrings.Contains(resolution.ToString()))
{
     problem = new Problem(resolution, method.SourceContext);
     problem.Certainty = 90;
     problem.FixCategory = Microsoft.VisualStudio.CodeAnalysis.Extensibility.FixCategories.NonBreaking;
     problem.Id = this.GetNextId();
     problem.MessageLevel = Microsoft.VisualStudio.CodeAnalysis.Extensibility.MessageLevel.Warning;
     base.Problems.Add(problem);
     fullyQualifiedResolutionStrings.Add(resolution.ToString());
}

And this is the only change I had to do to make the rules integrate properly:


if (!fullyQualifiedResolutionStrings.Contains(resolution.ToString()))
{
     problem = new Problem(resolution, method);
     problem.Certainty = 90;
     problem.FixCategory = Microsoft.VisualStudio.CodeAnalysis.Extensibility.FixCategories.NonBreaking;
     problem.Id = this.GetNextId();
     problem.MessageLevel = Microsoft.VisualStudio.CodeAnalysis.Extensibility.MessageLevel.Warning;
     base.Problems.Add(problem);
     fullyQualifiedResolutionStrings.Add(resolution.ToString());
}

The only issue with this solution is that the suppression generated based on the SourceContext or position in the file result in a different suppression in the code. Which in turn no longer allows us to suppress the messages in the MSOCAF tool itself. But asĀ suppressionsĀ are to be kept to a minimum anyways, I don't really care about that.

Let's hope Microsoft will solve this issue in the next release of MSOCAF.