Wednesday, June 13, 2012

Tutorial (part 1)

In one of my projects the customer had the requirement, that the application must be able to generate C files used in a test environment for electronic control units (ECU). I tried to generate the C code by using preprocessed text templates integrated in Visual Studio. This worked well but the the customer had further requirements: The template for the C code had to be customizable because a change in the test environment should not necessarily lead to an modification in the application. That was the point were I decided to write my own T4 text template generator that could parse T4 text templates at run-time. Because I had other projects were I needed similar functionality, including the open source project NHibernate.BusinessObjects, I decided to make the T4 Text Template Generator available to the community.

In the first part of this tutorial I will show you how to generate textual output by using a simple T4 text template. The examples are written in C# but you can do the same with VB. To create the T4 text templates, I use Visual Studio 2010 and the Tangible T4 Editor.

The first step is to create a T4 text template file. Therefore, create a new text file in your Visual Studio project and rename the extension to .t4. You should not create a new file based on the "Text Template” template because Visual Studio automatically assigns the TextTemplatingFileGenerator to the CustomTool property and creates a subsidiary text file. In this tutorial, you need to set the Copy to Output Directory attribute to either Copy if newer or Copy always.

The template directive must be the first directive in a template file. In the language attribute specify the language (either C# or VB) used in the template. In the next line add the text you want to generate.

<#@ template language="C#" #>
Hello World!

The next step is to use the template in your application. Therefore, create an instance of the OMS.Ice.T4Generator.Generator class and a stream writer. On the generator call the Generate() method and pass the path to the template and a stream writer as parameters. After the T4 template has been processed, the stream writer contains the generated Hello World! text.

namespace OMS.Ice.T4Generator.Tutorial
{
internal class Part1
{
public static void Generate()
{
IGenerator generator = new Generator();
var stream = new MemoryStream();
var textWriter = new StreamWriter( stream );
generator.Generate( Path.Combine( AppDomain.CurrentDomain.BaseDirectory, @"Part1\Part1.t4" ), textWriter );

stream.Seek( 0, SeekOrigin.Begin );
var textReader = new StreamReader( stream );
var generatedText = textReader.ReadToEnd();
}
}
}

In the second part of this tutorial, I will show you how to use C# in your text template.

No comments:

Post a Comment