Introduction

FxCop

It uses introspection, MSIL parsing, and call graph analysis to inspect assemblies for more than 200 defects in the following areas: Library design, Localization, Naming conventions, Performance, Security. Introspection is described as a new faster, engine for performing Reflection on .NET classes .The main advantages of introspection engine are it performs a more extensive analysis than reflection, multithreading, analysis of assemblies of different versions of the framework, ability to Managed Extensions for C++ executables, and non-locking behaviour.

FxCop includes both GUI and command line versions of the tool. It also provides XML based test reports. You can write custom rules based on your company standards and add-up in FxCop tool to test your assembly.

Why FxCop?

To ensure that coding standards such as naming conventions, localization etc. are as per company standards.

To avoid bad coding and make use of best practices.

Well-formatted test reports.

Solution

Process

FxCop allows you to write / create your own rules or to use standards provided by Microsoft, and apply to your assembly. A rule is managed code that can analyze targets and return a message about its findings. FxCop analyses programming elements in managed assemblies and provide an informational report containing messages about the targets, including suggestions on how to improve the source code.

Coding standards: all developers are supposed to follow a company’s coding standards. It’s not an easy task to check manually the thousands of lines of code to ensure that coding standards are followed or not. FxCop solves this problem. You create an assembly having all these standards and run your assembly (DLL or EXE) against these rules, and FXCop will ensure that the specified rules are used in the coding or not.

Create a new project

Compile the assemblies.

Start the FxCop application.

Add the targets (assemblies) to be analyzed by the project.

Review the rules automatically loaded by FxCop and clear the selection of any rules that should not be applied to the targets during analysis.

Using the solution to solve the problem: Analyze the assemblies and review messages

Analyse the assemblies

Review the reported messages and determine the disposition for each:

Code defect - fix the source code.

Message is reporting an intentional variance from the rule - exclude the message.

Exclude items as appropriate.

Correct any code defects detected by FxCop.

Rebuild your assemblies.

Default rules of FXCop

COM Rules – rules about COM interoperability.

Design Rules – rules about the design of your .NET types and assemblies.

Globalization Rules – globalization/localization rules.

Naming Rules – rules about naming conventions.

Performance Rules – rules to improve performance of your code.

Security Rules – rules to make your code more secure.

Usage Rules – rules about proper usage of the .NET framework.

Custom Rules

FxCop supports writing custom rules. The FxCop SDK is used to develop custom rules that extend the set of violations detected. Custom rules can be written by writing a class in any. NET language.

Steps to write Custom Rules in FxCop

Create the project: Create a class library project that has the name of the DLL you want.

Add the necessary references: You will need to add references to FxCopSdk.dll and Microsoft.Cci.dll.

Create your first rule: Add a new class to the project to be used for implementing the rule. If you are not using any helping libraries, the class should be derived from BaseIntrospectionRule.

Add the following using statements to the class:

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

Create the RulesDefinitions.xml and add it to the project. Change the "Build Action" for this file to be "Embedded Resource".

Implement the rule.

Build the project.

Add the rules to FxCop. There are two ways to make the rule visible in FxCop. The first is to add it to the rules\ sub-folder in FxCop, which will make it available to all FxCop projects. The other is to add it to a specific project by the "Project - Add Rules" menu option.

(Check the example for more information.)

Tech and Delivery method

One of the thumb rules is coding standards are around as long as the programming/development exists.

FxCop targets .NET code only. Microsoft has obviously made a huge investment in .NET and in promulgating the best .NET coding practices through the .NET Framework Design Guidelines, which you can find at Design Guidelines for Class Library Developers.

Internally, Microsoft wanted to make sure their own developers followed the rules for consistency and maintainability. To enforce the Design Guidelines they devised a solution, out of which sprang FxCop.

FxCop aims to make it easy to comply by scanning compiled assemblies and creating a report that details coding errors (called violations) and suggests code fixes and improvements.

FxCop in Visual Studio 2005

FxCop Command

The /project option, which uses a project saved from the FxCop application.

The /file and /rule options, which directly specify the assemblies and rules, respectively.

To specify the location of the output file, use one of the following:

The /out option, which saves the results of an analysis in an XML file.

The /console option, which displays the results in a console window or, if integrated with Visual Studio, in Visual Studio's Output window.

FXCop GUI

The GUI version of FxCop has three panes that are easy to navigate. To analyse an assembly, in Configuration pane, you simply select Add Assembly from the Project menu (not File).

To see the rules that FxCop will apply, click the Rules tab, which lists them by category. To make changes, click on the category name and select or deselect the rules you want to apply.

The FxCop 1.30 has six additional new rules, so overall now we have 12 rules. You can add your own custom rules.

Click on Analyze and wait.

FxCop will list all the bugs (not as per coding standards) on the Message pane. The Property pane will give more information on the error highlighted. The yellow highlighted codes are the bad coding practices.

