Saturday, July 23, 2011

Generate several files from one template with the T4 Toolbox

I have been playing with using T4Toolbox to generate more than one file from a single template within Visual Studio.

T4Toolbox.Template

The Template class is the T4Toolbox’s version of TextTransformation that has a very special method called RenderToFile(); this method writes the text to be generated to a file. So, If I wanted to generate a file for each item in a list (say a list of database tables), I could use a foreach loop to create a new instance of my Template class and call Its RenderToFile method with different file names.

<#@ template language="C#v3.5" hostSpecific="true" #>
<#@ output extension="txt" #>
<#@ include file="T4Toolbox.tt" #>
<#
    Write("This file (minimum.txt) is also generated");
    for (int i = 7; i <= 11; ++i)
    {
        string fileName = string.Format("file{0:00}.lam", i);
        var lt = new LameFileTemplate(fileName);
        lt.RenderToFile(fileName);
    }
#>
<#+
private class LameFileTemplate : Template
{
    public LameFileTemplate(string fileName)
    {
        this.FileName = fileName;
    }
    private string FileName {get; set;}
    public override string TransformText()
    {
        #><#=this.FileName#><#+
        return this.GenerationEnvironment.ToString();
    }
}
#>

When I save this file, Visual Studio runs the template and creates several files. Notice that creates a file that matches the file name of the template; this can’t be helped. Since the default output extension is “cs”, it is important to set this to something else.

image
My template and generated files

NOTE: In a failed demo that I gave at the Portland Code camp this spring I wrote a template that would create a SELECT stored procedure for each table in a given database (each in its own file). The demonstration was too complicated and hard to follow. It used the Generator class SMO and a bunch of other stuff.