Friday, September 26, 2008

Example Rule - Private fields should have correct prefix i.e. “_”

Example Rule - Private fields should have correct prefix i.e. “_”



1. Create a ClassLibrary name is PrivateFieldShouldHaveCorrctPrefix.

2 .Add following dll references to project-

FxCopSdk.dl

Microsoft.Cci.dll

These two assemblies are located in the Program Files\Microsoft FxCop 1.36 folder.

3. Add one xml file “PrivateFieldRules.xml” to the project “PrivateFieldShouldHaveCorrctPrefix”.

3.a. Xml file name should end with ‘Rules’.

3 b. Go to properties of PrivateFieldRules.xml and set Build Action to “Embedded Resource”.

3 c. PrivateFieldRules.xml is given below-



Private fields should have correct prefixName>

Prefix private fields names with the correct prefix.Description>

/Naming/IdentifiersShouldHaveCorrectPrefix.htmlUrl>

Prefix field name '{0}' with '{1}'.Resolution>

ErrorMessageLevel>

NonBreakingFixCategories>

vipul.arwade@gmail.comEmail>

VIpulArwadeOwner>



4. Add one class file BaseRule.cs to project ‘PrivateFieldShouldHaveCorrctPrefix’.


4 a. Add following namespaces –

1) Microsoft.FxCop.Sdk

2) Microsoft.FxCop.Sdk.Introspection



4 b. Wrie a class BaseRule which should inherited from ‘BaseIntrospectionRule’ class.



public abstract class BaseRule : BaseIntrospectionRule

{

protected BaseRule(string name)

: base(name, "PrivateFieldRule.PrivateFieldRules", typeof(BaseRule).Assembly){ }

}



Constructor of class should pass name of class which actually implements the rule (Here the class name is ‘PrivateFieldRule’), name of xml file which describes the rule and assembly data of class itself.

Here actual implementer class sends a name of itself to BaseRules class through the constructor.


5 Add another class file PrivateFieldRule.cs which actually implements the class.



public class PrivateFieldRule : BaseRule

{

private const string FIELD_PREFIX = "_";

public PrivateFieldRule() : base("PrivateFieldRule"){ }



public override TargetVisibilities TargetVisibility

{

get { return TargetVisibilities.NotExternallyVisible; }

}

public override ProblemCollection Check(Member member)

{

Field field = member as Field;


/ / Is the provided member a field?

if (field == null)

return null;


/ / We are only interested in private fields

if (!field.IsPrivate)

return null;


// ignore constants and fields with special names

if (field.IsLiteral || field.IsSpecialName)

return null;

string name = field.Name.Name;


/ / Ignore compiler generated event backing stores

if (RuleUtilities.IsEventBackingField(field))

return null;

if (!name.StartsWith(FIELD_PREFIX))

Problems.Add(new Problem(GetNamedResolution("Prefix", name, FIELD_PREFIX), field));

return Problems;

}

}



In this class,I am overriding check method and passing instance of member.This rule tells that each private member must start with ‘_’.

i.e. private int _rollNumber;



6. Add a custom rule assembly i.e. PrivateFieldShouldHaveCorrctPrefix.dll to Visual Studio Code Analysis, copy this dll to \Program Files\Microsoft Visual Studio 9.0\Team Tools\Static Analysis Tools\FxCop\Rules, where c:\ reflects the drive where Visual Studio is installed.



This rule gives an error /warning (which one you like to set) when anyone violate the rule .

Create your own custom rules

Create your own custom rules:

The first step in creating a custom FxCop rule is creating a Visual Studio project for the assembly that will contain the rule (assuming, of course, that such a project doesn't already exist for hosting existing custom rules). This project should generally be a plain-vanilla library project. Since you're presumably something of a quality nut if you're bothering to create custom FxCop rules, you'll presumably want to verify that the following options are set for all configurations of your project:

· The warning level is set to 4.

· No warnings are excluded.

· Warnings are treated as errors.

· XML documentation output is enabled.

If you're using a Visual Studio edition that supports static analysis, analysis should be enabled, and all rules should be set to generate errors rather than warnings.

FxCop rules are organized into DLL assemblies (which can be created as Class Library projects in Visual Studio).Each assembly, when loaded into FxCop, displays its rules in the GUI as leaf nodes in a hierarchical tree.Each rule assembly should directly reference two assemblies provided with FxCop. These two assemblies are located in the Program Files\Microsoft FxCop 1.36 folder:

· FxCopSdk.dll

· Microsoft.Cci.dll

The only namespace that needs to be imported to use the API is Microsoft.FxCop.Sdk.

Visual Studio Team System: To add a custom rule assembly to Visual Studio Code Analysis, copy the DLL to c: \Program Files\Microsoft Visual Studio 9.0\Team Tools\Static Analysis Tools\FxCop\Rules, where c:\ reflects the drive where Visual Studio is installed.

To create Custom rule your project should contain following three files – (Third file is optional)

1) Rule metadata xml file

2) Base rule file

3) Actual rule file (Optional-you can implement the rule in base rule also)



1) Rule Metadata XML



Each rule assembly contains an XML resource defining metadata for all of the rules in the assembly. In Visual Studio,the addition of this resource to your project can be accomplished by adding an XML file and then marking the file as an "Embedded Resource" in the Visual Studio properties window.





