T4 - Text Template Transformation Toolkit CvsReader
Mar 1, 2011 • Michal Franc -
While watching Scot Hansleman presentation about MVC I discovered great feature in Visual Studio 2010. T4 is an code generation engine. It translates template files (“*.tt”) , using scripts created in C# or VB , to C# , VB , T-SQl , Txt files etc.
You can generate a lot of different things :
Dynamic classes which are changing based on the settings file
CRUD procedures which are generated dynamically
Generated Unit Tests (that would be cool)
I have made a simple template which generates Class that automates reading the CVS files. It’s a simple project created just 4fun.
CVS format file :
First line defines column names and second line specifies their types.
Templates are stored in “.tt” files. Every “.tt” files starts with a “template” directive containing options. You can specify language used to analyze file . You also need to load the assemblies used by the script blocks in template. I just need System assembly for IO operations.
With Visual Studio 2010 there is a special item type “Text Template”. When you create this item VS will ask you if you want to run the template. T4 engine generates new files every time you save “changes to the “*.tt” file.
Let’s create a simple container class which stores data defined in the CVS . Column name and type is defined in the first two lines.
This Script loads first two lines from a file and loads them into the columns and types string. As you can see this code is in “C#”. Every script in the template must be within the “<# #>”.
With column names and types we can start the container class generation. Let’s call it “CvsData”.
Code outside the “<# #>” scope is treated just like simple text. Inside script I m using the Write() function to create text. For each column script generates property.
Generated “*.cs” file.
Now I can compile this file and use the CvsData class.
I just want to read data and return it as a List with CvsData objects.
This is a very simple example. Created just for fun and to demonstrate basics of T4, Check the Oleg Sych site for more info and tutorials. He has created a bunch of great materials about T4.
I will definitely spend more time playing/learning the T4 engine.