Click here to Skip to main content
Click here to Skip to main content

7 Steps to Write Your Own Custom Rule using FXCOP

By , 25 Nov 2008
 

Table of Contents

Introduction

FXCOP is one of the legendary tools which help us automate reviews using set of rules against compiled assemblies. This article will discuss some basics of FXCOP and then concentrate mainly on how we can add custom rules in FXCOP.

I have been writing and recording a lot of architecture related videos on design patterns, UML, FPA estimation, Enterprise application blocks, C# projects, etc. You can watch my videos here.

Basics of FXCOP

As the name suggests, the COP in FXCOP means the police. So it’s an analysis tool which runs rules against the .NET assemblies and gives a complete report about broken rules. As it runs on the assembly, it can be run on any language like C#, VB.NET etc. You can download the latest copy of FXCOP from here.

The below figure gives a visual outlook of how FXCOP runs the rules on the assembly and then displays the broken rules in a different pane.

Using the Existing Rules

Using the existing rules is pretty simple. Open the FXCOP tool and you will see two tabs, one is the targets tab and the other the rules tab. Targets tab is where you add the assembly. You can add the assembly DLL by right clicking and then clicking on add targets.

The rules which need to be run can be selected in the second tab ‘Rules’. So click on the tab and select the necessary rules and hit analyze.

Adding a Custom Rule - All Connection Objects Should be Closed

To understand the concept of custom rule, we will take a practical example. What we will do is when any connection object is opened in a method, we will ensure that it’s closed. If it’s not closed, FXCOP will throw an error.

Step 1

To make custom rules, the first step is to create a class library. FXCOP expects an XML file in which rules are defined. The format of the XML file is shown below. We have named this file as ‘Connection.XML’. The Rule tag has the ‘TypeName’ property which has the class name i.e. ‘ClsCheck’. We will create the class at a later stage. The description tag defines what error message should be thrown in case the rules are broken.

<?xml version="1.0" encoding="utf-8" ?>
<Rules>
<Rule TypeName="clsCheck" Category="Database" CheckId="Shiv001">
<Name>Connection object Should be closed</Name>
<Description> Connection objects should be closed</Description>
<Owner> Shivprasad Koirala</Owner>
<Url>http://www.questpond.com</Url>
<Resolution> Call the connection close method </Resolution>
<Email></Email>
<MessageLevel Certainty="99"> Warning</MessageLevel>
<FixCategories> Breaking </FixCategories>
</Rule>
</Rules>

Step 2

The first thing is to reference and import the FXCOP SDK. So add a reference to the FxCopSdk.DLL. You can find FxCopSdk.dll where FxCop is installed.

Once you have added a reference, you need to import the DLL in the class file.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.FxCop.Sdk;

Step 3

For defining custom rule, you need to inherit from the ‘BaseIntrospectionRule’ class of FxCop. So below is the custom class ‘ClsCheck’ which inherits from ‘BaseIntrospectionrule’ class. The constructor of ‘ClsCheck’ is very important. We are basically calling the parent constructor where we need to pass the class name and the XML file. So we have passed the ‘clsCheck’ class and the ‘Connection.XML’ file name. We also have to override the ‘Check’ method. The ‘Check’ method is called when every method is parsed. If there are any issues, we need to return back a problemcollection array which will be displayed in the FXCOP UI. 

public class clsCheck : BaseIntrospectionRule
{
public clsCheck(): base("clsCheck", "MyRules.Connection", typeof(clsCheck).Assembly)
{
}

public override ProblemCollection Check(Member member)
{
…….
……..
}
}

Step 4

So the first thing is we convert the member into the Method object. We have defined two Boolean variables, one which specifies that the connection object has been opened and the second that the connection object has been closed.

Method method = member as Method;
bool boolFoundConnectionOpened = false;
bool boolFoundConnectionClosed = false;
Instruction objInstr=null;

Step 5

Every method has an instruction collection which is nothing but the actual code. So we loop through all instructions and check if we find the string of SQLConnection. If yes, we set the Boolean value of the found connection to true. If we find that we have found ‘Dbconnection.close’, we set the found connection closed to true.

