Using Extension Methods - HedgehogDevelopment/tds-codegen GitHub Wiki

In order to use extension methods within a T4 template the assembly must be available to Visual Studio and the assembly directive must be used.

The assembly directive must either be a full path to the assembly containing the extension methods, or the assembly must be in a known location. Two commonly used known locations would be

  1. The GAC
  2. The Visual Studio Public Assemblies Folder

Example:

  • <#@ assembly name="C:\some\path\here\HedgehogDevelopment.CodeGeneration.Extensions.dll" #>
  • <#@ assembly name="HedgehogDevelopment.CodeGeneration.Extensions.dll" #> where the dll is in the GAC or the Public Assemblies folder

The Visual Studio Public Assemblies Folder is the recommended place to put commonly used tools and libraries that are only needed for Visual Studio. Normally this is located at:
%ProgramFiles%\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies

Compiling the Extensions Project

The Extensions project contains very general extension methods used typically for string manipulation. While using these extension methods, with your own T4 templates, is totally optional, the samples provided do require them.

For this project we are assuming that the file is to be placed in the Visual Studio Public Assemblies Folder. As part of the build process of the Extensions project there is a post build step to copy the dll and pdb to the Visual Studio Public Assemblies Folder (%ProgramFiles%\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies).

The build will fail if Visual Studio is not running as Administrator

The compiled Extensions assembly only needs to be compiled and copied to the Public Assemblies folder once. If active development of these extension methods is not required you can prevent building of this project. You can do this simply by going to the solution's Configuration Manager and un-checking the Build tab of the Extensions project.

Using the Extension Methods

To use the extension methods in your T4 file, compile the Extensions project and add these two lines to your T4 (.tt) file:

<#@ assembly name="HedgehogDevelopment.CodeGeneration.Extensions.dll" #>
<#@ import namespace="HedgehogDevelopment.CodeGeneration.Extensions" #>