Update: To have rules target both Visual Studio and FxCop, see the following entry: FAQ: Can I create custom rules that target both Visual Studio and FxCop?
Although not officially supported or documented, the Managed Code Analysis (FxCop) feature available with Visual Studio Team System comes with a rich API for writing custom rules.
There are a number of samples and articles on the web that already cover using this API and its usage with the externally available FxCop, so instead of covering the same information, this entry will instead give a quick rundown on integrating existing custom rules with Visual Studio.
Before beginning, download the attached zipped project (at the bottom of the post) and extract the contents. This project contains a single custom rule called PrivateFieldsShouldHaveCorrectPrefix that performs a simple check to make sure that private class fields (both instance and static) are prefixed with an underscore. The following code shows the type of field names it fires violations against (and those it doesn’t):
public class Class1{ private int _Field; private int _field; private int Field; // Violates PrivateFieldsShouldHaveCorrectPrefix private int field; // Violates PrivateFieldsShouldHaveCorrectPrefix private int m_field; // Violates PrivateFieldsShouldHaveCorrectPrefix}
As the source has been provided, you can change PrivateFieldsShouldHaveCorrectPrefix to follow your own naming rules or add additional rules to the library to enforce your own company’s guidelines.
To register the rule library with Visual Studio, the built assembly (in this case, Microsoft.FxCop.Rules.Samples.dll) should be placed in the Code Analysis Rules folder, which by default is located at C:\Program Files\Visual Studio 8\Team Tools\Static Analysis Tools\FxCop\Rules. Once the library has been registered, all opened projects (new and existing), will have any rules that are contained in the assembly enabled by default. You can now simply run Code Analysis over a project to analyze it with your new rules.
Before attempting this there are a couple of things you should be aware of:
Please note that this is not supported by Microsoft so please don’t call Product Support Services if you have any troubles, however, feel free to post any issues you encounter on the FxCop forum.