for (int i = 0; i < method.Instructions.Count; i++)
{objInstr = method.Instructions[i];
if (objInstr.Value != null)
{
if (objInstr.Value.ToString().Contains("System.Data.SqlClient.SqlConnection"))
{
boolFoundConnectionOpened = true;
}
if (boolFoundConnectionOpened)
{
if(objInstr.Value.ToString().Contains("System.Data.Common.DbConnection.Close"))
{
boolFoundConnectionClosed = true;
}

Step 6

Now the last thing. We check if the connection is opened, was it closed? If not, then we get the message of the connection.xml file and add it to the problems collection. This problems collection is returned to the FXCOP to display it.

if((boolFoundConnectionOpened)&&(boolFoundConnectionClosed ==false))
{
Resolution resolu = GetResolution(new string[] { method.ToString() });
Problems.Add(new Problem(resolu));
}
return Problems;

Step 7

Once you have compiled the DLL, add the DLL as rules and run the analyze project button. Below is the project which was analyzed and the ‘objConnection’ object which was open and was never closed.

public void addInvoiceDetails(int intInvoiceid_fk,
int intCustomerId,
int intProductid_fk,
double dblTotalAmount,
double dblTotalAmountPaid)
{
SqlConnection objConnection = new SqlConnection();
}

You can see in the output how the method name is displayed with the resolution read from the connection.xml file.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Shivprasad koirala
Architect http://www.questpond.com
India India
Member

I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small
E-learning company in India. We are very much active in making training videos ,
writing books and corporate trainings. Do visit my site for 
.NET, C# , design pattern , WCF , Silverlight
, LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server  training 
and Interview questions and answers


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionRule not getting listed in Ruleset editor in VS2012memberoops.uvj4 Apr '13 - 18:54 
Hi,
 
I have created the rule dll and pasted it in "C:\program files (x86)\Microsoft Visual Studio 11.0\Team Tools\Static Analysis Tools\FxCop\Rules" folder.
 
following is the code EmptyCatchBlock.cs
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.FxCop.Sdk;
 
namespace EmptyCatchBlockRule
{
    public abstract class BaseFxCopRule : BaseIntrospectionRule
    {
        protected BaseFxCopRule(string ruleName)
            : base(ruleName, "EmptyCatchBlock.EmptyCatchBlockMetadata", typeof(BaseFxCopRule).Assembly)
        { }
    }
 
    public class FindEmptyCatchBlock : BaseFxCopRule
    {
        public FindEmptyCatchBlock()
            : base("FindEmptyCatchBlock")
        { }
 
        // Only fire on non-externally visible code elements.
        public override TargetVisibilities TargetVisibility
        {
            get
            {
                return TargetVisibilities.All;
            }
        }
 
        public override ProblemCollection Check(Member member)
        {
            Visit(member);
            return this.Problems;
        }
 
        public override void VisitMethod(Method method)
        {
            bool isCatchExists = false;
            bool isThrowExists = false;
            if (method != null)
            {
                InstructionCollection iList = method.Instructions;
 
                for (int i = 0; i <= iList.Count(); i++)
                {
                    if (iList[i].OpCode == OpCode._Catch)
                    {
                        isCatchExists = true;
                    }
 
                    if (isCatchExists)
                    {
                        // Checking for throw 
                        if (iList[i].OpCode == OpCode.Throw)
                        {
                            isThrowExists = true;
                        }
                    }
 

                    if (isCatchExists)
                    {
                        //If the call is not made to HandleError method. 
                        if (!isThrowExists)
                        {
                            Resolution resolu = GetResolution(new string[] { method.ToString() });
                            Problems.Add(new Problem(resolu));
                        }
                    }
                }
            }
                base.VisitMethod(method);
        }
 
    }
 
}
 
All the references are from "C:\program files (x86)\Microsoft Visual Studio 11.0\Team Tools\Static Analysis Tools\FxCop" folder.
 
Following is the EmptyCatchBlockMetadata.xml as embedded resource.
 
<?xml version="1.0" encoding="utf-8" ?>
<Rules FriendlyName="Custom FxCop Rules">
  <Rule TypeName="EmptyCatchBlock" Category="iXCRules" CheckId="IX1001">
    <Name>Find Empty Catch Block</Name>
    <Description>Checks methods for empty catch blocks.</Description>
    <Url />
    <Resolution>Method {0} has empty catch block. Catch block should not be empty.</Resolution>
    <MessageLevel Certainty="100">Error</MessageLevel>
    <FixCategories>NonBreaking</FixCategories>
    <Email />
    <Owner />
  </Rule>
</Rules>
 

Then opened new instance of VS 2012 for creating new ruleset file. But I am not able to see the created rule(which is in dll) in editor. Can you please help?
Thanks
Upendra

QuestionGood Article!membershielo5 Feb '12 - 20:54 
Hi!
 
Thank you for this good article but I tried it using FxCop 10.0 and it didn't work. It says The assembly contains no FxCop rules. Can you help me with this?
 
Thanks,
 
xmione
_______________________________________________________________
Life is a continuous progress. If it isn't, it isn't life...-xmione(that's me)

QuestionHi,I am new in fxcop.I want to write my own custom rule.But my question is can I fetch and check the actual code from fxcop rule.eg-if my code is something like using System.Data;using System.Text;class test(){int i=0;}then can i get the value of linmembersouravghosh186 Sep '11 - 4:01 
&><
GeneralIn FXCop under myrules i am not able to see the rulesmembertechinical23 Dec '10 - 6:48 
Hi I am beginner.
As mentioned in the article i have created the project and i have attached the dll in the rules tab of FXCop and it shows dll name but there is no child nodes to that dll. How can i resolve this issue. Help would be much appreciated.
 
-lbmanikandan
GeneralRe: In FXCop under myrules i am not able to see the rulesmembertechinical23 Dec '10 - 18:31 
Hi now i am not able load dll in the FXCop as it is throwing error "Unable to load rule assembly 'D:\MyRules\output\MyRules.dll': The assembly contains no FxCop rules.
 
Kindly let me know how to resolve this error.
GeneralRe: In FXCop under myrules i am not able to see the rulesmembertechinical24 Dec '10 - 2:58 
Thanks all, now the problem has been solved.
 
What i did to resolve this problem:
1) Select Rules xml file, Click F4 (Properties window will display), i have mentioned "Embedded Resource" for "Build Action" option.
2) Project Namespace (MyCustomRule) has to be provided correctly in the below constructor.

public cdataReaderChk() : base("DataReaderCheck", "MyCustomRule.Connection", typeof(cdataReaderChk).Assembly)
{
}
 
-Mani
GeneralI am not able to see the Rule in FxCop 1.36membernaveen.gundu27 Jan '09 - 18:56 
Hi,
I have created a new Rule, and followed exactly as the sample source code provided by you but still I am not able to see the Rule in FxCop after adding the Rule DLL. Could you please help me to resolve this issue.
 
Thanks,
Naveen
GeneralRe: I am not able to see the Rule in FxCop 1.36memberRajesh KS27 Jan '09 - 23:41 
Add rule XML file as embedded resource. If you use 'ildasm Rule.dll' - manifest should contain following resource details. Then only rules will appear.
 
.mresource public MyRules.Connection.xml
{
// Offset: 0x00000000 Length: 0x00000208
}
GeneralRe: I am not able to see the Rule in FxCop 1.36memberShivprasad koirala28 Jan '09 - 0:13 
I had the same problem check out your XML file, especially the type name. Second you can attach to the FXCOP exe to check if it atleast invoked the DLL.
 
Footprints on the sand are not made by sitting at the shore.

GeneralRe: I am not able to see the Rule in FxCop 1.36membernaveen.gundu28 Jan '09 - 0:16 
Select the XML Properties in Visual Studio -> set the Build action to "Embedded Resource". Please refer to answer given by Rajesh KS.
 
Thanks,
Naveen
GeneralGreat enjoyed both the tutorial FXCOP and StyleCOPmemberhemasarangpani25 Nov '08 - 20:29 
Nice keep it up
GeneralFeedbackmemberSadadevguru4 Nov '08 - 1:38 
many people get stuck with the rules.xml file i think you should explain that in more detail. Second you should also talk about automatic compilation with VS.NET IDE
GeneralFxCop is not about 'code review' at allmemberThomas Weller3 Nov '08 - 23:05 
You wrote: "FXCOP is one of the legendary tools which help us automate code reviews."
 
What? Am I missing something? This is simply wrong! D'Oh! | :doh:
 
FxCop does not analyze the source code, it analyzes compiled IL-Assemblies!
 
To analyze the source code of a project, use MS StyleCop instead. StyleCop is for source code what FxCop is for MSIL.
 
Don't confuse these two kinds of analysis - they apply to two different kinds of software artifacts, and you should use them differently, although they can be partially used to fulfill the same needs. But in my view it makes no sense at all to check coding guidelines or something for an already compiled assembly.
 
Sorry, but you should be much more accurate if you'd like to explain something to other people. Suspicious | :suss:
 
Regards
Thomas
GeneralRe: FxCop is not about 'code review' at allmemberShivprasad koirala4 Nov '08 - 1:31 
The difference between stylecop and FXCOP is the first uses the direct code while the second the IL assembly. I have shown a actual example of code review in the above example. If you see the DOM of FXCOP you can see the instruction object exposed which has the code. Finally all code written either in C# or VB.NET boils down to IL code. So if you review that you are already revewing the code.
 
I know exactly what i have written and i stick to it. Its a legendary tool which helps us to automate code reviews.
 
Regards
Shiv
 
Footprints on the sand are not made by sitting at the shore.

GeneralRe: FxCop is not about 'code review' at allmemberThomas Weller4 Nov '08 - 1:55 
The IL is NOT the code!!
There is only a loose connection between the two.
 
One common reason for that are compiler optimizations.
For example, when a switch on a string has more than 6 cases, the C# compiler estimates that it is worth creating a generic Dictionary<string,int> and to do the switch on the hash value of the string.
 
If you don't believe me, then have a look at the IL of the following method (using the 'legendary' .NET Reflector):

public static int Method(string s) 
{
   switch (s) 
   {
      case "1":
         return 1;
      case "2":
         return 2;
      case "3":
         return 3;
      case "4":
         return 4;
      case "5":
         return 5;
      case "6":
         return 6;
      case "7":
         return 7;
      default:
         return 0;
   }
}
 
Or what if you are using an aspect weaver like PostSharp.Laos? Or some other kind of compiler enhancement? Again, the IL will be quite different from the original source.
 
I repeat it again: What you are saying is completely wrong! Sigh | :sigh:
 
Regards
Thomas
GeneralRe: FxCop is not about 'code review' at allmemberShivprasad koirala4 Nov '08 - 2:00 
Ooops what you said is right. The code and IL code does not have one to one mapping. I bought your point i will correct the article. I accept the definition is wrong and what you said is right it can work partially like that but not in a full proof way.
 
Footprints on the sand are not made by sitting at the shore.

GeneralRe: FxCop is not about 'code review' at allmemberSadadevguru4 Nov '08 - 1:36 
When you analyze assemblies you analyze code....I do not find anything wrong in the article. The best part of IL analyzation is that it is independent of C# and VB.NET.
GeneralRe: FxCop is not about 'code review' at allmemberThomas Weller4 Nov '08 - 2:11 
Sadadevguru wrote:
When you analyze assemblies you analyze code..

 
That's simply not true. You analyze IL instructions that were generated by the compiler - and probably some other tools. This can make a big difference. See this post for an explanation and an example.
 
Regards
Thomas
GeneralRe: FxCop is not about 'code review' at allmemberHrienTYadava4 Nov '08 - 1:52 
Well Stylecop only works only for C# i think. Must be i am wrong. I think the article wording is wrong. But yes it definetly helps analyzing code. I think the article should specify it analyzes IL code.....But does it matter finally it does gives us the output of the code quality.
GeneralRe: FxCop is not about 'code review' at allmemberThomas Weller4 Nov '08 - 2:06 
HrienTYadava wrote:
finally it does gives us the output of the code quality

 
It gives as an impression of the quality of the compiler output, not necessarily about the source code. Here are some reasons for that. And this matters a great big lot, when it comes to testing real world applications!
 

HrienTYadava wrote:
Stylecop only works only for C# i think

As far as I know, that's correct.
 
Regards
Thomas
GeneralRe: FxCop is not about 'code review' at allmvpNishant Sivakumar4 Nov '08 - 8:22 
Indirectly, FxCop serves as a kind of code analysis tool. In fact, if you run Code Analysis in Visual Studio 8, it's FxCop that comes into play. We use it at work and it's been very helpful in pointing out areas where we can improve the code (naming, use of properties, return types, collection types, globalized method calls etc.). So while his statement may have been wrong pedantically, it's not all that wrong in practice.
 

GeneralRe: FxCop is not about 'code review' at allmemberThomas Weller4 Nov '08 - 19:00 
Nish,
I did not want to make a point against FxCop or using FxCop. It is indeed a really helpful tool. I use it myself in my projects, both on developers workstations and as part of an automated integration build and analysis process. I just wanted to point out that it is not the source code document but the compiled assembly that FxCop analyzes. Of course the assembly normally mirrors the source code very closely, and in that case my distinction may really have sort of a 'pedantic' smell. But sometimes it can make a huge difference. And furthermore, FxCop goes only half way down the road of analyzing potential defect sources. (For example FxCop cannot be used to enforce a companies coding style guidelines.)
 
Nishant Sivakumar wrote:
Indirectly, FxCop serves as a kind of code analysis tool.

Sure, it is often used for that. And it does well, as long as you know what exactly it is you are analyzing.
 

Nishant Sivakumar wrote:
In fact, if you run Code Analysis in Visual Studio 8, it's FxCop that comes into play.

No argument here. StyleCop integrates into VS 8 as well as FxCop (except it is not automatically downloaded), even much better if you use it in combination with Resharper...
 

Nishant Sivakumar wrote:
So while his statement may have been wrong pedantically, it's not all that wrong in practice.

There is not such a thing as 'wrong in practice' - there's only right or wrong. It's about knowing what you're doing and stating it clearly. Sigh | :sigh: (And this is especially true when you write introductory articles for newbies, since they normally believe what you are saying...)
 
Regards
Thomas
QuestionRe: FxCop is not about 'code review' at allmemberravithejag19 Jun '12 - 21:03 
When i run an fxcop in my program it is showing lot of errors,
when i checked it even if it is not an error it is showing errors
Is there any problem with the SDK?

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 25 Nov 2008
Article Copyright 2008 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid