Eagle Eagle - 1 month ago 17
C# Question

T4 - TT - Using custom classes in TT files

I would like to use my own class define in a CS file in my TT.

Example:

public class ClassDefinition
{
public string NameSpace { get; set; }
public string Name { get; set; }
public string Protection { get; set; }

List<ClassProperty> Properties { get; set; }
}


My TT looks like:

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>

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

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

<#@ include file="$(ProjectDir)ClassDefinition.cs" #>

<#

// Read the model file
XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(this.Host.ResolvePath("GeneratedXmlFile.xml"));

IList<XmlNode> nodeList = new List<XmlNode>();
foreach (XmlNode node in doc.DocumentElement)
{
switch(node.Name)
{
case "Model":
{
ClassDefinition classDefinition = new ClassDefinition();


But I have this error message:

Compiling transformation: The type or namespace name 'ClassDefinition' could not be found (are you missing a using directive or an assembly reference?)


I checked on internet and tried to:
- use include
- use assembly
- use USING
But nothing works.

Any ideas ?

Answer

Here is the complete solution:

1) Separate the classes into another project 2) Include the reference to these classes through the TT via

<#@ assembly name="$(TargetDir)MyOwnLibraryProject.dll" #>
<#@ import namespace="MyOwnNamespace" #>

3) Do not forget to include a reference of this Library into your TT project

4) You have to copy the MyOwnLibraryProject.dll into the BIN\DEBUG folder of the TT solution

5) The magic appear !!!

Every time you changed your DLL do not forget to put the new version into the folder :) Or just configure your Library project output to be the same as your TT one. I would like to thank you all for giving guide lines and ideas.

Comments