I m glad to share the world with you... ...

Tuesday, May 22, 2007

The sample of self-define the code check rule in VS IDE.

1. To use the FxCop class,  we should reference those classes before hand:
 
using Microsoft.FxCop.Sdk;
using Microsoft.FxCop.Sdk.Introspection;
using Microsoft.Cci;
 
2. Inherite the BaseIntrospectionRule
 
    public abstract class BaseRule : BaseIntrospectionRule
    {
        protected BaseRule(string name)
            : base(name, "msdnwebcastRule.testRules", typeof(BaseRule).Assembly)
        { }
    }

 
3. Inherite the class and implement the checking rules by override the chek functions:
 
    public class TestRule : BaseRule
    {
        private const string FIELD_PREFIX = "_";

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

        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;
        }
    }

Then compile the class lib and put the asembly to the FxCop's rules folder, OK.

No comments: