Table of Contents

IT:AD:Transformations:T4:HowTo:Create a Code File

Process

After starting a new page

Includes

Use IT:AD:Transformations:T4:Syntax:Directives to include what you need:

<#@ include file=”T4Toolbox.tt” #>

C# Namespaces

Use IT:AD:Transformations:T4:Syntax:CodeBlocks Create the namespace:

namespace <#=codeGenerationTools.EscapeNamespace(namespaceName)#>
{
//Code goes here:
}

Outputing Collapsible Regions

Single File T4 code quickly become unwieldy, multiple T4 files even worse. THerefore, whereas collapsible code sections in C# is a AntiPattern, collapsible code in T4 scripts is helpful.

<#
CodeRegion codeRegion = new CodeRegion(this, 1);
...
region.Begin("Primitive Properties");
#>

//Your code here

<#
codeRegion.End();  //Or ClearIndent();
#>
Note:The region will not be generated if no source code is generated for the region.

Outputing Code Indentation

Regions are ok…but what really makes code readable are indents/outdents…

<#
PushIndent(”\t”); //or ”\t\t” or "  "
#>
 
//Blah...

<#
PopIndent();
#>

TextTransformation Class

What do you mean PushIndent/PopIndent?!? Where did those method definitions come from?! Who the heck defined those methods?!?

Turns out the while you are in the *.tt file, you are in the context of a class – the TextTransformation class.

So, since you are in the context, anywhere in the page gives you access to a couple of other methods worth knowing about (links point to MSDN documentation pages):

The most commonly used will be WriteLine and the indent/output.

[

http://msdn.microsoft.com/en-us/library/bb126474.aspx](http://msdn.microsoft.com/en-us/library/bb126474.aspx)

Access to Host Environment (i.e. Visual Studio)

If we lived in a bubble…But we don't.

So we need to know how to get in touch with the world outside of our template…

EnvDTE.DTE dte = (EnvDTE.DTE) ((IServiceProvider) this.Host)
                   .GetService(typeof(EnvDTE.DTE));

Src: http://msdn.microsoft.com/en-us/library/bb126474.aspx

Getting the Current Namespace

A perfectly good example of why we need to ask questions outside of our template is to inquire as to the project's default namespace:

<#
// Get the project's default namespace:
IServiceProvider serviceProvider = (IServiceProvider)Host;
DTE dte = (DTE)serviceProvider.GetService(typeof(DTE));

ProjectItem templateItem = dte.Solution.FindProjectItem(Host.TemplateFile);
#>
namespace <#= templateItem.ContainingProject.Properties.Item("DefaultNamespace").Value #>.SomeSubNSOfYours {
//...
}

 

Standard Helper Classes

Are there any other methods we can use, other than what was available in the TextTransformation class?

Sure…just include the standard template that is used by all of the EF4 templates:

<#@ include file="EF.Utility.CS.ttinclude"#>

It's a single file that contains several classes of ready helper methods.

See here for the full list of methods you may find useful: [[IT/AD/T4/Syntax/ttinclude/]]