How to Debug System.NullReferenceException When Running Transformation?
.net, t4, visual-studio
Solution
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:
- Add debug="true" to template directive: `<#@ template debug="true" #>`
- Launch debugger `System.Diagnostics.Debugger.Launch();`
- Break `System.Diagnostics.Debugger.Break();`
- Select New instance of Microsoft Visual Studio in Visual Studio Just-In-Time Debugger dialog and click Yes
- 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.
Problem
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.