Create Custom FxCop Rules
FxCop is a free, open source code analysis tool
from Microsoft. FxCop, stands for "Framework Police" and is a rules-based
engine that checks managed code assemblies. .NET assemblies contain metadata
entries that describe the assembly and all of its contained types. FxCop reads
the assembly metadata and checks it for compliance against a set of rules that
describe recommended coding standards and practices.
Once FxCop has analyzed the assemblies, it reports any rule violations and
produces well-formatted XML test reports. Areas covered by FxCop are
localization, performance, and security. FxCop checks .Net code against rules
stored in an embedded xml file.
FxCop performs tests on the assemblies by parsing the MSIL
(Microsoft Intermediate Language) they contain, inspecting, and reporting on
code that fails to meet the rules. Since FxCop performs the tests on managed
assemblies and not the source code, it's .NET-language neutral. Thus, you can
run it against any assembly created using any language that targets the
Microsoft .NET managed environment.
FxCop was developed by Microsoft and is available as a free download from their
FxCop has an extensive set of pre-defined rules. However, it also allows you to
develop your own custom rules. To develop your own rules, you will need to
delve into the MSIL. There are a number of ways to do this. One way to explore
the MSIL for an assembly is to use the MSIL Disassembler (IL
DASM) that comes with Visual Studio. A better way is to use the free
Reflector for .NET by Lutz Roeder.
Now the bad news. There is no documentation for FxCop so developing custom rules
is a matter of trial and error. Looking through the object model of FxCop is
time well spent. To that end, I am sharing, on the following pages, a number of
custom rules I created to check VB6 applications that were converted to VB.NET.
I created these rules mostly to verify the converted applications used .NET
statements and controls and did not rely on older VB6 controls or use the
FxCop Rule Overview
Each FxCop rule resides in its own class whose name must match the name of the
rule. Also, each rule must have its own node in the embedded XML file. The XML
file is what supplies the rule's message, description, resolution, and other
Most FxCop rules start out by calling either the Check
or VisitCall method. Then, once a rule violation
has been determined, return a Problem or
ProblemCollection after making a call to the GetResolution
method to retrieve the rule information such as, message, resolution, certainty
level, etc. from the XML file.
Hopefully, the following samples and some Googling, will help get you started.