Working with T4 recently I learned a couple of valuable lessons I’d like to share.
Lesson 1: Template Language
One of the parameters of the language directive is the language, which specifies the language used in the code blocks of the template. Two languages are specified, C# and VB.
<#@ template language="C#" #>
However, any attempts to use var, lambdas, initialization lists or even inheritance failed. And then I found the answer to the problem on Oleg Sych’s great blog. In VS2008 you can specify which version of the language you want to use. For instance v3.5 for using C#/VB.NET 3.5
<#@ template language="C#v3.5" #>
Then, suddenly, all of these missing features worked!
Lesson 2: Generate Multiple Output Files
There are cases when you want a T4 template to generate, not one, but several output files. And of course, you want the automatically added to the project, source control, all menu. For instance, maybe you want to generate files for a database object model. You have a single template that parses the description of the model and generates code, but the code should be put in different files.
Here is a dummy example, that produces five EntityX classes, all on the same file.
<# for(int i = 1; i <= 5; ++i)
{
#>
public class Entity<#=i#>
{
}
<#
}
#>
However, with the help of this script by Damien Guard you can define blocks that get generated in different files. You can also define common blocks, such as header and footer for all output files. What you have to do is:
- include the script into your template
- create an instance of the blocks manager
- define file blocks
- optionally define header and footer blocks
- process the blocks at the end of the template
Here is a concrete example for the above example:
<#@ template language="C#v3.5" hostspecific="True" #>
<#@include file="MultipleOutputHelper.ttinclude" #>
<# var manager = Manager.Create(Host, GenerationEnvironment); #>
<# manager.StartHeader(); #>
// Code generated by a template
using System;
namespace Tests
{
<# manager.EndBlock(); #>
<# for(int i = 1; i <= 5; ++i)
{
manager.StartNewFile(String.Format("Entity{0}.cs", i));
#>
public class Entity<#=i#>
{
}
<#
manager.EndBlock();
}
#>
<# manager.StartFooter(); #>
}
<# manager.EndBlock(); #>
<# manager.Process(true); #>
The result is five EntityX classes are generated, each in a separate file called EntityX.cs, and all these files are automatically added to the project.
Marius Bancila is a Microsoft MVP for VC++. He works as a software developer for Visma, a Norwegian-based company. He is mainly focused on building desktop applications with VC++ and VC#. He keeps a blog at http://www.mariusbancila.ro/blog, focused on Windows programming. He is the co-founder of codexpert.ro, a community for Romanian C++ programmers.