Thursday 20 May 2010

A T4 Generator Tool for VS Express

T4 stands for Text Templating Transformation Toolkit which is a transformation engine built into all VS studio editions. In a few words, you can write a text template file which consists of plain text and source code wrapped around the T4 language notation. The T4 notation is similar to the ASP.NET design page source code. You indicate directives by using <#@ tags, statements with <# tags, and expressions with <#= tags. Below is a simple T4 template.

<#@ template debug="true" language="C#v3.5"#>
<#@ Import Namespace="System.Linq" #>
<#@ Assembly Name="System.Core,Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" #>
<#@ output extension=".cs" #>
<# WriteLine(@"Hello World");#>

You can find more information on the T4 language in MSDN. Now, using the TextTransform.exe utility in Program Files\Common Files\microsoft shared\TextTemplating\1.2\TextTransform.exe you can transform the T4 template. Create a file and give it a .tt extention ie.simpleT4.tt. Copy the above template text into the file and save it.

Since the VS express editions don’t support the installation of add-ins, the external tools is a way to add some productivity tools inside the VS express IDE. Go to Tools->External Tools and add a new tool. Give it a meaningful "Title" ie. T4 Generator. Set the "Command" to point to the TextTransform.exe ie. C:\Program Files\Common Files\microsoft shared\TextTemplating\1.2\TextTransform.exe.

Set the "Arguments" as follows:

-out $(ItemFileName) $(ItemFileName)$(ItemExt)

Set the "Initial directory" as your project directory ie. $(ProjectDir). Finally, check the "Prompt for arguments" and "Use Output window" the former to have the chance to modify the command line just before running and the latter to have some feedback during the operation.

In order for the tool to run smoothly you need to have the simpleT4.tt file included in your project. Open the simpleT4.tt and with this file in focus go to Tools and run the external tool. A new file simpleT4 with the contents of the transformation will be added in your project directory.

No comments:

Post a Comment