visualstudioHave you ever wanted to generate some html, C# or other code on the fly? Most of us have done this by either appending strings in code or writing content to a text file. If you need more advanced capabilities in your code generation then maybe you even resorted to a third party library like StringTemplate. Well these techniques are no longer needed due to the powerful T4 Text Template engine that is available with Visual Studio 2005 and above.

T4 was originally intended to be used as a mechanism for DSLs (Domain Specific Languages) to programmatically generate code. However T4 is flexible enough that it can be used for anything. For example, if you have been experimenting with ASP.NET MVC, then perhaps you are a little unsatisfied with the markup generated by Visual Studio for Views. Well, T4 is a perfect tool for you to generate your own custom markup. Here is a quick example on how to use T4:

If you are using Visual Studio 2005 then you will need to install the DSL Tools first. The tools are not needed if you are using Visual Studio 2008

Steps

1. Launch Visual Studio and create a new C# console project.
2. Create a new text file and name in HelloT4.tt. The extension is important because Visual Studio will recognize the extension and use a tool named TextTemplateFileGenerator to generate an empty cs file named HelloT4.cs.
3. Modify HelloT4.tt so it contains the following text

<#@ template language="C#">
using System;   

public class <#= this.ClassName #>
{
   public static void HelloT4()
   {
      Console.WriteLine("T4 can write code!");
   }
}
<#+ string ClassName = "MyT4Class"; #>

Visual Studio will automatically regenerate the HelloT4.cs file whenever you make changes to the template file (HelloT4.tt). Alternatively, you can right click on the template file in Solution Explorer and select the "Run Custom Tool" option. Here is the code that was generated from our sample script:

using System; 

public class MyT4Class
{
    public static void HelloT4()
    {
        Console.WriteLine("T4 can write code!");
    }
}

T4 can be used directly within a project as I demonstrated above or you can use the command line tool.

Other Resources:
GenerationBestKeptVisualStudioSecret.aspx" target="_blank">T4 (Text Template Transformation Toolkit) Code Generation - Best Kept Visual Studio SecretT4, Visual Studio 2008's Best Kept Secret
Visual T4 - Editor used to make T4 scripts
T4: Text Template Transformation Toolkit
T4 Toolbox - T4 Template Library