Toby Jackson Toby Jackson - 1 month ago 18
C# Question

How do I pass a string parameter to a t4 template

Hi I am trying to find a way to pass a normal string as a parameter to a text template.

This is my Template code, if someone could tell me what I would need to write in c# to pass my parameters and create the class file. That would be very helpful, Thanks.

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ parameter name="namespacename" type="System.String" #>
<#@ parameter name="classname" type="System.String" #>
<#
this.OutputInfo.File(this.classname);
#>
namespace <#= this.namespacename #>
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

/// <summary>
/// This class describes the data layer related to <#= this.classname #>.
/// </summary>
/// <history>
/// <change author=`Auto Generated` date=<#= DateTime.Now.ToString("dd/MM/yyyy") #>>Original Version</change>
/// </history>
public partial class <#= this.classname #> : DataObject
{
#region constructor

/// <summary>
/// A constructor which allows the base constructor to attempt to extract the connection string from the config file.
/// </summary>
public <#= this.classname #>() : base() {}

/// <summary>
/// A constructor which delegates to the base constructor to enable use of connection string.
/// </summary>
/// <param name='connectionstring`></param>
public <#= this.classname #>(string connectionstring) : base(connectionstring) {}

#endregion
}
}

Answer

The following is one way to pass parameters:

  1. You have to create TextTemplatingSession.
  2. Set the session dictionary for the parameters.
  3. Process the template using that session.

Sample code (Replace the ResolvePath with the location of your tt file):

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ output extension=".txt" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<# 
string templateFile = this.Host.ResolvePath("ClassGeneration.tt");
string templateContent = File.ReadAllText(templateFile);

TextTemplatingSession session = new TextTemplatingSession();
session["namespacename"] = "MyNamespace1";
session["classname"] = "MyClassName";

var sessionHost = (ITextTemplatingSessionHost) this.Host;
sessionHost.Session = session;

Engine engine = new Engine();
string generatedContent = engine.ProcessTemplate(templateContent, this.Host);

this.Write(generatedContent);  #>

I saw this example on Oleg Sych's blog, which is great resource for t4.

Comments