Here's some code to enumerate FXCop rules , the input is a path to a folder containing assemblies that implement the rules, the output is an XML file that lists all the rules by assembly. I needed the list to import into a db.
The function loads an assembly and searches for classes that implement the interface IRule (defined in the FXCop SDK), it then queries the interface for the rule Name & Description, the type name of the class that implements the rule is also descriptive of what the rule does, it's included in the XML output too.
using System;using System.Reflection;using System.IO;using System.Xml;using Microsoft.Tools.FxCop.Sdk;
namespace FXCopRuleEnumerator{ class App {
[STAThread] static void Main(string[] args) { if (args.Length != 1) return;
string assemblyFolder = args[0];
XmlDocument doc = new XmlDocument(); XmlNode rootNode = doc.CreateNode(XmlNodeType.Element,"rules",null); doc.AppendChild(rootNode);
foreach (string assemblyPath in Directory.GetFiles(assemblyFolder)) { EnumerateRules(assemblyPath,doc); } Console.WriteLine(doc.OuterXml); }
static void EnumerateRules(string assemblyPath,XmlDocument doc) { Assembly assembly = Assembly.LoadFrom(assemblyPath);
XmlNode assemblyNode = doc.CreateNode(XmlNodeType.Element,"assembly",null); doc.DocumentElement.AppendChild(assemblyNode);
int countRules = 0;
foreach (Module module in assembly.GetModules()) { foreach (Type type in module.GetTypes()) { if (type.IsClass && !type.IsAbstract) {
ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes); if (ctor != null) { object o = ctor.Invoke(null); IRule aRule = o as IRule; if (aRule != null) { countRules++;
XmlNode ruleNode = doc.CreateNode(XmlNodeType.Element,"rule",null); assemblyNode.AppendChild(ruleNode);
XmlNode childNode = doc.CreateNode(XmlNodeType.Element,"Type",null); childNode.InnerText = type.Name; ruleNode.AppendChild(childNode);
childNode = doc.CreateNode(XmlNodeType.Element,"Name",null); childNode.InnerText = aRule.Name; ruleNode.AppendChild(childNode); childNode = doc.CreateNode(XmlNodeType.Element,"Description",null); childNode.InnerText = aRule.Description; ruleNode.AppendChild(childNode); }
} }
XmlAttribute attribute = doc.CreateAttribute("","name",""); attribute.Value = assembly.FullName; assemblyNode.Attributes.Append(attribute);
attribute = doc.CreateAttribute("","count",""); attribute.Value = countRules.ToString(); assemblyNode.Attributes.Append(attribute); } }
}