This article describes a mechanism for automating codesnippets. The
code presented using T4 templates to generate attributes for each code snippet. When
the attribute is applied to a class, the snippet code is generated in a partial class,
based on the arguments supplied to the attribute. This approach allows you to change
the values of the codesnippet parameters and regenerate the code, it also removes
repetitive boiler-plate code from your classes, favouring a more concise, declarative
description of the classes capabilities.

I have found this to be a great time-saver and use the same code in every single
Silverlight / WPF project that I work on.

Whilst dependency properties are a pretty extreme case of boiler-plate code, they are
by no means the only example. More recently I started on a project which had a fairly
extensive model-layer. This layer contains numerous classes which implement
INotifyPropertyChanged and properties which raise the event. Again, I
found myself writing lots of boiler-plate code. The
"standard" approach to boiler-plate code is to
use codesnippets and I found myself adding new snippets for the various code patterns
we used within the modules. This accelerates development, but still generates lots of
code that is not refactor friendly and does nothing to enhance the readability of the
code.

If I could somehow combine the versatility of codesnippets with the convenience of the
declarative code generation, this would be a nice solution to all my boiler-plate code
issues. This article describes the solution I came up with.

This article and the code it presents makes use of T4 templates, a mechanism which is
built-in to Visual Studio for the generation of sourecode from a template, i.e. code
which generates code. For a quick introduction to T4 template I would recommend my
earlier
article on codeproject.

You don"t need to know all the ins-and-outs of T4 templates to use
this code-generation technique. Probably all you need to know is that T4 templates are
text files with a ".tt" extension that are
executed whenever their contents is changed, the solution is built, or the following
button is clicked:

So, if you are using the technique described in this article, whenever you add or
remove an attribute from a class and want to update the generated code, simply click
the button above or build the project.

The first step in the process is to convert each codesnippet into an attribute that
can be associated with a class. The attribute should have properties that reflect the
properties of the codesnippet. As an example, the following snippet is one that I
created for adding CLR properties to a class which implements
INotifyPropertyChanged:

To use this snippet declaratively we need an attribute which has the properties, i.e.
type, property, field and defaultValue. There are a number of technologies that could
be used to perform this transformation, for example, you could use Linq to XML to query
the above XML, and construct an attribute (as a string) programmatically. However, I
personally favour XSLT whenever I need to transform XML documents because the templated
approach makes it much easier to visualise the output of the transformation. XSLT is
most often used for XML to XML transformation, although by setting the
"output method" you can transform XML into any
form of text-based output. For example, you can use it to transform XML into SQL, C# or
CSV, it really is a powerful language!

The following simple XSLT document transforms a codesnippet into an attribute:

The transform above is really quite simple, the first template matches the document
root, outputting a namespace and using statement. Any child CodeSnippet
elements are selected in order to output their transformed content within the scope of
the namespace. Note that because the CodeSnippets xml file has a default
namespace applied via an xmlns attribute, we must prefix the element names with the
same namespace in order to successfully match them.

The template which matches the CodeSnippet element outputs the attribute
class and selects the XPath
â€œ//s:Declarations/s:Literalâ€ which matches
a nodeset with a node for each Literal element in the snippet XML document, i.e. the
properties of the snippet. The template also selects the element which contains the
snippet code itself.

As you can see the XSLT approach is quite elegant; you provide discrete templates each
of which transform an XML node into the desired target format. The structure of the
output is clearly visible, being reproduces directly in this XSLT file. The templates
are connected together by the apply-templates elements which define the next nodeset to
match as an XPath query.

The only part of the above XSLT which is a bit ugly is the code which escapes the
quotes in the code defined within the codesnippet so that it can be included within a
C# verbatim string. XSLT is great at transforming the structure of XML documents, but
not so good at transforming the content. A simple find and replace on a string required
recursion as you can see in the escapeQuote template in the above
example.

The result of running this XSLT transformation with the above codesnippet as the input
is the following attribute:

You could manually execute the above XSLT each time you want to generate an
attribute, however, it would make life easier if you could simply drop a .snippet file
into your project and have the attribute generated automatically.

As an aside, I originally investigated whether it would be possible to locate all a
user"s codesnippet via the Visual Studio APIs. However, each user
typically has their own set of snippets defined causing issues if code is shared
between users. I decided that a better approach would be to require that a snippet is
added to a project so that you can ensure that everyone who works on the project shares
the same snippet code.

In the example project, if you add a snippet into the Snippets folder then click the
button indicated to run all the T4 templates, you will find that a corresponding C#
file is generated with the output of the XSLT transform described in the previous
section.

To achieve this, I make use of Env.DTE which is an API for Visual Studio automation.
This API allows you to explore a Visual Studio project, locating the classes and other
files it contains. I have found it to be a great tool to use in conjunction with T4, as
have other. See for example Daniel Vaughan"s excellent article which
describes a technique for generating class metadata (e.g.
property names etc...) using T4 & Env.DTE.

