Showing posts with label Quality. Show all posts
Showing posts with label Quality. Show all posts

Sunday, August 30, 2015

Create custom code analysis rule using FxCop and use it in visual studio 2013

1. Create a class library project in visual studio
2. Add the references FxCopSdk.dll and Microsoft.Cci.dll. The dll location is "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Team Tools\Static Analysis Tools\FxCop"
3. Create the XML file and name it as RuleMetadata.xml   
<?xml version="1.0" encoding="utf-8" ?>
<Rules FriendlyName="My Custom FxCop Rules">
  <Rule TypeName="EnforceHungarianNotation" Category="MyRules"CheckId="CR1000">
    <Name>Enforce Hungarian Notation</Name>
    <Description>Checks fields for compliance with Hungarian notation.</Description>
    <Resolution>Field {0} is not in Hungarian notation. Field name should be prefixed with '{1}'.              </Resolution>
    <MessageLevel Certainty="100">Warning</MessageLevel>
    <FixCategories>NonBreaking</FixCategories>
    <Url />
    <Owner />
    <Email />
  </Rule>
</Rules> 
4. Create the BaseFxCopRule.cs class
   Note: In below "MyCustomRules.RuleMetadata" MyCutomRules is name space and RuleMetadata is    xml file name which we created above.
using Microsoft.FxCop.Sdk;
namespace MyCustomRules
{
    internal abstract class BaseFxCopRule : BaseIntrospectionRule
    {
        protected BaseFxCopRule(string ruleName)
        : base(ruleName, "MyCustomRules.RuleMetadata", typeof(BaseFxCopRule).Assembly){ }
    }
}
5.Create a EnforceHungarianNotation.cs class which you can wright logic of custom rules.
  Here i we are wright the code for for every static variables should start with s_ and every non static variables should start with m_
using Microsoft.FxCop.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 
namespace MyCustomRules
{
    internal sealed class EnforceHungarianNotation : BaseFxCopRule
    {
        public EnforceHungarianNotation(): base("EnforceHungarianNotation"){ }
        // Only fire on non-externally visible code elements.
        public override TargetVisibilities TargetVisibility
        {
            get{return TargetVisibilities.NotExternallyVisible;}
        }
        public override ProblemCollection Check(Member member)
        {
            Field field = member as Field;
            if (field == null)
            {
                // This rule only applies to fields.
                // Return a null ProblemCollection so no violations are reported for this member.
                return null;
            }
             if (field.IsStatic){ CheckFieldName(field, s_staticFieldPrefix); }
            else { CheckFieldName(field, s_nonStaticFieldPrefix);}
            // By default the Problems collection is empty so no violations will be reported
            // unless CheckFieldName found and added a problem.
            return Problems;
        }
        private const string s_staticFieldPrefix = "s_";
        private const string s_nonStaticFieldPrefix = "m_";
        static int a;
        private void CheckFieldName(Field field, string expectedPrefix)
        {
            if (!field.Name.Name.StartsWith(expectedPrefix, StringComparison.Ordinal))
            {
                Resolution resolution = GetResolution(
                  field,  // Field {0} is not in Hungarian notation.
                  expectedPrefix  // Field name should be prefixed with {1}.
                  );
                Problem problem = new Problem(resolution);
                Problems.Add(problem);
            }
        }
    }
} 
6. After completing above steps build your application. Goto Solution Explore-->right click on solution and build it.
7. copy the dll from the bin folder  to "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Team Tools\Static Analysis Tools\FxCop\Rules " 
8. Now test the rules for same project. Now goto EnforceHungarianNotation.cs class create a static variable
9. run the code analysis on solution we can see the warning CR1000 which we created.