Tag Archives: Code Generation

Code Generation with T4

I was first exposed to T4 in January/February of 2008 when I was ramping up for a project that used the Guidance Automation packages.  Even though that fell through, it was still worthwhile for getting exposure to a cool little utility like this.

T4 stands for Text Template Transformation Tool and is a built-in feature for Visual Studio 2008 and as an add-on for 2005.  It’s an engine that can be used for generating code from any data source you want.

Add a template
In any project in VS, right click and Add -> New Item., select a text file and rename it so it has the extension .tt.  This keys Visual Studio into the fact that it’s dealing with a T4 file.

Now would also be a good time to install the Clarius add-on for T4.  http://www.visualt4.com/

This tool gives you a bit more design time support than you normally get with T4 out of the box.  Note to the faint of heart: Unless your willing to shell out for the not-free editions your about to step back in time to a place before Intellisense, AutoComplete, Syntax highlighting and other things we’re all accustomed to.

The best way to think about T4 is back to web scripting languages like PHP, ASP, etc.  You have your template, and you have blocks of code for control flow for logic.  Let’s take a look at a simple template

[code lang="xml"]
<#@ template language="C#" debug="true" hostspecific="true" #>
<#@ output extension="txt" #>
<#
for(int i=0; i < 10; i++)
{
#>
I'm a template on line <#= i #>
<#
}
#>
[/code]

Which tells us the control flow is done in C# and the output is a text file.  When you save the file the template engine will run.  You can also run the engine by right clicking and choosing “Run Custom Tool”.

You can see our output is now nested under our item in Solution Explorer.

t4-1

There are two tags to be aware of here <# #> and <#= #>, the first allows for control flow code to be inserted and the second one is for outputting values.

That’s enough for a start, I’ll be back in another post about going a little more in depth.