Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use .net Reflection with T4?

I have a c# project which includes a Text Template. I would like this template to generate some SQL based on reflecting against the C# classes in the project.

How does one access the current project's contents using T4? Is it possible, and if so, is Reflection available, or is it access to just the raw source that must then be parsed?

Thanks in advance!

like image 969
Andrew Theken Avatar asked Dec 06 '09 22:12

Andrew Theken


People also ask

How do I add a .TT file to Visual Studio?

Include the file into your Visual Studio project. In Solution Explorer, on the shortcut menu of the project, choose Add > Existing Item. Set the file's Custom Tools property to TextTemplatingFilePreprocessor. In Solution Explorer, on the shortcut menu of the file, choose Properties.

What is transform all T4 templates?

t4 is basically a tool built into VS for doing text transformation, typically for doing code generation. Transform All T4 Templates searches your solution for *. tt files and executes them to create other text, again typically source code, files.


2 Answers

How does one access the current project's contents using T4?

One way is to use the EnvDTE COM component. Googling T4 and EnvDTE should bring back plenty of examples.

Is it possible, and if so, is Reflection available, or is it access to just the raw source that must then be parsed?

Reflection is definitely available from T4. It works mostly as you would expect.

Oleg Sych has a number of great blog entries regarding common T4 usage scenarios, but there are plenty of other resources for T4 out there as well.

like image 145
Michael Maddox Avatar answered Sep 21 '22 05:09

Michael Maddox


Completely aside from locking problems, be careful using reflection within a T4 template. The template generator in VS2010 runs against version 4.0 of the Framework, so you could introduce unwanted dependencies if you're generating code for 3.5 or below.

I just found this out the hard way, after using reflection to decide whether to generate parameterless or parameterised calls to ToString for various BCL types. TimeSpan has only ToString() in 2.0, but 4.0 adds ToString(string) :P

like image 43
anton.burger Avatar answered Sep 19 '22 05:09

anton.burger