Text Template Transformation Toolkit (T4) is a template-based code generation engine. It is included with Visual Studio 2008 and available as a download for Visual Studio 2005 in DSL and GAT toolkits. You can use T4 templates to generate Visual Basic, C#, T-SQL, XML or any other text files.
T4 templates have ASP.NET-like syntax and consist of processing directives, text blocks and code blocks.
<#@ template language=“C#” #> Hello <# Write(”World!”) #>
Processing directives provide template compilation and processing options. In the example above, <#@ template #> directive specifies that code blocks of this template are written in C#.
Text blocks are copied to the output “as is”. In the example above, Hello is a text block.
Code blocks contain Visual Basic or C# code that can manipulate text blocks or generate template output directly. In the example above, the code block calls Write method which writes “World!” to the output file. Code blocks can use any available .NET APIs. For example, a template can use SMO to generate CRUD stored procedures for a table in a SQL Server database.
How it works
T4 engine performs two steps to generate output from a template.
During the first step, T4 engine “compiles” the template: it parses the processing instructions, text and code blocks, generates a concrete TextTransformation class, and compiles it into a .NET assembly. During the second step, T4 engine creates an instance of the GeneratedTextTransformation class, calls its TransformText method and saves the string it returns to the output file.
This series of articles introduces code generation with C# and Text Templates in Visual Studio; explains how to create reusable templates and combine them in complex code generators.
- Creating your first code generator
- Troubleshooting code generation errors
- Debugging code generation files
- Creating reusable code generation templates
- Creating complex code generators
- Reusing code generators on multiple projects
- Handling errors in code generators
- Unit testing code generators
- Making code generators extensible
- Generating code from DSL models
- Integrating generated files in Visual Studio projects
Here are the tools you will be using when working with T4 text templates.
Visual Studio Custom Tool
T4 engine is integrated as a custom tool into Visual Studio 2008. When you add a text file with .tt extension to your project, Visual Studio assigns TextTemplatingFileGenerator as a custom tool and automatically generates output file from the template. This is similar to how Visual Studio generates strongly-typed datasets from .xsd files.
Command Line Utility
Text editing and debugging support for T4 templates is currently rather limited. I use T4 Editor from Tangible Engineering, which extends Visual Studio to provide IntelliSense and syntax highlighting for .tt files. Another option is the T4 Editor from Clarius Consulting, however functionality of its free edition is more limited.
Debugging requires placing calls to Debugger.Break method in code blocks to set breakpoints. Check out this post by Gareth Jones for more details. Hopefully, future versions of Visual Studio will provide a better debugging experience for T4 templates.
Visual Studio Templates
Unfortunately, Visual Studio itself does not provide a specific item for T4 templates in the Add New Project Item dialog. This makes it difficult for developers to discover this code generation tool even exists. You can download T4 Toolbox from CodePlex, which adds several items to the Code Generation folder of the Add New Project Item dialog.
Here are some articles that will help you understand how template transformation works by showing how specific blocks and processing directives are “compiled”. Examples in these articles include the original template text, compiled template code and output file it produces.
- Text Blocks
- Statement Blocks
- Expression Blocks
- Class Feature Blocks
- <#@ template #> directive
- <#@ output #> directive
- <#@ import #> directive
- <#@ assembly #> directive
- <#@ include #> directive
- <#@ parameter #> directive
- <#@ property #> directive
- <#@ xsd #> directive
- Preprocessed Templates
- MSBuild integration
- What’s new in T4 in Visual Studio 2010
The following articles cover advanced topics of code generation with T4.
- T4 Architecture
- T4 Template Design
- Test runner for T4 unit tests
- Pros and Cons of T4 in Visual Studio 2008
- Using CodeDOM to create code generators compatible with T4
- Automatic Template Transformation
- There is a growing number of videos about T4 published on MSDN.
- How Do I: Create and Use T4 Templates (by Hilton Giesenow)
- Advanced code generation patterns with T4 & DSL Tools (by Gareth Jones and Jean-Marc Prieur)
- Authoring Blueprints - Using T4 Templates (by Michael Legman)
- Code Generation in Visual Studio Using T4 Templates (by David Hayden)
You can find some T4 examples on MSDN. You will notice that it has very limited information about use of T4 outside of DSL and Guidance packages. Here are some examples of standalone templates you can start using without having to build your own Software Factory.
- How to create a simple T4 template
- How to use T4 to generate .config files
- How to use T4 to generate Decorator classes
- How to use T4 to generate CRUD stored procedures
- How to use T4 to generate strongly-typed navigation class in ASP.NET (by Kirill Chilingarashvili)
- How to generate multiple outputs from single T4 template
- T4 template for generating ADO.NET Entity Framework Stored Procedures (by David DeWinter)
- T4 script for generating ADO.NET Entity Framework Views (by ADO.NET team)
- T4 template for generating LINQ to SQL Data Context (by Damien Guard)
- T4 template for generating WiX source files (by New Age Solutions)
- T4 Toolbox: Template for generating SQL view from C# enumeration
- MSBuild task for transforming T4 templates (by Elton Stoneman)
- T4 template for generating state machines in C# (by Andrew Matthews)
- T4 Toolbox: Strongly-typed AzMan wrapper generator
- T4 Toolbox: LINQ to SQL classes generator
- Make Visual Studio Generate Your (SubSonic) Repository (by Rob Conery)
- SubSonic v3’s T4 Templates (by George Capnias)
- Generating DataContext Proxy Classes With T4 Templates (by Mel Grubb)
- T4 Text Templating in Silverlight (by Jason Jarrett)
- Generate enums from a database using T4 (by Code Junkie)
- T4 template for generating Entity Framework classes (by Danny Simmons, ADO.NET team)
- T4 templates for generating Dynamic Data views (by David Ebbo, ASP.NET team)
- Using T4 Command-Line Parameters - Generating NHibernate Magic Strings (by Richard Brown)
- Using T4 to generate code based on M language in Oslo (by Kirill Chilingarashvili)
- SQLite foreign key constraint generator using T4 (by Derek Wilson)
- T4 templates for the .NET Compact Framework (by Jeff Doolittle)
- T4 Toolbox: LINQ to SQL schema generator
As a code generation tool, T4’s purpose is similar to that of CodeDom (Code Document Object Model). CodeDom provides an API you can use to generate code in any .NET language from the same program. CodeDom API is low-level, complex, and has a steep learning curve. It is typically used for code generation in frameworks that need to to support multiple .NET languages. For example, T4 engine itself uses CodeDom; you have to use CodeDom to extend T4 with custom directives. Compared to CodeDom, T4 is easier to learn and use. However, T4 templates are language-specific. In other words, if you want to generate the same code code in C# and Visual Basic, you will need to create 2 separate T4 templates. Unlike CodeDom, T4 can generate any text files (XML, HTML, etc) and not just .cs or .vb files. This makes T4 a better fit for code generation in application development then CodeDom.
T4 engine is similar to CodeSmith, which has been around a lot longer, provides an excellent set of ready-to-use templates, better template editing and debugging experience for a reasonable price. Unlike CodeSmith, which was was designed to be a template-based code generation tool, T4 engine was designed as a supporting tool for Software Factories. T4 does not offer any reusable templates out of the box and provides rather limited documentation focused on use of T4 templates in DSL and Guidance packages. However, with inclusion in Visual Studio 2008, I think we will see more and more teams adopting T4 engine as a free alternative to CodeSmith.
T4 engine is also similar to NVelocity, an open-source template transformation engine. NVelocity was ported from Java and intends to stay as close to Jakarta Velocity as possible. This makes its template syntax different from ASP.NET and I would think that more people will prefer T4. I don’t know if a significant number of NVelocity templates are available at this time.