FriendlyName The display name of the rule library as it will appear in the FxCop GUI rules tree.

TypeName The name of the .NET class that implements the rule. Do not qualify with a namespace.

Category The category of the rule. This should generally be a programmatic version of FriendlyName.

CheckId An identifier that distinguishes the rule from all others in the same Category.

The display name of your rule as it will appear in the leaf level of the FxCop GUI rules tree.

Description A description of your rule.

Url A URL associated with the rule that can be used to provide even more information about thee rule.

Resolution A short suggestion on how to fix the violation. It may contain String.

MessageLevel The severity of the error: CriticalError, Error, CriticalWarning, or Warning.

Certainty The certainty is an integer from 0 to 100 that indicates how often the rule typically detects a real problem in the code.

Email An email address to be associated with the rule for display to the user.

OwnerThe person who "owns" the rule for display to the user. Often left empty.



2) Base rule file



The base rule implementation technique is to override suitable overload(s) of the BaseIntrospectionRule.Check method in order to add code that implements your rule verification logic.



For example



public abstract class BaseRule : BaseIntrospectionRule

{

protected BaseRule(string name):

base(name, "ProjectName.RuleMetadataXMLName", typeof(BaseRule).Assembly{}

}



In this BaseRule is inherited from BaseIntrospectionRule.The actual implemetor class of the rule passes name of the class itself which tells that it has actual implementation of rule. Also BaseRule class passes three parameters to BaseIntrospectionRule are name of the class which actualy implements the rule,name of metadata xml file which contains all the extra information about the rule and third is assebly information of BaseRule.You can implement actual rule here also.



3) Actual rule implementer file



This is optional.We should write actual implementation of rule because for simplicity and exendibility of number of rules.

Most FxCop rules start out by calling either the Check or VisitCall method. Then, once a rule violation has been determined, return a Problem or ProblemCollection after making a call to the GetResolution method to retrieve the rule information such as, message, resolution, certainty level, etc. from the XML file.



For example-



public class ActulImplementerClassOfRule : BaseRule

{

private const string FIELD_PREFIX = "_";

public ActulImplementerClassOfRule ()

: base("ActulImplementerClassOfRule") { }

public override TargetVisibilities TargetVisibility

{

get { return TargetVisibilities.NotExternallyVisible; }

}

public override ProblemCollection Check(Member member)

{

//logic to check member

//which not follows the rule

return Problems;

}

}

By developing FxCop customizations, you can

By developing FxCop customizations, you can:



Ensure that the names of controls on forms and web pages follow your naming conventions.


• Check that your preferred controls, components, and classes are used instead of alternatives.


• Inspect literal argument values being passed to your methods.


• Examine control structures, such as conditions and loops, to evaluate code metrics.


• Determine the callers and callees of methods.


• Spell-check text elements such as identifiers, literals, and resource strings.


• Verify that elements are properly documented with XML documentation comments.


• Build standalone tools that take advantage of FxCop's code analysis APIs.

The kinds of rules checked by FxCop

FxCop will typically be used by the following people:


1. Developers use FxCop continuously during development, because it helps with familiarising themselves with the .NET coding best practices.

2. Code reviewers use the tool to verify that developers are indeed complying with the best practices as defined in the rule set.

The kinds of rules checked by FxCop include:



• Design

• Globalization

• Interoperability

• Mobility

• Naming

• Performance

• Portability

• Security

• Usage

Wednesday, September 17, 2008

What is FxCop ?

What is FxCop ?



FxCop analyses programming elements in assemblies, called targets, and provides an informational report containing messages about the targets. FxCop represents the checks it performs during an analysis as rules. A rule is managed code that ‘analyses a target ‘and returns a message about its findings. Rule messages identify any relevant programming and design issues and, when possible, supply information on how to fix the target. Suggested improvements are often based on the .NET Framework Design Guidelines, which are, aswe have already learnt, Microsoft’s guidelines for writing robust and easily maintainable code using the .NET Framework.

FxCop analyses .NET assemblies for potential code compliance problems and forms part of static code analysis. With static code analysis the compiled code is checked for compliance to identify possible defects before executing the code.


FxCop is a mature tool. The first version of FxCop was released to the public shortly after the release of the .NET Framework 1.0 itself in 2002. In summer 2007, FxCop was awarded the Chairman's Award for Engineering Excellence by Microsoft chairman Bill Gates. This award reflected the substantial improvement FxCop has made to development and testing practices of managed code at Microsoft. FxCop is now integrated with Visual Studio as a part of the Visual Studio Team System code analysis features.



The .NET Framework includes an API for examining assembly metadata in the System.Reflection namespace. Rules in early versions of FxCop examined code directly through the reflection API. However, reflection has some limitations that become evident when used in a tool such as FxCop.


FxCop solves this problem by providing an alternate, similar technology called introspection. The API is similar to reflection but offers generally improved analysis features and is overall more suitable for FxCop than the reflection API.


Some of the less frequently used node types are Node,AssemblyReference,AttributeNode,Expression,(numerous),Instruction,Member,EventNode,EventNode,Field,Method,InstanceInitializer,StaticInitializer ,PropertyNode,TypeNode, ClassNode, DelegateNode, EnumNode,InterfaceNode, Struct ,ModuleNode, AssemblyNode, ModuleReference, SecurityAttribute, Statement.