Custom FxCop Rules, Adventure #1 22 November 2011Posted by golda972 in C#, code analysis, documentation, FxCop.
Static code analysis is a beautiful thing. It is also integrated into the higher-end versions of Visual Studio 2010.
Sometimes, though, the built-in rules are not enough. For example:
This rule is sensible. Nobody wants resources to float around until their containing class gets finalized at some indeterminate point in the future.
The first* issue that arose in our project is that, to my great sorrow, all data management in our project is done with strongly-typed DataSets. Lots and lots of strongly-typed DataSets. And by way of a grandparent, DataSet, DataTable, and DataView all implement IDisposable but do not have any resources that actually need to be released.
This rule (and its brother, CA2000: Dispose objects before losing scope) are important for catching big, fat bugs (“Why won’t the FileStream open? Oh, wait, I never closed it when EatSushiFromFile() crashed last time”). But with all the noise from “Thou shalt dispose the SushiTable because it inherits from DataTable which implements IDisposable,” no one really wants to hear about the rule (“Suppress! Suppress!”).
The process starts with a surprise:
Surprise! Microsoft doesn’t provide documentation for writing custom code analysis rules!
Who does? (I asked)
The main prize from Jason Kersowaty is his Introspector – this gem is absolutely necessary for revealing what data you can visit when searching for problems in the code under analysis.
The last tool in your arsenal is a .NET decompiler. I went with the open source ILSpy. The tried and true method to write your own rule is to study (and copy and paste, where appropriate) the rules written by the people who had some understanding of the Introspection API. The libraries containing these rules can be found under the same folder as FxCop itself on your computer:
Team Tools\Static Analysis Tools\FxCop\Rules\
I really think that this is enough information to start with. Next post should be about the process and the design pattern I used to create one of my rules.
*Actually, another issue came first. But that’s HP’s business, not yours.