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.
Comments (5)
  1. Sonnet says:


     I follwed all the steps you have described for debugging T4 template, but I get the following exception when I try to generate code off of the T4 template with debug statements:

    Failed to load base class ‘Microsoft.VisualStudio.TextTemplating. … ModelingTextTransformation’ from which Transformation class inherits

    Any help will be greatly appreciated.


  2. Bharath says:

    Same issue here. Is there any other way to debug T4 templates in GAT packages.

  3. Durante este mes de mayo estuve trabajando en un editor de T4 templates como parte de SFT , así que ahora

  4. jescrich says:

    During this past month I’ve been working in a new T4 template editor as a part of the SFT . If you’re

  5. Great info on T4 Templates for VS

Comments are closed.

Skip to main content