Microsoft XAML Toolkit CTP – July 2010: FxCop Rule Authoring

The XAML toolkit, announced here and downloadable here, provides a number of FxCop rules for analyzing your XAML.  This post describes how the XAML Toolkit also helps you write FxCop rules. 

Writing an FxCop Rule

There are resources on the net describing how to write an FxCop rule.  You can read the original MSDN article here or a newer posting on the FxCop team blog here.  The difference here is that the XAML Toolkit has already sub-classed the BaseIntrospectionRule with the BaseXamlRule.

BaseXamlRule implements the Check(Resource resource) method.  This method will:

  • Find the XAML/BAML resource
  • Determine the resource’s type (Silverlight, WPF, other),
  • Load the proper Schema Context
  • Load the XAML or BAML content into a XAML DOM
  • Calls a new abstract method CheckXaml()
    1: public abstract void CheckXaml(XamlDomObject rootObjectNode,
    2:                                XamlSchemaContext schemaContext,
    3:                                string resourceName);

 

To implement a XAML FxCop rule you implement the CheckXaml() method, and not the Check() method.

Restricting rules

Not all XAML rules apply to all flavors of XAML.  For example you might write a rule that should only run with Silverlight XAML.  For this purpose the BaseXamlRule has a virtual method IsRuleValidForXamlFlavor().

 

    1: internal virtual bool IsRuleValidForXamlFlavor(ResourceType xamlFlavor)
    2: {
    3:     return true;
    4: }

The values of ResourceType are:

    1: internal enum ResourceType
    2: {
    3:     SimpleXAML,
    4:     Workflow,
    5:     WPF,
    6:     Silverlight
    7: }

You don’t need to implement this method in every XAML rule.  The base implementation returns “true”.  But if you need to exclude your rule from some flavors of XAML you can do it here.