Updating @jkheadley's answer... In Visual Studio 2019, the error does not occur if you "Debug T4 template," but it does if you "Run Custom Tool." The solution (found on SO here) is to add the following to the header of your *.tt
file:
<#@ template hostspecific="true" language="C#" #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
Then modify @jkheadley's function as follows below. (For those less familiar with *.tt
templates (like myself), add the function below to the bottom of your *.tt
template file.)
void WriteToOutput(string output)
{
IServiceProvider hostServiceProvider = (IServiceProvider)Host;
if (hostServiceProvider == null)
throw new Exception("Host property returned unexpected value (null)");
IServiceProvider serviceProvider = (IServiceProvider)this.Host;
// Visual Studio 2019: per https://stackoverflow.com/a/53346767
// get DTE object via Microsoft wrapper
EnvDTE.DTE dte = (EnvDTE.DTE) serviceProvider.GetCOMService(typeof(EnvDTE.DTE));
if (dte == null)
throw new Exception("Unable to retrieve EnvDTE.DTE");
var window = dte.Windows.Item(EnvDTE.Constants.vsWindowKindOutput);
var outputWindow = window.Object as EnvDTE.OutputWindow;
if (outputWindow == null)
throw new Exception("Unable to obtain OutputWindow object");
outputWindow.ActivePane.Activate();
outputWindow.ActivePane.OutputString(output);
outputWindow.ActivePane.OutputString("\n");
}
And then, in the body of your *.tt
template, test it in the time-honored fashion:
WriteToOutput("hello, world");
Good luck!