Key Components

Financial Resources

Evaluation

Results and Benefits

FxCop works with compiled assemblies and uses metadata to get information about the code. It also has an extensive set of rules, which are based on the MS Coding practices for .NET.

FxCop advantages

Extensive set of rules available out of box. Since it works with assembly metadata, it works with code created in any .NET language.

Free - Open source tool.

Well formatted XML based repots.

A Similar tool to Microsoft FxCop is Code Analyzer, but it is a licensed product:

Code Analyzer:

Code Analyzer advantages (comparing to FxCop):

FxCop is limited to assembly metadata; Code Analyzer works with source code and provides more functionality like comments, position in source code and more.

FxCop has flat rules structure, which makes orientation in policy more difficult for larger policies. Code analyzer has hierarchical structure, based on logical rule categories.

FxCop provides only one type of report, Code Analyzer is flexible and provides more report types and users can create their own report types.

Standards Master 2004:

Standards Master 2004 offers numerous advantages over FxCop. Many of these advantages may be credited to the fact that Standards Master works with your source code directly, not compiled assemblies as FxCop does. For example:

When examining naming conventions, Standards Master can check all identifiers in your code, not just the ones that appear in META data. Generally, most variables are declared within method bodies, and these do not appear in the META data FxCop examines.

Unlike FxCop, Standards Master 2004 can automatically fix many of the errors it finds. Since Standards Master works as an add-in, there is no need to switch tools to correct violations found. This means developers can fix standards violations easily while they work.

The naming conventions features of Standards Master are completely configurable; those in FxCop are essentially fixed. Microsoft's naming guidelines are not universally accepted or used (especially in VB circles) and do not apply to private or local variables. If your own standards have varied from or extended Microsoft's suggestions in any way, FxCop will not accommodate your changes.

Standards Master 2004 checks for dozens of code construction options that FxCop does not check.

Lessons Learned

FxCop tool enables programmers and QA managers to check .NET code for compliance with coding standards and best practices.

Once you have a policy defined you can use FxCop to analyze code (naturally organized into solution and projects) and create reports, which contain all violations of policy rules described in detail and related to source code position.

Use FxCop in your regular development to avoid bad coding and maintain quality of the application.

Sample Tests, Tables, etc.

Please check the attached zip project. In the example one custom rule is created to check all string variable should start with str as prefix. Install FxCop, and use the DLL file to verify your assembly.

How much time FxCop takes to review the DLL or EXE?

It depends on how complex and how related your assembly is. If it has reference dependencies then it takes extra time. It also depends on what all rules you want to apply to verify a DLL or EXE and how well you have coded your DLL.

Approximately for 5000 lines of code it takes less than a minute.

FxCop generates XML based test reports.

Is FxCop free? Source code available for MS designed default rules?

Yes. It’s free to download. Source code for default MS rules is also available. (From the website you can only download DLLs but from the blog site mentioned in the section below, we can download the source code for the same.) It’s not necessary to use the MS default rules, you can create your own custom rules.

More Info

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

It also comes from with advanced code visualization (Dependencies Matrix, Metric treemap, Box and Arrows graph...), more than 60 metrics, facilities to generate reports and to be integrated with mainstream build technologies and development tools.

NDepend also allows to compare precisely different versions of your codebase.

When I load the project in VS2005 Team Suite, the referenced components can't be found:
fxcop
FxCopCommon
FxCopSdk
FxCopUI
Microsoft.Cci

I thought that FxCop was installed with VS2005 Team Suite, do I need to download and Install FxCop to make my own rules?

Also I have looked on the internet for tutorials on how to write your own rules for FxCop and I haven't been able to find anything. I would like to write a rule that checks some advanced things based on, among other things, custom attributes for some classes. Where can I find more info on how to write my own rules?

In my recent experience using FXCop, I have noticed with increasing alarm that FXCop chokes on VS Designer written Code. For example, any web service that is created, FXCop will have a hissy fit over naming conventions and poor usage of the .NET Framework. Another good example of how poorly VS writes out code is when creating an .xsd file for a dataset.

If MS is really all about pushing the correct coding constructs of the .NET environment, then they need to eat their own dog food when it comes to using their designers to write out code.

The reason why a poor man will always be poor and the rich man will be rich, is because the poor man will always maximizes his expenditures and the rich man will always maximizes his potential. --T.Parker

The latest version of the libraries has changed the namespace elements.

This article uses:
using Microsoft.Tools.FxCop.Sdk;
using Microsoft.Tools.FxCop.Sdk.Introspection;

while the newer libraries don't include the "Tools" sub-namespace:
using Microsoft.FxCop.Sdk ; // the documentation incorrectly shows these two
using Microsoft.FxCop.Sdk.Introspection ; // as Microsoft.Tools.FxCop.Sdk (take out "Tools")