Debugging T4 Text Templates
People often ask me about the best way to debug T4 templates. This topic is covered in our new downloadable help file CTP, but I thought I'd get it up here in searchable form.
The first thing you need to do is to set the debug flag on the template directive of your template.
<#@ template debug="true" inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" #>
If you're debugging a system-provided template rather than one of your own, this typically means that you'll need to copy the included portion of the template directly into the template file that's in your project.
Next you'll need to bring in the System.Diagnostics namespace (this isn't strictly necessary but it means you won't have to fully-qualify types).
<#@ import namespace="System.Diagnostics" #>
Finally, call Debugger.Break wherever you want to stop in your template.
<# Debugger.Break(); #>
When this gets hit, you should be asked whether you want to start a new instance of Visual Studio to debug or use an existing one. You'll then be debugging within the generated-on-the-fly transformation class that implements your template.
If you're going to be doing a lot of debugging, there's also another technique available.
Open a second instance of Visual Studio.
Open your template files in the new instance.
Set breakpoints on the control code in the template just as though it was regular code.
Choose Tools/Attach to Process… and pick the original devenv.exe Visual Studio process.
Run your template in the original Visual Studio.
Your breakpoint should be hit.
I haven't actually tried it, but I believe these steps should also work for T4 templates used within GAT.