Using the Text Template Transformation Toolkit (T4) in Visual Studio

Test Template Transformation Toolkit (T4 templates) was introduced with Visual Studio 2005 as a separate installer; later it was provided out of the box with Visual Studio 2008 and 2010 installations. T4 templates can be used to generate source code or any kind of text content (.txt, .xml, .html, etc.) dynamically. Since it supports both C# and VB syntaxes the learning curve will be much less for developers.

Even Visual Studio itself is making use of the T4 templates in the case of MVC, Entity Framework and Linq To SQL for auto generating the source code. The extension of the T4 templates is .tt.

Control Blocks

Inside the T4 templates you can use different control blocks to perform various operations as mentioned below.

Directive Block

This block is used to specify the directives for the template. The block will start with <#@ and ends with #>. Some of the directives are template, output, parameter, etc.

<#@ template debug="false" hostspecific="false" language="C#" #>

Expression Block

This block is to provide an expression that will be converted to a string during the execution of a template. Below is a sample.

Today's date is <#= DateTime.Now #>

Statement Block

This block is used to generate the code on the output file. It starts with a <# and ends with #>. It can have code statements, declarations, etc., but cannot have method or class declarations. Below is a sample.

<#
for(int i=0; i<10; i++)
{
       WriteLine("Hello" + i);
}
#>

Class Feature Block

This block can be used to write things that should not be a part of the main transform. Helper methods, property declarations, etc. can be accommodated here. It should start with a <#+ and end with a #>. Below is a sample.

<#
for(int i=0; i<10; i++)
{
       WriteHelloText("Hello" + i);
}
#>
 
<#+
       private void WriteHelloText(string text)
       {
              WriteLine(text);
       }
#>

Executing a Template

When you add a template in Visual Studio it also adds a child file for the template that is based on the output extension that you specify on the template. The output is written onto the child file when the templates are executed. Templates can be executed in many ways.

1. Saving the template – When you make some changes and save the template, then the template is executed. The output can be witnessed on the output file once the template execution is successful.

2. Using Custom Tool – Right click on the template and select run Custom tool. This action results in the execution of the template.

3. In Visual Studio 2010 the solution explorer has a button, 'Transform All Templates'. Clicking on it will execute all of the template files available in that project.

4. Through code – Preprocessed templates will expose a method named TransformText, which will return the output of the executed template. It can be explicitly called from another class during runtime.

Different Types of T4 Templates

There are two types of T4 templates available with Visual Studio 2010. Based on their types they can either be executed during design time or during run time.

Text Template

This template is used during the design time.  It is mainly used to re-generate the source code based on needs like customization for a particular client or the source code needs to be updated based on some parameters from an external source like a database or XML. It uses the TextTemplatingFileGenerator custom tool.

Preprocessed Text Template

This is a run time template i.e. the execution of the preprocessed template would be triggered by another object during runtime. When you create a preprocessed text template in Visual Studio the output .cs file will have a default virtual method named TransformText and it can be called in other parts of the application. The TransformText method will return a string containing the output text. These templates can be used in scenarios like generating email content dynamically based on some given parameters. It uses the TextTemplatingFilePreprocessor custom tool.

T4 is a nice feature and it definitely becomes handy for developers. Only caveat that I see is the lack of intellisense and syntax help on the templates.

Happy reading!



Related Articles

Comments

  • good

    Posted by virus on 11/01/2012 04:05am

    good article man.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: April 22, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Database professionals — whether developers or DBAs — can often save valuable time by learning to get the most from their new or existing productivity tools. Whether you're responsible for managing database projects, performing database health checks and reporting, analyzing code, or measuring software engineering metrics, it's likely you're not taking advantage of some of the lesser-known features of Toad from Dell. Attend this live …

  • Hurricane Sandy was one of the most destructive natural disasters that the United States has ever experienced. Read this success story to learn how Datto protected its partners and their customers with proactive business continuity planning, heroic employee efforts, and the right mix of technology and support. With storm surges over 12 feet, winds that exceeded 90 mph, and a diameter spanning more than 900 miles, Sandy resulted in power outages to approximately 7.5 million people, and caused an estimated $50 …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds