TechnoCowboy
TechnoCowboy

Reputation: 344

T4 template NullReferenceException when using parameter directive

I am trying to implement an application that can process T4 templates.

I have implemented an Custom Text Template Host as shown in this article: https://msdn.microsoft.com/en-us/library/bb126579.aspx

I can run a simple template like this, and it works fine with both C# code and the include directive:

    <#@ template debug="true" #>
    <#@ include file="includehello.txt" #>  
    Some text.
    <# for(int i = 0; i < 3; i++) { #>
        //Line <#= i #>
    <# } #>

But, as soon as i try to use the "parameter" directive, i get a NullReferenceException.

    <#@ template debug="true" #>
    <#@ parameter type="System.String" name="worldParam" #>
    Hello <#=worldParam#>

The code that runs the template looks like this:

CustomCmdLineHost host = new CustomCmdLineHost();
Engine engine = new Engine();
host.TemplateFileValue = "HelloWorldTemplate.tt";           
//Read the text template.  
string input = File.ReadAllText(templateFileName);
host.Session = host.CreateSession();           
// Add parameter values to the Session:  
host.Session["worldParam"] = "world";
//Transform the text template.  
string output = engine.ProcessTemplate(input, host);
//Save the result
string outputFileName = Path.GetFileNameWithoutExtension(templateFileName);
outputFileName = Path.Combine(Path.GetDirectoryName(templateFileName), outputFileName);
outputFileName = outputFileName + "1" + host.FileExtension;
File.WriteAllText(outputFileName, output, host.FileEncoding);

I suspect that the parameter values are never transferred into the engine, so the question is :

How do I transfer parameter values to the engine?

I found this question that uses host.Initialize(); but that seems to be for precompiled templates and the Initialize method is not implemented in the example article. Neither is the CreateSession(); I implemented that as described in that article.

P.S. In order to get the code from the article to work, i had to add the Nuget Package Microsoft.CodeAnalysis, in addition to adding the mentioned references to Microsoft.VisualStudio.TextTemplating.15.0 and Microsoft.VisualStudio.TextTemplating.Interfaces.15.0.

I am using VS2017. Target framework : .Net Framework 4.6.2

Upvotes: 2

Views: 872

Answers (1)

Mutlu Kaya
Mutlu Kaya

Reputation: 129

You need to implement ITextTemplatingSessionHost interface in addition to ITextTemplatingEngineHost. Class signature must be

public class CustomCmdLineHost : ITextTemplatingEngineHost, ITextTemplatingSessionHost

Upvotes: 1

Related Questions