devxlogo

Monitor .NET Code Quality with FxCop and Custom Rules

Monitor .NET Code Quality with FxCop and Custom Rules

XCop is a free code analysis tool (open source) from Microsoft that analyzes managed .NET assemblies. .NET assemblies contain metadata entries that describe the assembly and all its contained types. FXCop works by reading the assembly metadata and checking it for compliance against built-in and custom rules that describe recommended coding standards and practices.

After analyzing the assemblies, FxCop reports any rules violations in the areas of localization, performance, and security. It checks code against a set of rules and messages stored in an embedded xml file, displaying appropriate messages at runtime when rules violations occur. You can extend the built-in rules with custom rules that you create. This article discusses how to use FxCop, and how to create and apply such custom rules.

To implement the techniques discussed in the article, you’ll need: FxCop Version 1.32, the .NET framework version 1.1 or higher installed, and Windows XP/2000 or a later OS.

What is FxCop?
FxCop, an abbreviation for “Framework Police,” is a rules-based engine that checks managed code assemblies for conformance to Microsoft’s .NET Framework design guidelines and custom guidelines. It performs tests on the assemblies by parsing the MSIL they contain, inspecting and reporting on code that fails to meet the rules. Because FxCop performs the tests on managed assemblies and not the source code, it’s .NET-language neutral; in other words, you can apply it to any assembly created using any language that target the Microsoft.NET managed environment.

Why Use FxCop?
FxCop provides some immediate advantages, particularly for shops that use more than one .NET language.

  • It works with any managed assembly created by any .NET-compliant language that runs on the Microsoft.NET framework.
  • It has an extensive set of pre-defined rules.
  • It has support for creating custom rules.
  • It produces well-formatted XML test reports.
  • It’s an open source tool, so you can extend or alter it as needed.

Still, at its current stage of maturity, FxCop does have some limitations:

  • It works only with assembly metadata, not source, so it can’t be as specific as source code analysis tools.
  • It follows a flat rules structure that makes implementing large sets of policies tougher.
  • It does not support custom report types.

How to get FxCop?
FxCop was developed by Microsoft. It’s available as a free download.

If you have problems or questions you can post messages to the FxCop team or to the MSDN forums.

Some Important FxCop Terminology
A target refers to the managed assembly on which FxCop is used to inspect against compliance to the standards.

FxCop represents the checks it performs during an analysis as rules. FxCop rules are implemented as public classes. All rules implement a Check method that returns a reference to an object of the ProblemCollection class from the FxCop SDK. This value determines whether a violation has occurred. A rule consists of managed code that analyzes the target(s) and returns a message stating its findings. These messages not only display standards violations but also provide guidance on how to rectify the violations in the source code.

Rules in FxCop are categorized as Default Rules and Custom Rules. The default rules are grouped based on category.

Here are some of the important in-built rules in FxCop, their objectives and an example of each.

  • Design Rules?these are rules about the design of your .NET types and assemblies.
    Example: Abstract types should not have constructors.
  • Globalization Rules?these are rules concerning globalization and localization.
    Example: Do not hardcode locale specific strings.
  • Naming Rules?these are the rules that cover naming conventions.
    Example: Avoid type names in parameters.
  • Performance Rules?these rules check for possible performance improvements or impediments to code.
    Example: Test for empty strings using string length.
  • Security Rules?These are rules that check for secure code.
    Example: Pointers should not be visible.
  • Usage Rules?these are rules that provide guidance about the standard .NET framework usage.
    Example: Finalizers should be protected.

The FxCop Interface
FxCop exposes two interfaces: a GUI-based user interface and a command-line interface. The FxCop GUI has three windows (see Figure 1).

A configuration pane displays the targets and rules for the current FxCop project in a TreeView. You use the configuration pane to select the target assembly or assemblies (you can analyze more than one assembly at the same time) and the rules that FxCop will use to analyze the target assembly.

?
Figure 1: The FxCop User Interface: Here’s a screenshot of the FxCop UI showing the Configuration Pane, the Message Pane and the Properties Pane.
?
Figure 2: An FxCop Analysis Report: The figure shows a sample FxCop analysis report containing several message types.

A Messages pane displays an analysis report on the target assembly after inspection. These messages are displayed at the following levels based on their importance and criticality.

  • Critical Error
  • Error
  • Warning
  • Critical Warning
  • Information

Figure 2 shows a typical FxCop analysis report.

A Properties tab displays information about the target assembly, including the namespace, type and type members, group of rules, rule, or message. You can select a rule, a group of rules, discard some rules, etc. to build a set of rules against which you want FxCop to test the assembly.

Creating Custom Rules in FxCop
FxCop lets you create custom rules to enforce your own standards. You use the FxCop SDK to develop custom rules and add them to the in-built default rules. Custom rules are classes that inherit from the BaseIntrospectionRule class in the FxCop SDK. You describe custom rules in an XML document, and then embed that in the application as a resource.

