Pablo Galiano : TTxGen on MSDN Code Gallery

Subscriptions

<December 2008>
SuMoTuWeThFrSa
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

News

Subscribe to Pablo Galiano by Email

Post Categories

TTxGen on MSDN Code Gallery

TTxGen is a generic single file generator based on the text templating engine.

What is that???, Some background:

Single file generators or custom tools are COM components registered with Visual Studio that generate code.

To implement a custom tool you basically need to implement the IVsSingleFileGenerator interface. For more detail you can read kzu's post 

A custom tool also needs to be registered and associated to file a extension.

The IVsSingleFileGenerator interface declares two methods:

int DefaultExtension (
	out string pbstrDefaultExtension
)

This method is used to specify the extension of the generated file.

int Generate (
	[InAttribute] string wszInputFilePath,
	[InAttribute] string bstrInputFileContents,
	[InAttribute] string wszDefaultNamespace,
	[OutAttribute] IntPtr[] rgbOutputFileContents,
	out uint pcbOutput,
	[InAttribute] IVsGeneratorProgress pGenerateProgress
)

This method is used to generate the code that we want. It receives the name of the file associated with custom tool, the content of the file and it returns a Byte[] with the generated code.

One serious drawback is that we need to implement, register and deploy one custom tool for each representation of custom code that we want to generate.

Ok that's all for custom tools, now the funny part...

As you may know the text templating (t4) engine is now part of Visual Studio 2008. Based on this I created an implementation of a generic single file generator using t4.

The idea here is to have the same context as in custom tools. For that I have created a custom directive processor that injects the context needed on the tt:

<#@ output extension=".xml" #>
<#@ ParentFileInjector processor="TTxGenDirectiveProcessor" requires="fileName='Sample.xml'" #>
<#= this.ParentFileName #>
<#= this.ParentFileContent #>

If we want to access the parent file name we can use the ParentFileName variable, and for the content we can use the ParentFileContent.

TTxGen comes with some tooling to create a xGen template with the proper directives and context to start generating code:

scn1

scn2

The Create xGen Template command unfold a tt template, default the extension to the extension of the parent file and it automatically replace the requires argument.

 

You can download TTxGen from codegallery.

 

Pablo

posted on Monday, February 04, 2008 6:10 PM by pga

What do you think?

(required) 
required 
optional
required