Export (0) Print
Expand All
1 out of 1 rated this helpful - Rate this topic

Accessing Visual Studio or other Hosts from a T4 Text Template

Visual Studio 2010

Updated: March 2011

In a text template, you can use methods and properties exposed by the host that executes the template, such as Visual Studio.

This applies to regular text templates, not preprocessed text templates.

Set hostspecific="true" in the template directive. This lets you use this.Host, which has type ITextTemplatingEngineHost. This type has members that you can use, for example, to resolve file names and to log errors.

Resolving File Names

To find the full path of a file relative to the text template, use this.Host.ResolvePath().

<#@ template hostspecific="true" language="C#" #>
<#@ output extension=".txt" #>
<#@ import namespace="System.IO" #>
<#
 // Find a path within the same project as the text template:
 string myFile = File.ReadAllText(this.Host.ResolvePath("MyFile.txt"));
#>
Content of myFile is:
<#= myFile #>

Displaying Error Messages

This example logs messages when you transform the template. If the host is Visual Studio, they are added to the error window.

<#@ template hostspecific="true" language="C#" #>
<#@ output extension=".txt" #>
<#@ import namespace="System.CodeDom.Compiler" #>
<#
  string message = "test message";
  this.Host.LogErrors(new CompilerErrorCollection() 
    { new CompilerError(
       this.Host.TemplateFile, // Identify the source of the error.
       0, 0, "0",   // Line, column, error ID.
       message) }); // Message displayed in error window.
#>

If you are executing a text template in Visual Studio, you can use this.Host to access services provided by Visual Studio and any packages or extensions that are loaded.

Set hostspecific="true" and cast this.Host to IServiceProvider.

This example gets the Visual Studio API, DTE, as a service:

<#@ template hostspecific="true" language="C#" #>
<#@ output extension=".txt" #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="EnvDTE" #>
<# 
 IServiceProvider serviceProvider = (IServiceProvider)this.Host;
 DTE dte = serviceProvider.GetService(typeof(DTE)) as DTE;  
#>
Number of projects in this solution: <#=  dte.Solution.Projects.Count #>

Date

History

Reason

March 2011

Created topic

Customer feedback.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.