Implementing Custom Rules using the FxCop SDK
I’ll provide a more detailed example in the rest of this article, but as an overview, here are the steps you need to follow to create custom rules in FxCop:

First, create a class library project and add references to the FxCopSdk.dll and Microsoft.Cci.dll assemblies.

Next, create a class to implement the rule. This class must inherit from the BaseIntrospectionRule class.

Add the following using statements to your custom rule class:

   using Microsoft.Cci;    using Microsoft.Tools.FxCop.Sdk;   using Microsoft.Tools.FxCop.Sdk.Introspection;

Create a constructor for your custom rule class that looks similar to this:

   public MyCustomRule() : base( "MyCustomRule",       "ProjectName.RuleCategory.RuleDefinitions",       typeof(MyCustomRule).Assembly )   {      }

You’ll also need to describe the rule in a XML document file and save that as an embedded resource (change the “Build Action” for this file to be “Embedded Resource”) in the main assembly. I’ll describe that process in more detail below.

Save and compile to build the assembly.

Finally, add your new rule using the FxCop IDE. Note that this assembly gets added to the FxCop rules engine. At this point, you can use FxCop to inspect a target assembly using both the predefined and your new custom rule.

A Custom Rule Example
In this example you’ll design a BaseRule class that you can later extend with CustomRule classes. Here are the files you’ll require:

  • NamingRules.xml?Contains the description of each and every rule that you will implement.
  • NamingRules.cs?Contains C# code for all the custom naming rules.
  • BaseRule.cs?The C# code file containing the BaseRule class.

Here’s the rule definition for the sample custom rule in XML format in the NamingRules.xml file:

               Objects of the Object class should be properly named.            Objects of the Object class should be prefixed with obj'.          Joydip     Self     Self     http://localhost     Change the name of the object {0} so         that it starts with a prefix of 'obj'.     [email protected]     Warning     Breaking      

The rule name in the preceding code is InterfaceNamingRule, and the category is NamingRules.

Here’s the code for the BaseRule class (which you can find in the BaseRule.cs file in the downloadable code) that you’ll extend with a custom rule class shortly.

   using System;   using Microsoft.Cci;   using Microsoft.Tools.FxCop.Sdk;   using Microsoft.Tools.FxCop.Sdk.Introspection;      [CLSCompliant(false)]      namespace FxCopCustomRulesLibrary   {      public abstract class BaseRule : BaseIntrospectionRule      {          protected BaseRule(string name) : base(name,               "FxCopCustomRulesLibrary.NamingRules.NamingRules",                typeof(BaseRule).Assembly)          {          }      }   }   

The BaseRule class in the preceding code provides some common functionality to facilitate code reusability and simplify code maintenance. For example, the class constructor makes a call to the BaseIntrospectionRule constructor with the required parameters.

Listing 1 shows a custom rule class that inherits from the BaseRule class. You’ll find this in the NamingRules.cs file in the downloadable code.

Analyzing assemblies using FxCop
You need to follow this sequence of steps to analyze assemblies using FxCop.

  • Start the FxCop application
  • Select and then add the targets (assemblies) to be analyzed by the project. (Project->Add Targets on the FxCop menu system)
  • Add the Custom rules (if any) to the FxCop Application (Project->Add Rules on the FxCop menu system)
  • Click on the Analyze button

Integrating FxCop with VS.NET
You can integrate FxCop with the Visual Studio IDE to enable developers to analyze the source code at the time of coding. Integration is beneficial for the developers because it FxCop’s generated reports help developers find and fix errors before application deployment.

How to integrate?
FxCop ships with a command-line tool named fxcopcmd.exe that you can use to integrate FxCop with the VS.NET IDE or to add FxCop analyses and report generation to your build process. To integrate it:

  • Select Tools?> External Tools from the VS menu; you’ll see a popup window with configurable options.
  • In the Title field, enter FxCop.
  • In the Command field enter C:Program FilesMicrosoft FxCop 1.32FxCopCmd.exe. Note: This is the default installation path. You may need to use a different path if you installed FxCop in a custom location.
  • In the Arguments field, enter /f:$(TargetPath) /r:”C:Program FilesMicrosoft FxCop 1.32Rules” /c
  • Set the Initial Directory field to $(ProjectDir)
  • Check the “Use Output Window” option.

Save your changes. Now, from the VS.IDE, you can click Tools – > FxCop in the menu system. FxCop loads the rules and displays the report in the VS.NET IDE’s Output window.

The software applications in today’s IT industry are increasingly becoming more complex and sophisticated with time. Microsoft released the free FxCop code analysis tool to help developers achieve the goal of designing quality software applications that conform to predefined standards. In this article, you’ve seen how to use FxCop to create custom rules and analyze managed assemblies for compliance to required standards, and how to integrate FxCop into the Visual Studio IDE, making it more convenient for developers to analyze their assemblies for problems on demand, or as part of their standard build process.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist