Generating code is a truly fascinating and a very satisfying experience for me. There is something very meta about it… Effectively you write programs that write programs for you. I live by the advice (which also comes naturally to me) 3 strikes you automate. Ah well, t4 then… We will first briefly see what T4 is, then I will explain using an example for code generation.

What is T4 or TTTT?

T4 is one of the cool things Microsoft has produced, it has been around since a long time although it’s not that famous. I have been using it since about 2009 on some odd tasks / code which I found could be automated. It’s a very handy tool for generating boiler plate code.

T4 = Text Template Transformation Toolkit.

To describe it simply it’s like XSLT (Xml Transformation) or like PHP… ASP.Net’s Razor engine works on the similar principle. It can be used to generate any text output. There are two ways in which the t4 engine can be used.

  • Static code generation (compile time)
  • Dynamic code generation (at runtime)

Create a new project in Visual studio, and add the tt files into the project. I am currently using the VS Community Edition which is absolutely free and it also supports T4.

Add tt files

Once you create a .tt file you will likely see the below warning. This is normal, if you know its your tt file its fine.

Warnings

Technically on saving the tt file, a code generator is run and that can execute all the .NET code that is embedded in the tt. This code will run with your current privileges hence, the potential to be harmful…

Understanding the tags

The tt files will contain code like below. You will see some odd tags here is a brief explanation about them.

<#= #> tags: These are control expressions, they contain only code. Any .NET code can be embedded into them. They will return a value that is written into the output of the template.

<# #> tags: These are standard control blocks, they can be staggered across the template. You can write partial code in these blocks and have pure text in between and again continue with the earlier code.

<#@ #> tags: All template directives need to be inside these.

<#+ #> tags: They contain class features, this is if we define any class within the template, you can add methods or properties etc.. within these blocks.

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".txt" #>

Most of the code above is self-explanatory, the embedded language is C#, the extension type of generated file is .txt, all the other code is importing the namespaces for the embedded code.

These are known as the template directives. For more details here is the link https://msdn.microsoft.com/en-us/library/gg586945.aspx

Example

We will take a simple example to prepare a list of files in a directory, I was going to take a complex one, but it can take very long - probably I will do it in another post. The goal is to generate an XML file which contains the directory path and lists all the files in it along with its attributes.

We will only talk about static code generation here, dynamic is same in principle.

Lets say I have the below directory with following files in it. Directory

Now, I would like to generate an XML for it.

Lets first see what the .tt file actually looks like.

Visual studio project

There is another file which is a .txt file that has been generated by the t4 engine after parsing our .tt file, and its currently empty.

I will add some code like below to read a directory (elementary c# stuff) into the .tt file as below. Remember the <#= and the #>, anything outside those will be directly put into the output file.

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>
<#@ output extension=".txt" #>

<xml>
<#DirectoryInfo dir = new DirectoryInfo("c:\\tmp\\downloads");#>
	<Directory Name="<#=dir.FullName #>">
	<#foreach (var file in dir.GetFiles())
	  {#>
		<File LastWriteTime="<#=file.LastWriteTime#>">
			<#=file.Name#>
		</File>
	<#}#>
	</Directory>
</xml>

After just saving or compiling this .tt file the code generator will kick in and generate following output text or XML ;) file for us.

<xml>
	<Directory Name="c:\tmp\downloads">
		<File LastWriteTime="12/03/2015 21:31:46">
			Todo - Copy (2).txt
		</File>
		<File LastWriteTime="12/03/2015 21:31:47">
			Todo - Copy (3).txt
		</File>
		<File LastWriteTime="12/03/2015 21:31:48">
			Todo - Copy (4).txt
		</File>
		<File LastWriteTime="12/03/2015 21:31:49">
			Todo - Copy (5).txt
		</File>
		<File LastWriteTime="12/03/2015 21:31:46">
			Todo - Copy.txt
		</File>
		<File LastWriteTime="12/03/2015 21:31:46">
			Todo.txt
		</File>
	</Directory>
</xml>

That is the basic principle of the T4 templates. Static code generation is useful to generate UI code / html, generate resources / dictionaries etc. Hope it was useful.