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