Presentation: Code Generation with T4
Back in October, I presented a session on Code Generation with T4 at the Developer Tools Ecosystem Summit. This session provides an overview of developing code generators with T4, starting with template syntax and transformation process, to template debugging, to integration and deployment. During this session you see a sample code generator built from scratch, using Logical Class Diagrams as a source of metadata. Logical Class Diagrams are one of the powerful new UML modeling tools shipping in Visual Studio 2010 Ultimate Edition. The session covers the breadth of the functionality offered by T4 today and highlights the improvements made in Visual Studio 2010.
You can watch the recording on Channel 9. In case you need to fast forward, here is the original outline I created for this session.
- Template Syntax and Transformation Process (5 minutes)
- Demo – Create simple template (15 minutes)
- Processing Directives (10 minutes)
- Demo – Template debugging (5 minutes)
- Template Deployment (5 minutes)
- Custom Tool Integration (5 minutes)
- Pre-compiled templates (5 minutes)
- What’s new in 2010 (5 minutes)
Unfortunately, the code example for this session was originally developed using Visual Studio 2010 Beta 1. In Beta 2, the APIs for accessing UML metadata are different and much easier to use. Here is a working template, inspired by Tim Fischer’s example:
<#@ template debug="true" hostspecific="true" language="C#" #> <#@ output extension=".cs" #> <#@ assembly name="Microsoft.VisualStudio.Uml.Interfaces.dll" #> <#@ assembly name="Microsoft.VisualStudio.Uml.Extensions.dll" #> <#@ import namespace="Microsoft.VisualStudio.Uml.Classes" #> <#@ import namespace="Microsoft.VisualStudio.Uml.Extensions" #> using System; namespace ClassLibrary { <# string projectPath = this.Host.ResolvePath(@"..\ModelingProject\ModelingProject.modelproj"); using (IModelingProject project = ModelingProject.Load(projectPath)) { foreach (IType t in project.Store.Root.OwnedTypes) { IClass c = t as IClass; if (c == null) continue; #> public class <#= c.Name #> { <# this.PushIndent("\t\t"); foreach (IProperty p in c.OwnedAttributes) { this.WriteLine("public " + p.Type.Name + " " + p.Name + ";"); } this.PopIndent(); #> } <# } } #> }


