Running a T4 template using C#

Novice picture Novice · Jan 24, 2011 · Viewed 18.2k times · Source

I have T4 template (mycode.tt) which generates a cs file. I usually right click the tt file and select RunCustomTool which internally takes an xml file and generate code for me. Now i want to run the custom tool using a c# windows application. So onclick of a button i want to run the Custom Tool . Is it possible to run the CustomTool from c#.

Edit:

I have 2 tt files and one of them doesn't have a codebehind cs file. But another has a .cs file attached with it and i am invoking the second file's TransformText() method from the first .tt file. So i need to invoke the first file.So i cannot use the TransformText() method. Is there a way to dynamically call the textTemplate file ?

Answer

jb_ picture jb_ · Jan 24, 2011

You can easily achieve it, when you using VS2010. If you add a new file to the project, choose a preprocessed text template file. You can edit the template just as normal. Instead of generating the output directly, the file generates the code that is generated normally. I know it sounds confusing. But what you see in your output file is the code generated by the text templating toolkit to get your output (more or less).

This is a short example of a preprocessed text template named "TestTemplate.tt" and how do you use it in your code:

The tt-file:

<#@ template language="C#" #>
Some output.

Code:

using System;
using System.Diagnostics;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            TestTemplate testTemplate = new TestTemplate();
            Debug.Print(testTemplate.TransformText());
        }
    }
}