Click here to Skip to main content
15,867,686 members
Articles / Operating Systems / Windows
Article

FXCop 1.32

Rate me:
Please Sign up or sign in to vote.
4.43/5 (12 votes)
17 Oct 20059 min read 106.6K   2.2K   49   5
Bad Code in .NET? FxCop to the rescue.

Introduction

FxCop

FxCop is a code analysis tool that checks managed code assemblies for conformance to Microsoft® .NET Framework design guidelines plus custom guidelines.

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

  1. Create the project: Create a class library project that has the name of the DLL you want.
  2. Add the necessary references: You will need to add references to FxCopSdk.dll and Microsoft.Cci.dll.
  3. 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.
  4. Add the following using statements to the class:
    C#
    using Microsoft.Cci;
    using Microsoft.Tools.FxCop.Sdk;
    using Microsoft.Tools.FxCop.Sdk.Introspection;
  5. The constructor should look as follows:
    C#
    public class1() : 
        base( "class1",  // note that there is no "Rule"
              "ProjectName.RuleDefinitionsXML",
              // replace ProjectName with Company.FxCop.Category.
              typeof( class1 ).Assembly )
    {//TO DO}
  6. Create the RulesDefinitions.xml and add it to the project. Change the "Build Action" for this file to be "Embedded Resource".
  7. Implement the rule.
  8. Build the project.
  9. 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.

Please download the set-up file from here.

You can operate FxCop in three modes:

  1. In built with Visual studio 2005
  2. FxCop COM on Command prompts
  3. FxCop GUI

FxCop in Visual Studio 2005

Image 1

FxCop Command

To specify the assemblies and rules, use one of the following:

  • 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

Image 2

  • 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

Code Rules and standards, XML test reports, Free tool, Easy way for writing custom rules.

Financial Resources

It’s free. It also integrated with Visual Studio 2005.

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):

  1. FxCop is limited to assembly metadata; Code Analyzer works with source code and provides more functionality like comments, position in source code and more.
  2. 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.
  3. 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:

  1. 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.
  2. 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.
  3. 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.
  4. Standards Master 2004 checks for dozens of code construction options that FxCop does not check.
  5. Standards Master 2004 offers robust commenting and formatting options that are completely unavailable in FxCop.

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.

A list of licenses authors might use can be found here


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow to get fxcopcmd NewOnly fxcop warnings through command line ? Pin
Rameez Ahmed Sayad13-Nov-13 22:29
Rameez Ahmed Sayad13-Nov-13 22:29 
GeneralNDepend Pin
Patrick Smacchia MVP.NET6-May-07 12:51
Patrick Smacchia MVP.NET6-May-07 12:51 
Questioncan't find reference components Pin
ebdrup8-May-06 0:52
ebdrup8-May-06 0:52 
GeneralFXCop shows how bad MS Designer code is Pin
ThaddParker29-Oct-05 7:30
ThaddParker29-Oct-05 7:30 
GeneralTools is not in the namespace anymore Pin
EntilzhaFini26-Oct-05 11:52
EntilzhaFini26-Oct-05 11:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.