Monday, November 14, 2011

Debugging T4 Templates

T4 templates are a great way to write code that writes code.  Huh?  I'm not going to go into it here, so if you want more information, see Scott Hanselman's post on T4 templates, as well as Oleg Synch's posts.

One of the pain points when writing T4 templates is with debugging them.  Sometimes you'll save a .tt file and get some obscure error message that is impossible to figure out, and you have no clue what part of your T4 file is messed up.

It is possible to debug them, and Oleg provides some great pointers.  Here is my summary of how to get it working:

1. Make a registry edit as follows:
     If you're on a 32 bit OS:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\DbgJITDebugLaunchSetting - Set to 0x2
      If you're on a 64 bit OS:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\DbgJITDebugLaunchSetting - Set to 0x2
(if you don't make this change, you can get debugging to work, but Visual Studio will be hung after you finish debugging)

2. Reboot
(otherwise the registry change won't get picked up)

3. Set debugging to true at the top of your .tt file:
<#@ template language="C#v3.5" debug="True" #>

4. Force the debugger to launch

5. Put breakpoints in your code

6. Make a change to and then save your T4 file

When you save or run your T4 file, it should now pop up a window asking you if you want to debug it using a new instance of Visual Studio.  This second instance should allow you to step through the execution of the T4 file so that you can see where your code is broken.