Click here to Skip to main content
15,880,469 members
Articles / Web Development / ASP.NET

7 Steps to Write Your Own Custom Rule using FXCOP

Rate me:
Please Sign up or sign in to vote.
4.56/5 (26 votes)
25 Nov 2008CPOL4 min read 166K   1.4K   75   31
7 steps to write your own custom rule using FXCOP

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.

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.

Image 1

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.

Image 2

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.

Image 3

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
<?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.

Image 4

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

C#
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. 

C#
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.

C#
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.

C#
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.

C#
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.

C#
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.

Image 5

For further reading do watch the below interview preparation videos and step by step video series.

License

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


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
QuestionAutomatically inherit a web page from a custom base class Pin
mahendra.Net12-Feb-16 1:29
mahendra.Net12-Feb-16 1:29 
QuestionTrouble in returning a variable back to resolution Pin
Shivangi_K20-May-15 19:33
professionalShivangi_K20-May-15 19:33 
QuestionHow do i Check my Windows Forms Application's Compiled Dll against FxCop. Pin
naveenprasadsomasundaram19-Feb-15 1:42
naveenprasadsomasundaram19-Feb-15 1:42 
QuestionFXCOP Custom Code............ Pin
Simbu Murugesan17-Jun-13 2:42
Simbu Murugesan17-Jun-13 2:42 
QuestionRule not getting listed in Ruleset editor in VS2012 Pin
Upendra Jagdale4-Apr-13 18:54
professionalUpendra Jagdale4-Apr-13 18:54 
QuestionGood Article! Pin
shielo5-Feb-12 20:54
shielo5-Feb-12 20:54 
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 lin Pin
souravghosh186-Sep-11 4:01
souravghosh186-Sep-11 4:01 
GeneralIn FXCop under myrules i am not able to see the rules Pin
techinical23-Dec-10 6:48
techinical23-Dec-10 6:48 
GeneralRe: In FXCop under myrules i am not able to see the rules Pin
techinical23-Dec-10 18:31
techinical23-Dec-10 18:31 
GeneralRe: In FXCop under myrules i am not able to see the rules Pin
techinical24-Dec-10 2:58
techinical24-Dec-10 2:58 
GeneralI am not able to see the Rule in FxCop 1.36 Pin
naveen.gundu27-Jan-09 18:56
naveen.gundu27-Jan-09 18:56 
GeneralRe: I am not able to see the Rule in FxCop 1.36 Pin
Rajesh KS27-Jan-09 23:41
Rajesh KS27-Jan-09 23:41 
GeneralRe: I am not able to see the Rule in FxCop 1.36 Pin
Shivprasad koirala28-Jan-09 0:13
Shivprasad koirala28-Jan-09 0:13 
GeneralRe: I am not able to see the Rule in FxCop 1.36 Pin
naveen.gundu28-Jan-09 0:16
naveen.gundu28-Jan-09 0:16 
GeneralGreat enjoyed both the tutorial FXCOP and StyleCOP Pin
hemasarangpani25-Nov-08 20:29
hemasarangpani25-Nov-08 20:29 
GeneralFeedback Pin
Sadadevguru4-Nov-08 1:38
Sadadevguru4-Nov-08 1:38 
GeneralFxCop is not about 'code review' at all PinPopular
Thomas Weller3-Nov-08 23:05
Thomas Weller3-Nov-08 23:05 
GeneralRe: FxCop is not about 'code review' at all Pin
Shivprasad koirala4-Nov-08 1:31
Shivprasad koirala4-Nov-08 1:31 
GeneralRe: FxCop is not about 'code review' at all Pin
Thomas Weller4-Nov-08 1:55
Thomas Weller4-Nov-08 1:55 
GeneralRe: FxCop is not about 'code review' at all Pin
Shivprasad koirala4-Nov-08 2:00
Shivprasad koirala4-Nov-08 2:00 
GeneralRe: FxCop is not about 'code review' at all Pin
Sadadevguru4-Nov-08 1:36
Sadadevguru4-Nov-08 1:36 
GeneralRe: FxCop is not about 'code review' at all Pin
Thomas Weller4-Nov-08 2:11
Thomas Weller4-Nov-08 2:11 
GeneralRe: FxCop is not about 'code review' at all Pin
HrienTYadava4-Nov-08 1:52
HrienTYadava4-Nov-08 1:52 
GeneralRe: FxCop is not about 'code review' at all Pin
Thomas Weller4-Nov-08 2:06
Thomas Weller4-Nov-08 2:06 
GeneralRe: FxCop is not about 'code review' at all Pin
Nish Nishant4-Nov-08 8:22
sitebuilderNish Nishant4-Nov-08 8:22 

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.