Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run T4 programmatically

Tags:

c#

t4

I am trying to generate code using T4, but I am unable to run my TextTemplate programmatically using net 3.5.

All links which are supposed to explain how to do it are dead This This

Generating a code file by saving the TextTemplate works as expected.

like image 893
Ronijo Avatar asked Oct 14 '25 15:10

Ronijo


1 Answers

Update:

There is a newer version available than was mentioned originally see here the announcement: https://devblogs.microsoft.com/dotnet/t4-command-line-tool-for-dotnet/

It is located in

{VS_INSTALL_PATH}\Common7\IDE\TextTransformCore.exe.


Based on your comments.

I have tested the approach and did the following:

Add the TextTransform.exe into your project file (either with Add Existing Item, Copy and Paste it into your Project Folder and then reference it, or what ever)

Create a new .tt file, mine has the following content

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".txt" #>
<#
var dateTimeNow = DateTime.Now.ToString();
#>
<#=dateTimeNow#>

(Just a simple .txt file will be generated with a DateTime to see that its working)

Declare both files - TextTemplate1.tt and TextTransform.exe - as Copy always in its property Copy to Output Directory.

Now have the following code somewhere, I did it in Main

static void Main(string[] args)
{
    File.Delete("TextTemplate1.txt"); //delete the existing file, to make sure the code does what its supposed to do
    Thread.Sleep(1000); //wait for filesystem to do its job

    var proc = new Process
    {
        StartInfo =
        {
            FileName = "TextTransform.exe",
            Arguments = "TextTemplate1.tt"
        }
    };

    proc.Start();
    proc.WaitForExit();
}

(Droped the path, so its relative to the executing .exe - needs to be in same directory)

And with that you should successfully get this output

Everything works as expected, need more info to help you find your problem.

My TextTransform.exe file:

like image 169
Rand Random Avatar answered Oct 17 '25 04:10

Rand Random



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!