Text Templates in Microsoft Visual Studio

Introduction

T4, which stands for Text Template Transformation Toolkit is a code generator build into Visual Studio (available in 2008 and 2010 Standard editions or higher).
It allows you to build text files out of templates, using C# or VB.NET as “scripting” languages within the template. In this article I will provide an introduction on T4 starting with a simple example and explaining the different parts of the template.

Setting up a simple template

Let’s assume we want to “import” constants (#defines) from a C++ header file into a C# project. The header file, called Constants.h, looks like this:

#pragma once

// here are the values
#define VALUE1 1
#define VALUE2 2
#define VALUE3 10
#define VALUE4 20
// this depends on the previous value
#define VALUE5 VALUE4+1

The file we want to generate in C# out of this header file should look like this:

using System;

namespace T4Demo
{
   public static class Constants
   {
      // here are the values
      public const int VALUE1 = 1;
      public const int VALUE2 = 2;
      public const int VALUE3 = 10;
      public const int VALUE4 = 20;
      // this depends on the previous value
      public const int VALUE5 = VALUE4+1;
   }
}

Note: if you wonder why you would want to do something like this, imagine a project where you want to access features from a native library from managed code. You need to call some native functions and provide some numerical values that are defined in some header, and those values change relatively often.
You don’t want to update manually those constants in C#, having them updated automatically in the managed project when the native project changes could be a great help.

Using Visual Studio 2008 or 2010 Standard or higher we can add a text template file (having the extension .tt) to the project. Let’s call it Constants.tt.

Constants.tt.

The final template that generates the C# Constants class would look like this:

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ import namespace="System.IO" #>
using System;

namespace T4Demo
{
   public static class Constants
   {
<#
      using(StreamReader reader = File.OpenText(Host.ResolvePath(@"constants.h")))
      {
         string line = null;
         while((line = reader.ReadLine()) != null)
         {
            if(line.StartsWith("#pragma"))
            {
               // ignore
            }
            else if(line.StartsWith("//"))
            {
               // comment
#>
      <#=line#>
<#
            }
            else if(line.StartsWith("#define"))
            {
               string []parts = line.Split(new char[]{' '});
               if(parts != null && parts.Length >= 3)
               {
                  // part 1 is #define, part 2 is name, part 3 is value
                  string name = Normalize(parts[1]);
                  string value = Normalize(parts[2]);
#>
      public const int <#=parts[1]#> = <#=value#>;
<#
               }
            }
         }
      }
#>
   }
}
<#+
   string Normalize(string value)
   {
      return value.Trim();
   }
#>

Unfortunately, Microsoft Visual Studio doesn’t have syntax highlighting or IntelliSense for text templates. So when you open a text template, it looks like this:

text template

The good news is that free advanced editors are available. One of them is Visual T4 Editor Community edition from Clarius.
Another one is tangible T4 Editor plus modeling tools for VS2010 from tangible, available also in the Visual Studio Gallery.
Here is how the text template looks with the tangible T4 editor:

tangible T4 editor:text template

When you add and build the first text template file, Visual Studio will show you a warning:

T4 Warning

This is because being a template it could contain potential harming code. Check “Do not show this message again” and press OK.
If you want to get this warning again later, go to Tools > Options > Text Templating and set the Show Security Message property to True.

More by Author

Must Read