views:

26

answers:

1

I have a template that generates a class and a complementary interface to go with it from a script like so:

<#@ template language="C#v3.5" hostspecific="True" debug="True" #>
<#@ output extension="cs" #>
<#@ include file="T4Toolbox.tt" #>
<#@ include file="../BusinessObjectTemplate.tt" #>
<#
BusinessObjectTemplate template = new BusinessObjectTemplate();
template.BusinessName="Priority";

template.PropertyList=new Dictionary<string,BusinessPropertyT4>{
    {"Value",new BusinessPropertyT4("byte")},
    {"Display",new BusinessPropertyT4("string")},
};
template.TopRegionText="internal ModelPriority(byte value, String display)\r\n\t\t{\r\n"+
    "\t\t\tValue=value;\r\n"+"\t\t\tDisplay=display;\r\n"+ "\t\t}";
template.Render();
#>

How would I generate the TopRegionText(constructor) from the script without feeding it a direct string and have it go into the right place in the template?

+1  A: 

Assuming that you would prefer to use templating functionality of T4 to generate the constructor, you can define a virtual method (i.e. GenerateTopRegionText) in BusinessObjectTemplate class and call it from BusinessObjectTemplate.TransformText method. Having done that, you can override it like so:

<#+
class PriorityTemplate: BusinessObjectTemplate
{
    override void GenerateTopRegionText()
    {
#>
    internal ModelPriority(byte value, string display)
    {
        Value = value;
        Display = display;
    }        
<#+
    }
}
#>

More here.

Oleg Sych
+1 awesome this is exactly what I wanted, now to learn my way through implementing it =)
Maslow
can this be done using a script rather than template inheritance perhaps using a Func<String> or a settable property?
Maslow
I can't think of a different way off the top of my head. You can try and experiment with different approaches. Look at the preprocessed template code generated by T4 in temp directory (or use preprocessed templates in 2010) to see how it would work. Let me know if you find a better way to do it.
Oleg Sych