Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the location of a .tt file in T4

Tags:

c#

.net

t4

Using T4 I want to generate some code based on examining what files are in a directory relative to the template file being executed.

Is there a way in c# to identify what the path of the current template file is?

like image 463
Andrew Theken Avatar asked Dec 11 '08 18:12

Andrew Theken


People also ask

What are .TT files?

TT stands for - Visual Studio Text Template is a software development tool created by the Microsoft. Further explanation - TT file contains text block and control logic used for generating new files. To write the Text Template file we can use either - Visual C# or Visual Basic Code.

What are T4 templates in Entity Framework?

T4 templates in entity framework are used to generate C# or VB entity classes from EDMX files. Visual Studio 2013 or 2012 provides two templates- EntityObject Generator and DBContext Generator for creating C# or VB entity classes. The additional templates are also available for download.

How do I add a .TT file to Visual Studio?

Include the file into your Visual Studio project. In Solution Explorer, on the shortcut menu of the project, choose Add > Existing Item. Set the file's Custom Tools property to TextTemplatingFilePreprocessor. In Solution Explorer, on the shortcut menu of the file, choose Properties.


1 Answers

  • You need to set the hostspecific="true" property of the <#@ template directive to True.
  • This will make T4 generate a special property called Host, which gives you access to ResolvePath method and TemplateFile property.
    • Host is of type ITextTemplatingEngineHost.
    • TemplateFile is a String value which is typically the file-system path of the .tt file - however other T4 hosts (i.e. hosts other than Visual Studio) which may load a T4 file in-memory or otherwise may return some other value as the template file doesn't exist on-disk.
  • You can find details here: http://www.olegsych.com/2008/02/t4-template-directive/

For example:

<#@ template hostspecific="true" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#
    ITextTemplatingEngineHost t4Host = this.Host;
    FileInfo t4FileInfo = new FileInfo( t4Host.TemplateFile );
#>

// This file generated by <#= t4FileInfo.FullName #>

like image 141
Oleg Sych Avatar answered Oct 22 '22 23:10

Oleg Sych