A few months ago I began to look into how to distribute T4 Text Templates via Nuget to do Code Generation.  Creating a Nuget package including T4 files is easy to do, just include them as content files.  Content files in Nuget Packages are copied into the root of your application when the package is installed.

Content Files in Nuget packages are added to the project with the default settings for the file type.  T4 files are added to a project along with a dependent file, which will add the following items to your project file.

<ItemGroup>
  <None Include="CodeGeneration.tt">
    <Generator>TextTemplatingFileGenerator</Generator>
    <LastGenOutput>CodeGeneration.txt</LastGenOutput>
  </None>
</ItemGroup>

For most use cases this may be adequate, however in my case I was doing complex code generation where multiple T4 files contributed to the generation of a single output file.  In order to suppor this scenario I needed the T4 files to be added without the Generator and LastGenOutput Tag.  I took to Twitter to see if there was an easy way to specify the default add behavior in Nuget.

nuget

Since there was no out of the box solution to my problem I decided to use the Nuget 2.0+ functionality of running custom Powershell scripts on install.  Some poking around on StackOverflow turned up a couple solutions which made use of XML parsing to modify the project file.  These were verbose and hard to read so I came up with a more compact, reusable, easier to understand solution by utilizing the passed in Project parameter and the DTE.

param($installPath, $toolsPath, $package, $project)

  #Get all of the T4 files in the package extension .tt
  $files = $package.GetFiles() | Where-Object {$_.EffectivePath -match "tt$"}

  foreach ($file in $files)
  {
     $fileName = $file.EffectivePath
     $ProjectItem = $project.ProjectItems | Where-Object {$_.Name -eq $fileName}

     #Set CustomTool to empty not TextTemplatingFileGenerator
     $CustomTool = $ProjectItem.Properties | where-object {$_.Name -eq "CustomTool"}
     $CustomTool.Value = ""
  }

Install.ps1 is also available on gist

This short script can be added to any Nuget Package as the Install.ps1 script to discover all T4 Text Template files included in the package and remove the extra tags and dependent files from the solution.

In addition when needing to modify the Project File on Nuget Package install I would highly recommend programming against the DTE Project Interface instead of using XML, like I did above, as it results in solutions with less lines of code, that is easier to understand.

You should follow me on Twitter here