Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Debug System.NullReferenceException When Running Transformation?

I am attempting to generate code using T4 Text Templating, but when running the script, I get the error below:

Running transformation: System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.VisualStudio.TextTemplatingB0A58A4C85EA3D7032675015C6052C89.GeneratedTextTransformation.TransformText()
   at Microsoft.VisualStudio.TextTemplating.TransformationRunner.RunTransformation(TemplateProcessingSession session, String source, ITextTemplatingEngineHost host, String& result)

As I am unfamiliar with T4, I'm not sure exactly where to look to resolve this issue.

like image 241
Ryan Kohn Avatar asked Jun 08 '26 09:06

Ryan Kohn


2 Answers

You'll need to debug your template to find where the NullReferenceException is occurring. Tim Larson has quick overview here and Oleg Sych has a more details here, along with his other excellent blog entries on T4.

Here's the short-short version:

  1. Add debug="true" to template directive: <#@ template debug="true" #>
  2. Launch debugger System.Diagnostics.Debugger.Launch();
  3. Break System.Diagnostics.Debugger.Break();
  4. Select New instance of Microsoft Visual Studio in Visual Studio Just-In-Time Debugger dialog and click Yes
  5. Debug your T4 template

Here is a simple example to help catch the NullReferenceException when calling ToString on bar:

<#@ template debug="true" language="C#" #>
<#@ output extension=".txt" #>
<#
    System.Diagnostics.Debugger.Launch();
    System.Diagnostics.Debugger.Break();

    object bar = null;  
#>
foo<#= bar.ToString() #>

Be sure to check first link though since on some versions you'll need to update the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\DbgJITDebugLaunchSetting to 0x2 to get things to behave correctly.

like image 126
Scott Lerch Avatar answered Jun 10 '26 04:06

Scott Lerch


Updated 2023

In Visual Studio, right click on a .tt file and click Debug T4 Template.

Debugging a T4 Text Template

like image 29
mparkuk Avatar answered Jun 10 '26 03:06

mparkuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!