Go to DotNetFunda.com
 Online : 1771 |  Welcome, Guest!   Login
 
Home > Articles > ASP.NET > 7 Steps to write your own custom rule using FXCOP

  • Download the OOPS, ASP.NET and ADO.NET Training Videos for FREE, click here.

Submit Article | Articles Home | Search Articles |

7 Steps to write your own custom rule using FXCOP

 Download source file
 Posted on: 11/3/2008 6:18:31 AM by Questpond | Views: 3053 | Category: ASP.NET | Level: Advance | Print Article
Code review is one of the important activities in any project. Manual code reviews are definitely good and I will say better than automation. But when the project is large manual code reviews have their own limitations. FXCOP is one of the legendary tools which help us automate code reviews. This article will discuss some basics of FXCOP and then concentrate mainly on how we can add custom rules in FXCOP.

.NET Training Videos!
Buy online comprehensive training video pack just for $35.00 only, see what's inside it.

7 Steps to write your own custom rule using FXCOP
 


Introduction

Basic of FXCOP

Using the Existing rules

Adding a custom rule all Connection object should be closed

Step 1

Step 2

Step 3

Step 4

Step 5

Step 6

Step 7

 

 

Introduction
 

Code review is one of the important activities in any project. Manual code reviews are definitely good and I will say better than automation. But when the project is large manual code reviews have their own limitations. FXCOP is one of the legendary tools which help us automate code reviews. 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 lot of architecture related videos on design patterns, UML, FPA estimation, Enterprise application blocks, C# projects etc you can watch my videos on http://www.questpond.com
 

Basic of FXCOP
 

As the name suggest FXCOP where COP means the police. So it’s a code analysis tool which runs rules against the .NET assemblies and gives a complete report about the quality of the project. 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 http://www.microsoft.com/downloads/details.aspx?familyid=3389F7E4-0E55-4A4D-BC74-4AEABB17997B&displaylang=en 

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

Using the Existing rules
 

Using 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 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 object 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 a 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 in the 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 reference to the FxCopSdk.DLL. You can find the FxCopSdk.dll where FxCop is installed.
 

Once you have added 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 ‘BaseIntrospectionRule’ class of FxCop. So below is the a 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 covert the member in to the Method object. We have defined two Boolean variables one which specifies that the a connection object has been opened and the second that connection object has been closed.
 

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

Step 5 :- Every method has a instruction collection which is nothing but the actual code. So we loop through all instructions and check do we find the string of SQLConnection if yes we set the Boolean value of 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 than 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 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.



You can download the source code which is attached with the article


If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Interesting?   Share and Bookmark this kick it on DotNetKicks.com


Experience:0 year(s)
Home page:http://www.questpond.com
Member since:Wednesday, September 03, 2008
Level:HonoraryPlatinum
Status: [PanelMember] [Member] [MVP] [Administrator]
Biography: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. You can visit about my organization at http://www.questpond.com and also enjoy the videos uploaded for Design pattern, FPA , UML ,Share Point,WCF,WPF,WWF,LINQ, Project and lot. I am also actively involved in RFC which is a financial open source madei in C#. It has modules like accounting , invoicing , purchase , stocks etc.
 Latest post(s) from Questpond

   ◘ 4 steps to consume web services using Ajax (Includes Video tutorial) posted on 2/20/2010 9:16:32 AM
   ◘ 7 simple steps to run your first Azure Queue program posted on 2/11/2010 12:48:49 AM
   ◘ Simple 5 steps to expose WCF services using REST style posted on 2/1/2010 5:50:38 AM
   ◘ SQL Query Optimization FAQ Part 1 (With video explanation) posted on 1/28/2010 5:34:05 AM
   ◘ Simple 7 steps to run your first Azure Blob Program posted on 1/24/2010 7:08:28 AM


Submit Article

About Us | The Team | Advertise | Contact Us | Feedback | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found copied contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
All rights reserved to DotNetFunda.Com. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks.
(Best viewed in IE 6.0+ or Firefox 2.0+ at 1024 * 768 or higher)