PostSharp + Code Analysis = Abomination

(If you just want the targets files, click here.)

Are you using PostSharp for your .NET development? Do you get frustrated when code analysis within VSTS reports warnings like these:

Code Analysis Warnings

Now PostSharp is a superb AOP tool for .NET, but it is annoying to see these issues in code analysis again and again; what would be great is if we can edit the build process to make Code Analysis (CA) run before PostSharp processes the assembly. That way, code analysis errors on PostSharp-generated code is ignored, and everyone is happy. :)

Continue reading

CA2104: DoNotDeclareReadOnlyMutableReferenceTypes

If you’re not familiar with the code analysis rule mentioned in the title of this post, I recommend you check out David Kean’s FAQ post here for some background.

In summary, a violation of this rule may be fired even if you declare a read-only variable of a type that’s immutable, because the code analysis engine won’t know that that type is immutable. To get around this, you can follow David’s suggestion of putting an ImmutableTypes.txt file in the same directory as your FxCop project file.

But if you’re using Visual Studio Team System to execute your Code Analysis, it’s a different story because you don’t have an FxCop project file. Fortunately, this ImmutableTypes.txt file can be placed in the C:Program FilesMicrosoft Visual Studio 9Team ToolsStatic Analysis ToolsFxCopImmutableTypes.txt location to be picked up.

What would be great is if there was an MSBuild task that allowed developers on a project to make an ImmutableTypes.txt file directly in a VS project and have that merged with the existing ImmutableTypes.txt at the target location. That way, individual projects can build their ImmutableTypes without worrying about CA2104 violations. In fact…I may just build that task. ;) Right now I have a centralized project for gathering Immutable Types and I do this as part of my build:

<Copy SourceFiles=ImmutableTypes.txt DestinationFolder=$(VS90COMNTOOLS)….Team ToolsStatic Analysis ToolsFxCop />

That will copy the ImmutableTypes.txt file from my project to the C:Program FilesMicrosoft Visual Studio 9Team ToolsStatic Analysis ToolsFxCopImmutableTypes.txt location. Problem (tentatively) solved. :)