joydip_kanjilal
Contributor

How to build custom rules with FxCop

opinion
Nov 18, 20155 mins
Software Development

Take advantage of the FxCop library to build custom rules and enforce code quality

Microsoft’s FxCop is a free static code analysis tool that checks your assemblies for compliance against some built-in rules. You can also develop custom rules and run FxCop to check for compliance of the assemblies against such defined standards.

Getting started

FxCop analyses the MSIL generated by managed languages like C# and VB.Net and is downloadable as a standalone application. You should have a copy of Visual Studio installed in your system — the latest version is preferred. To get started with FxCop you should first download a copy of it.

What are rules and targets in FxCop?

In FxCop, a rule is a defined standard against which the FxCop engine would inspect an assembly to check for compliance or adherence to the defined standards. A target in FxCop refers to the managed assembly that would be analyzed by FxCop to check for compliance to the defined standards. Note that these defined standards are represented in FxCop using one or more rules. Such rules can be the predefined rules or even custom rules. Note that based on the severity of the violations, FxCop categorizes the messages into the categories given below.

  1. Critical Error
  2. Error
  3. Warning
  4. Critical Warning
  5. Information

FxCop generates well formatted XML comprehensive reports on the broken rules and contains an extensive set of pre-defined rules that are categorized into the following categories:

  1. Design rules
  2. Globalization rules
  3. Interoperability rules
  4. Mobility rules
  5. Naming rules
  6. Performance rules
  7. Portability rules
  8. Security rules
  9. Security Transparency rules
  10. Usage rules

You can leverage the utility tool called JSL FxCop to build your custom rules using the FxCop library. This utility comprises of a collection of utility classes and custom rules.

Implementing a custom rule using FxCop library

In this section we would discuss how we can build custom rules using the FxCop library. To build custom rules, you would first need to create a Class Library project in Visual Studio and include references to the FxCop library. Note that the FxCop library is available in the FxCopSdk.dll file which in turn is present in the FxCop installation directory in your system. The next thing you need to do is create a class and derive it from the class BaseIntrospectionRule as shown below.

 public class CustomRule : BaseIntrospectionRule

    {

        public CustomRule() : base("CustomRule", "IDG.FxCop.Rules.CustomRule", typeof(CustomRule).Assembly)

        {

        }

<code>    }

Note that you should call the base class constructor in your rule class and pass the class name, assembly and the XML file name to it as parameters. What’s this XML file all about? Why is it needed?

Well, the FxCop engine needs an XML file that contains the metadata information of one or more rules.

<?xml version="1.0" encoding="utf-8" ?>

<Rules FriendlyName="IDG.Rules">

  <Rule TypeName="CustomRule" Category=" IDG.FxCop.Rules" CheckId="R001">

    <Name>CustomRule</Name>

    <Description>This is a custom rule</Description>

    <Url></Url>

    <Resolution></Resolution>

    <Email></Email>

    <MessageLevel Certainty="100">CriticalWarning</MessageLevel>

    <FixCategories>NonBreaking</FixCategories>

    <Owner />

  </Rule> 

</Rules>

Next, you should override the Check method in your custom rule class. This is the method that gets called whenever the FxCop engine analyses your assembly and parses the methods in it. If there are any issues with the method being parsed by the FxCop engine, a list of errors are reported to let you know the violations that might have occurred. To report the violations that can occur when a method is checked for compliance to the defined rules, you should return an instance of ProblemCollection. Here’s how a typical Check method looks like.

public override ProblemCollection Check(Member member)

{

 //Write code here to validate your method against your custom rule(s)

}

Let’s now implement a simple rule. Here’s the metadata information that your custom rule would use.

<Rule TypeName="AvoidUsingVirtualMethods" Category="Performance" CheckId="R001">

    <Name>AvoidUsingVirtualMethods</Name>

    <Description>Rule that will identify if the target assembly contains virtual methods. </Description>

    <Url></Url>

    <Resolution>Avoid using virtual methods.</Resolution>

    <Email>joydipkanjilal@yahoo.com</Email>

    <MessageLevel Certainty="100">CriticalWarning</MessageLevel>

    <FixCategories>NonBreaking</FixCategories>

    <Owner />

</Rule>

The following code snippet illustrates how you check for virtual methods in the target assembly and report a message if one or more virtual methods are found.

public override ProblemCollection Check(Member member)

       {

            Method method = member as Method;

            bool isVirtual = method.IsVirtual;

            if (isVirtual)

            {

                Resolution resolution = GetResolution(new string[] { method.ToString() });

                Problems.Add(new Problem(resolution));

            }

           return Problems;

        }

You can now add a target assembly and this rule using the FxCop IDE. One you analyze the target assembly, you would be able to see a report on the violations to the rule (if any).

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author