Using XSLT to generate Performance Counters code

April 11th, 2009

Whenever I’m faced with a project in which I have to create a lot of tedious and repeating code I turn to the power of XML and XSLT. Rather than copy/paste the same code over and over again, just to end up with a refactoring and maintenance nightmare, I create an XML definition file and an XSLT transformation. I am then free to add new elements to the XML definition or to change the way the final code is generated from the XSLT transformation. This can be fully integrated with Visual Studio so that the code generation happens at project build time and the environment shows the generated code as a dependency of the XML definition file.

A few examples of how I’m using this code generation via XSLT are:

Data Access Layer

I know this will raise quite a few eyebrows, but I always write my own data access layer from scratch and is generated via XSLT.

Performance Counters

I create all my performance counters objects via XSLT generation, automating the process of defining/installing them and the access to emit and consume the counter values.

Wire Frames

In any project that has networking communication I access the wire format from classes generated via XSLT that take care of serialization and validation.

For example I’ll show how to create a class library that can be added to your project to expose Performance Counters from your application.

MSXSL.EXE

To start you’ll need to download the Command Line Transformation Utility (msxsl.exe). This is a command line tool that takes an XML and an XSLT file as input and produces the result transformation. As a side note I actually use the same technique on non-Windows platforms, but there of course I use the xsltproc utility.

msxsl.exe has to be placed in a convenient location from where it is accessible by Visual Studio. Download the file and place it in Visual Studio’s Common\IDE folder because the build environment has a macro for it: $DevEnvDir.

The Project

Create a new project in Visual Studio. Choose a C# Class Library type project and save it as “PerformanceCounters”. After the project is created, add to it two new files, from menu Project/Add New Item or press Ctrl+Shift+A. For the first file choose an XML file type and name it Counters.xml. For the second one choose an XSLT file type and name it Counters.xslt.

Next add the step that actually performs XSLT transformation to the project build process. Go to the project properties, either from menu Project/PerformcanceCounters properties... or right-click the project in the Solutions Explorer and select Properties from the context menu. Choose the Build Events pane in the right side navigation tab to get to the pre-build and post-build project events. Click the Edit pre-build... button and add the following command:

This command will run the command line transformation tool (msxsl.exe) and generate the CountersGenerated.cs file each time the project is built, prior to the project being actually built.

Save and close the project properties. The last thing we need now is to add the generated CountersGenerated.cs file to our project. However, we do not want this to be treated as an ordinary source file, we want the IDE to recognize that is a generated file dependent of the Counters.xml file. The way I prefer to do this is to actually manually add it directly into the project definition file. Open the PerformanceCounters.csproj file in your editor, locate the <ItemGroup> containing the Program.cs and insert this snippet:

Save the manually edited .csproj file and open the project normally from Visual Studio. The CountersGenerated.cs file now shows up in the Project Explorer as a generated file depending on Counters.xml:

The warning triangle is shown because the file does not exist on the disk, but don't worry about it as it will be generated shortly.

Defining the Performance Counters

We can go ahead and define the Performance Counters. The counters covering related functionality are grouped together and the groups can be single instance or multiple instance types. I also like to create a manager class that controls the management of the counters taking care of things like deployment during application setup and loading the counters when application starts. So my choice is for a XML like manager/group/counter. Some attributes are needed for the code generation XSLT transformation to know what class names and namespaces to use and some attributes are Performance Counters specific, like the counter types and bases for average counters. For start we'll create a simple counter and a group:

Now we need to set in place the actual XSLT transformation that will generate code as we desire.

The XSTL transformation

We want our XSLT transformation to generate C# code, so we're going to start by a stylesheet that will generate the skeleton of a C# file: the using directives and some comment to warn the user that the file is a generated file and should not be manually modified. Also our XSLT transformation is directed to generate an text output as opposed to the default XML output:

<?xmlversion="1.0"encoding="UTF-8" ?>
<xsl:stylesheetversion="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"xmlns:pc="http://rusanu.com/Schemas/PerformanceCounters/v1.0">
<xsl:outputmethod="text"encoding="utf-8"/>
<xsl:templatematch="/">/* This file was automatically generated during project build.
Do not manually modify this file as updates will be lost.*/
using System;
using System.Diagnostics;

<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>

This skeleton XSLT can be used for any C# code generation, provided of course you modify the appropriate using directives.

Next we should add a template to generate our C# code. How one writes XSLT transformation templates is largely a matter of style and once you get the hang of it it quickly becomes a second nature. XSLT is a fully fledged programming language of its own and you can start thinking at templates in terms of procedures and functions. At least I know I do :). Our XSLT template should do the following:

Identify the manager defined in the XML file and generate a C# class for it.

Generate a class for each performance counter category.

Generate a method for each individual performance counter value to read and increment the counter.

Hook up the manager class to provide methods for deploying and deleting the performance counter categories.

Hook up the manager class with an instance of each performance counter category class.

Hook up the manager to provide loading of the default instance of the performance counters category classes.

Note that the above refer mostly to the SingleInstance performance counter category types. Multiple Instance category are a bitmore complex and I will cover them in my next post.

So what did we achieve? We could had written this code manually in about 5 minutes. But the big advantage comes as we add more counters to our XML definition file. We could expand it to have 10 categories with 15 counters each and it would still generate all the needed counters. And refactoring the code is a breeze. Don't like how the counters are created? Just change the XSLT stylesheet and rebuild the project, all the performance counters creation code wil match your new preference.

In a future post I will cover how to use the performance counters in your projects, how to work with multiple instance counters and how to deal with the pesky AvgTimer32 counter type.