The T4 template below finds the Env.DTE Project that this template resides within, then
queries all the ProjectItems to find those that have the extension .snippet. It then
executes the GenerateAttributes method, which runs the XSLT transform
adding the generated output to the project:

The SaveOutput method is also a useful addition to the toolbox, it
saves the output of a T4 template into a file and adds it to the project. It is very
useful for templates that generate multiple classes, allowing you to split them across
multiple files.

We"ll start with a simple example, a class that implements
INotifyPropertyChanged and has a single property that raises the
PropertyChanged event from its setter. We"ll use the
SnippetPropertyINPC from the previous section, and also add a snippet for
the implementation of INotifyPropertyChanged itself. The following snippet
is added to the project:

Note that this is a partial class, a language feature
which Visual Studio uses extensively for keeping designer generated code separate from
our own code. Here is it being used so that we can generate another partial counterpart
to the class above, with the code that corresponds to the attributes. It is also
possible to have more than two partial definitions of a class, allowing you to use this
code generation technique with classes that already have a designer generated
counterpart.

The T4 template above first captures the output of
Includes.tt into a string, this is used to add the
"using" section to that start of each of our
generated files. This is followed by a Linq query that locates any class that has any
attributes that start with the text "Snippet".
For each of these, the method GenerateClass is invoked. The generated
output is then captured and saved to a file using the utility method
SaveOutput described earlier which saves to a file and adds it to the
project.

The GenerateClass method adds the boiler plate stuff, the namespace,
partial class and then iterates over all the snippet attributes,
invoking the GenerateSnippet method for each:

This method locates the attribute itself then uses Linq to
extract the fields for the snippet. For each field, we extract the default value from
the attribute. This makes use of the following Env.DTE utility method that captures the
text for a CodeElement:

The following regular expression is used to extract field
instance values from the attribute associated with the class:

