Thursday, October 16, 2008

C# : T4 - the Text Template Transformation Toolkit

Been looking at code generation templates. Obviously CodeSmith is right up there but then I read an article by Scott Hanselman entitled "T4 (Text Template Transformation Toolkit) Code Generation - Best Kept Visual Studio Secret" which describes a Visual Studio add-in (I'm using VS 2005) which does pretty much the same thing.

There's a link in the article to another "How-To" by Oleg Sych entitled "
How to create a simple T4 template". You need to download DSL Tools and you may also want to install the T4 Editor by Clarius Consulting.

As an example, here's my template (Template.tt):


<#@ template language="C#" #>
<#@ assembly name="System.dll" #>

//
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
//

using System;

public class <#= this.ClassName #>
{
public static void HelloDude()
{
Console.WriteLine("Hello, Dude");

for (<#= this.Variable #> = <#= this.Start #>; <#= this.Variable #> < <#= this.End #>;
<#= this.Variable#>++)
{
}
}
}
<#+
string ClassName = "MyClass";
string Variable = "i";
string Start = "0";
string End = "10";
#>



and here's the class (TestClass.tt) that uses it:



<#
this.ClassName = "TestClass";
this.Variable = "i";
this.Start = "0";
this.End = "20";
#>

<#@ include file="Path to template\Template.tt" #>



which results in this code:



//
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
//

using System;

public class TestClass
{
public static void HelloDude()
{
Console.WriteLine("Hello, Dude");

for (i = 0; i < 20;
i++)
{
}
}
}



Enjoy!

No comments: