Thursday, September 9, 2010

Vs2010 Code Analysis Custom Rules

I've written my first custom rules for visual studio to help me on my team with the written and unwritten rules. It was a long journey but I have the hang of it. These rules are set to run on every debug build I do and take about 8 seconds to run all.

 As I understand it custom rules ( Inherited from Microsoft.FxCop.Sdk) can also be used as code check in policies on TFS or in the build process to produce a nice xml report.

Here's the base class (.net 4.0 class library project type)


using Microsoft.FxCop.Sdk;
 
public abstract class BaseRule:BaseIntrospectionRule
{
 protected BaseRule(string ruleName)
  : base(
   ruleName,
   //typeof(BaseRule).Assembly.GetName().Name+".Rules"
   "ProjectNamespace.RuleMetadata",
   typeof(BaseRule).Assembly
   ) { }
}


This class was defined without a namespace, I believe it did not work while it was in one. It's also quite important to note that the string literal Must match your project namespace+xml filename without the .xml on it. The commented method may work as well if your xml file is called Rules.xml. This file must be set to Embedded Resource.

Rules can be set as Messages, Warnings, or Errors and show up in the standard Error List control if code analysis is turned on in your project.

The general classes of rules I have written so far include:

  • Do not use method - Things like GC.AddMemoryPressure, MessageBox.Show (we use a custom dialog with styling)
  • Do not inherit - We don't want anyone inheriting from Windows.Forms.Form
  • Do not raise- We don't want code that has NotImplementedExceptions still present.
  • UseHungarian for controls
    • uses a dictionary to determine if the control has a preferred name we use on the team.
  • Fields should be private
  • Control Property must be set to x
    • For example, in most cases we want all dialog border styles to be fixed - I check the Initialize Component method of anything that inherits from Form for the property to be set there.
  • MustOverride - For legacy reasons (old Visual Studio bug they tell me) we have methods/properties that are virtual instead of abstract, and if they aren't overridden will throw a runtime exception.

2 comments:

  1. Hi guy,
    Thanks for your post.
    I need some help for the "Control Property must be set to x" rule.

    I tried to override VisitMemberBinding(MemberBinding memberBinding) this way :
    Member m = memberBinding.BoundMember;
    if (mName.Name.Equals("set_StartPosition"))
    {
    //TODO check value is CenterParent
    }
    with no success so far...
    Regards

    ReplyDelete
  2. Try this out, see if it helps:

    http://ideone.com/kZp64

    ReplyDelete