field.Name + @""(?:[^""]|"""")*""|""(?:\\.|[^\\""])*"")"

The above expression matches both string literals and verbatim strings, and yes, I did
need a bit of help to find the right expression (thank
you StackOverflow!). If the expression matches, the methods
StringFromCSharpLiteral or StringFromVerbatimLiteral are used
to extract the value, by parsing the escaped string, to give the same result that the
compiler would in interpreting the field value. Again, my thanks go to Google
and Istvan for those useful methods!

Finally, the snippet itself is extracted from the attributes
GetSnippet method, and the field tokens within the snippet are replaced.

Note that the snippet for
INotifyPropertyChanged adds the event and a protected method for invoking
the event, however it does not add the interface to the class that is generated.
Therefore we have to add the interface to our class manually. However, it is perfectly
acceptable to indicate that a class implements a certain interface whilst having the
interface implementation in a partial counterpart.

Sometimes we have to modify codesnippets a little in order
to make them suitable for code-generation. One of the main reasons for doing this is
that if we generate code from a snippet, we cannot
"tweak" the output because this will be
overwritten next time the code is generated. For example, with manual snippets you will
probably find yourselves tailoring the generated code, tweaking it a little bit, to
suite the specific purpose. With code-generation, each generated
"instance" must be the same.

If we take the example detailed above, a snippet for generating a property that raises
change notifications, it is a common requirement that some code is executed when this
property changes. With regular, manual snippets, we would just edit the generated
output. In order to support this requirement with code-generation, we must build in
extension points into our snippet code.

Fortunately partial methods have a useful trick up their sleeves - partial methods. A
partial method is a void method defined in a partial class, but with no implementation.
You can then optionally provide an implementation for this partial method in one of the
other partial class counterparts. Note, this is entirely optional - it is not an
interface-style contract. If an implementation of the partial method is not supplied,
the compiler actually removes the call to the partial method, hence the reason why
partial methods must be void.

The previous sections have described the technologies and
mechanisms that make declarative code snippet automation work. In this section, I will
put these mechanisms into practice with a real-world example. Rather than create some
example project using code-generation techniques I thought it would be more informative
to start with an existing project which has a much larger codebase than a fabricated
example would. The project I chose was
"SilverTrack", a Silverlight based telemetry application
published here on codeproject. SilverTrack uses the Model-View-ViewModel UI
pattern, which often results in quite a bit of boiler-plate code. It also makes use of
custom-controls and user-controls, again adding further boiler-plate code.

The first step towards code-generation is to add the CodeGen folder which
adds the various templates to the project. I also added the codesnippets described
earlier in this article. There is one further snippet
"dp.snippet" for dependency
properties which will be described later.

SilverTrack has a number of ViewModel classes,
each containing numerous properties with change notification. Starting with
TelemetryChannelViewModel, I removed six of the properties and replaced
them with snippet attributes. I also removed the reference to the
"base" view model, which simply implements
INotifyPropertyChanged, replacing this with a suitable snippet (this give
you the freedom to create a more meaningful inheritance hierarchy).

Two of the properties had logic within their setters, this is replaced by partial
methods as shown below:

The net result of the above is to remove much of the
un-interesting boiler-plate code, with the code-generation creating a corresponding
partial class as shown below. The generated class contains 229 lines of code, which is
pretty good for 13 lines of attribute definitions and is of course much better for
future refactoring and maintenance.

SilverTrack also contain a number of controls which define
dependency properties. The WPF / Silverlight dependency property syntax is highly
verbose and is what spurned me to create my original non-snippet based code-generation
approach.

The dependency property code-snippet generates code which contains
DependencyObject and other classes from the System.Windows
namespace. Therefore, the Includes.tt template which contains code which
is added to the top of every generated class is updated to include these
namespaces:

<#@ template language="C#" #>
<# // the following template outputs code that is added to the start of every generated file #>
using System.ComponentModel;
using Visiblox.Charts;
using System.Windows;
using System;

Running the T4 templates results in the generation of a 73 line generated class
containing the dependency property boiler-plate code:

I had a lot of fun developing this technique and putting
together this article. It uses an interesting mix of technologies, Linq, XML, Env.DTE
and T4 to create something which I think is genuinely very useful. Boiler-plate code is
the bane of every programmer"s life, it slows us down when we
initially write our code, it hampers readability, and slows us down further if we have
to refactor in the future.

In this article I have illustrated how a declarative approach to code generation
removes all the boiler-plate code associated with properties raising change
notification, dependency property definitions and the implementation of
INotifyPropertyChanged. This leaves us with a simple declaration of a
classes capabilities. However, these are just a few examples, there is much more
boiler-plate code out there ... most design or architectural patterns involve a certain
amount of boiler-plate.

I hope you have found this article interesting and useful. Even if you do not use the
codesnippet automation technique it describes, perhaps you will find some other novel
use for T4 + Env.DTE, a very interesting technology pairing.

The sourcecode download for this article contains two projects; the first is a minimal
example with a couple of trivial classes just to show the basic principles. The second
is SilverTrack where the technique is used more extensively in a real-world
application.

I am also a Technical Evangelist at Scott Logic, a provider of bespoke financial software and consultancy for the retail and investment banking, stockbroking, asset management and hedge fund communities.

Comments and Discussions

These scripts are generating the snippets (eg: INotifyPropertyChanged) just fine when through the build menu, but when setting up the process to run whenever the code builds via these instructions http://msdn.microsoft.com/en-us/library/ee847423.aspx[^] EnvDTE.tt is throwing a NullReferenceException on line 35 (it appears that dte is null, not host).

Opening CodeSnippetAutomation.sln in VS2013 and building results in an error in GenerateObjects.cs "A namespace cannot directly contain members such as fields or methods" opening GenerateObjects.cs just shows it contains "ErrorGeneratingOutput"

Running "Transform all T4 Templates" from the Build menu shows that the .tt files are "blocked" and need to be unblocked via the properties menu. This is a lie, they need to be unblocked via windows explorer by right-clicking on them and selecting properties, and at the bottom of the General Tab under Security click the Unblock button.

The correct way to code this pattern is to read PropertyChanged into a local variable, test *that* variable for null, and then invoke on it. Otherwise, PropertyChanged could be set to null after the if test, but before the invoke occurs.

That's a valid point, thanks for pointing it out. However, I nearly always use INotifyPropertyChanged in view code, whether it is WPF, Silverlight, WP7 or WinForms. In this case the UI has thread-affinity, so you most often want to ensure that it is the UI thread that is executing this code. As a result, there is no race condition.

However, to be safe, it is probably still worth implementing your suggestion.

Glad you liked it - I was pretty pleased with the XSLT part too, it is one of my favourite technologies, although I do not get to use it very often. I have another half-finished project / article where I take a UML model in XMI format, then use T4 / Env.DTE / XSLT to create a CRUD application based on the model. Basically, an entire application generated from the model. I'll get round to finishing it one day!

Sounds interesting indeed. What would we do without partial classes eh? Allowing regeneration without disturbing user code.

Back in the day, circa 2000, I built an application generator that was able to create a Java enterprise app from an XML definition, using XSL. It would output database scripts, ant scripts, java classes, html etc. One takeaway from that experience was that it would have been better to generate intermediate XML for transformations; specific to each type of output. The volume of XSL I wrote...my god. As the scale and complexity of transformations increases, maintainability decreases exponentially.

I totally agree, large XSL transforms are a maintenance nightmare. I prefer to use them in a pipeline, where you use a number of smaller, maintainable XSL transforms to achieve the end-goal. In the UML/XMI example, my first XSL transform takes the horrible XMI document and transforms it into a much simpler domain model.

I did recently get to design a client site using XSLT - it turned out really well. So much better that the 'ASP.NET connecting straight to the database' approach that was proposed originally.