Reflection does not work as desired in some T4 cases

Jun 14, 2010 at 5:36 PM

All --

Please help with this question about the way T4 handles Reflection, etc.

I use a T4 design whereby a project-specific T4-File includes and calls a generic T4-Generator; then, the generic T4-Generator includes and calls a generic T4-Template.

I want my name of the physical T4-File to appear in my output (without having to hard-code it or otherwise manually maintain it); so, in the T4-File, I try to use Reflection to set a property in the T4-Generator, something like this...

myGenerator.T4ReflectionForFile = Assembly.GetExecutingAssembly().GetName().Name + "| " + MethodBase.GetCurrentMethod().DeclaringType.Name  + "| " + MethodBase.GetCurrentMethod().Name;

...then the T4-Generator passes that value along to the T4-Template which in turn prints it in the actual output.

The reason that I want this is that I want to put the name of the various T4 code-generation pieces into the code comments so that I can find the places to fix bugs more quickly. Furthermore, when looking at a code-generated output file, it would be nice to know, at-a-glance, how that generated output came to be and what T4 code-files were used to produce it.

In each part of the process, (T4-File, T4-Generator, and T4-Template), I use Reflection to make this call...

Assembly.GetExecutingAssembly().GetName().Name + "| " + MethodBase.GetCurrentMethod().DeclaringType.Name  + "| " + MethodBase.GetCurrentMethod().Name

Case_1:

In the T4-File, FileName="_T4L2sEntityManager03File.tt", and the call yields something like this...

ps3svpll| GeneratedTextTransformation| TransformText

Case_2:

In the T4-Generator, FileName="_T4L2sEntityManager03Generator.tt", and the call yields something like this...

ps3svpll| _T4L2sEntityManager03Generator| get_T4ReflectionForGenerator

Case_3:

In the T4-Template, FileName="_T4L2sEntityManager03Template.tt", and the call yields something like this...

ps3svpll| _T4L2sEntityManager03Template| get_T4ReflectionForTemplate


The problem is that the output from a call to Reflection is fine in Case_2 and Case_3 but in Case_1 it does not really help much at all.

The question is how can one make Reflection to work in Case_1 as it does in Case_2 and Case_3?

 

What do you think?

Please advise.

Thank you.

-- Mark Kamoski


 

Coordinator
Jun 14, 2010 at 8:24 PM

Mark,

You can use TransformationContext.Host.TemplateFile for Case #1. Alternatively, you can also turn on the debug option for the template and use StackTrace class to walk the StackFrame hierarchy, and output the file name.

Oleg