Tuesday, December 19, 2017

T4 Generation Templates VS 2017

Hi,

It took me a lot of time to find good resources about T4 (even if there are no real alternatives built-in for visual studio). Here a small template to create multiple files easily...

I used following resources exists using archive.org:

Further resources:


kr,
Daniel

<#@
template debug="false" hostspecific="true" language="C#" #><#@

assembly name="System.Core" #><#@

import namespace="System.Linq" #><#@
import namespace="System.Text" #><#@
import namespace="System.IO" #><#@
import namespace="System.Collections.Generic" #><#@

output extension=".log" #><#
CleanOutputFolder();

string propertyName = "Prop";
           
Enumerable.Range(1,3).ToList().ForEach(id => {

StringBuilder builder = new StringBuilder();
builder.AppendLine("public class Data" + id.ToString("00"));
builder.AppendLine(" {");
Enumerable.Range(1,3).ToList().ForEach(propId => {
builder.AppendLine(" public int "+propertyName+propId+" { get; set; }");
});
builder.AppendLine(" }");

CreateClass("Data"+id.ToString("00")+".cs", builder.ToString());
});


#><#+
public void CleanOutputFolder()
{
string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
string outputFolder = Path.Combine(templateDirectory, "output/");
foreach(var file in Directory.GetFiles(outputFolder))
{
File.Delete(file);
}
}

public void SaveOutput(string outputFileName)
{
      string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
      string outputFilePath = Path.Combine(templateDirectory, "output/", outputFileName);
      File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString());

      this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
}

public void CreateClass(string fileName, string content)
{
#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
<#= content #>
}

<#+
SaveOutput(fileName);
}
#>


No comments: