Chances are you have never heard of T4. Don’t worry, most haven’t. This tool was introduced when the DSL tools hit the market. As the name implies, it’s a code generation engine. It’s my understanding, T4 is used under the scenes by the DSL tools to generate out it’s artifacts. This is also the tool that things like Linq to SQL and the Entity framework use to generate its artifacts. Very Cool, and a bit daunting at first.
There are a number of great resources on Code Generation. I don’t want to recover what has been written better than I could but I do want to talk about the start of my journey with T4. So like anyone I hit the ole WWW in search for answers. The following resources got me rolling:
- T4 (Text Template Transformation Toolkit) Code Generation – Best Kept Visual Studio Secret
- PNP Guidance
- Kathleen Dollard’s Blog
- Oleg Sych’s blog and especially T4 Tutorial: Creating your First Code Generator
- Hanselminutes "Code Generation and T4 with Kathleen Dollard"
- Clarius’s Visual T4
Needless to say you don’t really need anything to get started. I don’t want to rehash anything already stated above, but I do want to cover a few good little hints I have learned so far.
- You can include other TT files.
- <#@ include file="core.tt" #>
- “Class level functions”. These have listed at the bottom of the TT file in a <=+ => if there are other code blocks in the TT file.
- Set your output file type. While you don’t really need it in VS if you are using the command line it will still save a few headaches. It can be whatever type of file type you want.
- <#@ output extension="XML" #>
- Assembly References. Just like a normal .NET program you have to reference what you need. I was a bit surprised I had to reference System.Core for some Linq Queries.
- <#@ assembly name="System.Core" #>
- Imports. Nothing different from a using statement in C#
- <#@ import namespace="System.Xml.Linq"#>
- You can’t pass in parameters into the T4 Engine. Well you can, but not with the host that ships out of the box. Kathleen Dollard is actually working on a host that will address that situation but I have cheated in the meantime. I have an settings file ( like a config ) which I set the setting file from my own host which in turn calls the T4 Engine. The the templates just read that file getting whatever dynamic settings they need.
- I have been driving my templates with Powershell.
- You can specify template framework versions, although you don’t have to.
- <#@ template language="C#v3.5" HostSpecific="true" #>
I will indeed post more on T4. It’s just amazing and we all should use it more. As I do it more and more I find myself coming up *MUCH* more creative ways to generate the same artifact with less.
More to come…..