Question

I am relatively new to T4 templates. I am working in visual studio 2012 and using the tangible T4 editor. I have my text templates in one project and I want to read a class in another project and do some processing and write the generated code to a third project. I want to pass in the class file path to my template For example "C:/Code/Project2/ClassFooBar.cs" and the template will read the class from the given location and do some processing with the class properties and write the generated code to project3. I want to pass in the file path since my project has a number of class files and there is not a pattern that I can specify in the template.

My solution structure is:

SolutionFoo:
 - Project1
    -TextTemplate.tt   

 - Project2
   - ClassFooBar.cs

 - Project3
    -GeneratedCode.cs

anyone can guide me with a clean way of passing in the class path and a way to writing the generated code to Project3?

Was it helpful?

Solution

In order to avoid the file locking issue or if you do not want to reference your Project2, try what I like to call "Design Time Reflection".

Since you have both projects (The one containing the T4 and the one containing the class you want to reflect) in the same solution, you can use the EnvDTE.CodeModel to transverse all code artifacts in your solution (Namespaces, Classes, ...) without the need to have Project2 built and referenced.

Have a look at the VisualStudio Automation. And if you are using tangible's T4 Editor, there is a free reusable template in their gallery that eases the access to the EnvDTE.CodeModel from within a T4 template.

This might be a good start point: http://t4-editor.tangible-engineering.com/blog/walking-the-visual-studio-code-model-with-t4-template.html

OTHER TIPS

I recently wrote up a description of this for another question. Do not read the class file. Instead, use reflection to work with the generated class. It will be a lot simpler than trying to parse c#.

[Edit - Appending untested pseudo code] using System.Reflection;

private void Reflect()
{
     var properties = typeof(ClassFoobar).GetProperties();
     var myRuntimeTemplate = new MyRuntimeTemplate();
     myRuntimeTemplate.DoSomeMethodDefinedInT4(properties);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top