views:

391

answers:

1

Hi all,

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!

+1  A: 

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.

Michael Maddox
Reflection is generally considered a bad method via T4 because it locks files or assembly so you can't edit it, the EnvDTE COM doesn't have this limitiation
Maslow
@Maslow: Anytime you access a DLL in any way from T4 inside Visual Studio (reflection or not), the DLL gets locked and cannot be easily changed without closing Visual Studio and reopening it. I personally consider that a bug in the Visual Studio T4 implementation (Microsoft would likely argue it is a caching feature). The lock happens with EnvDTE as well, but you aren't trying to change that DLL, so you don't notice it got locked and it doesn't matter. This locking issue has nothing specifically to do with reflection, it happens even when you aren't using reflection.
Michael Maddox
@Michael - Oleg Sync says specifically not to use reflection from within T4 http://stackoverflow.com/questions/1153542/t4-code-generation-access-types-in-current-project I don't know the reasoning, and maybe the context there was different, but that's what I was adding to this thread, I should have found the link and included it in the initial comment.
Maslow
@Maslow: I'm aware of that post by Oleg (I upvoted orsogufo's comment above a long time ago) and I think I now understand what you are trying to communicate. Yes, for the scenario in this question, there are better options than reflection that won't lock DLLs. Calling a method on a DLL is what causes the DLL to get locked and there are ways to inspect a DLL without calling methods. Thanks.
Michael Maddox