T4 as a general-purpose .NET scripting engine


At first, I had a mixed reaction to Kirill’s new article about using T4 and JavaScriptCommentStripper to strip comments and non-significant white space from JavaScript files. The T4 template he created for this purpose was not a template at all - it had no text blocks, just code going through a directory and stripping comments from each “debug” JavaScript file in it. This didn’t fit in with what I thought the purpose of T4 was. Kirill’s T4 template was essentially a script file written in C#.

Only when I came back to look at it again a couple of days later I realized what this really means - you can use T4 to execute general purpose scripts written in Visual Basic or C#. Simply because it was created as a text transformation engine, doesn’t prevent you from doing other things. For example, the following template will display a message box:

<#@ template language=C##>
<#@ assembly name=System.Windows.Forms.dll#>
<#@ import namespace=System.Windows.Forms#>
<#
    MessageBox.Show(”Hello, World”);
#>

This script is self-contained; there is no need for a project file; simply run it using TextTemplatingFileGenerator custom tool in Visual Studio or TextTransform.exe command line utility in Windows Explorer or command prompt.

Of course it is not an ideal .NET script engine - it will generate an empty output file; some of the methods, like Write will not be applicable, etc. And no, it is not dynamic and not as powerful as PowerShell. However, as Kirill’s article illustrates, T4 gets the job done and allows you to use your main programming language to do it quickly.


Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!