T4 to rescue and save you time

by Vahid 11. June 2010 05:56

till yesterday i had never used T4 for a real problem solving. i knew what it is but i did not know how great and easy it is.

in my current scenario i have a database table which contains options available for each property of 30 available properties of items to be added to the system. the table has almost 500 records.  in the item registration page i had to create a structure like this for each property:

<div id="div1" runat="server" class="row">
<asp:Label ID="SmartLabel13" runat="server" AssociatedControlID="" Text="Title of the property"></asp:Label>
<asp:DropDown ID="SmartDropDown1" runat="server">
<asp:ListItem Selected="True" Text="-----------" Value="">
<asp:ListItem Selected="True" Text="option 1" Value="option 1 value">
<asp:ListItem Selected="True" Text="option 2" Value="option 2 value">
<asp:ListItem Selected="True" Text="option n" Value="option n value">

creating 50 of these snippet and adding almost 12 list item for each of them along with setting the control names and property title and also AssociatedControlID of each would have taken me at least a day. i thought i could benefit from T4(Text Template Transformation Toolkit which is used for code generation) to save myself some time. so i started creating a T4 file to do this and vala… 15 minutes later i had it done. i have to say that, it was the first time that i actually was using T4. i cannot believe how easy it is to use it. the following few lines of code saved me at least a day by generating around 1000 lines of code:

<#@ template language="C#" debug="True" #>
<#@ output extension="txt" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #> 
<#@ import namespace="System.Data.SqlClient" #>
string catName=string.Empty;
int i=50;
System.Data.SqlClient.SqlConnection cn=new  System.Data.SqlClient.SqlConnection("data source=.\\sqlexpress;integrated security=true;database=Irizzle");
SqlCommand cmd=new SqlCommand("select * from IRZ.Lookupvalues order by Category",cn);
SqlDataReader dr=cmd.ExecuteReader();
<asp:ListItem Text="<#= dr["Name"].ToString()#>" Value="<#= dr["Code"].ToString()#>" />
<div id="div<#= dr["Category"].ToString()#>" runat="server" class="row">
<label for="drp<#= dr["Category"].ToString()#>"><#= dr["Title"].ToString()#></label>
<Irizzle:SmartDropDown ID="drp<#= dr["Category"].ToString()#>" runat="server">
<asp:ListItem Selected="True" Text="-----------" Value=""/>
<asp:ListItem Text="<#= dr["Name"].ToString()#>" Value="<#= dr["Code"].ToString()#>" />
<#    i++;}

i am sure T4 can save you and your companies hell lot of time. what i am wondering about is why not so many people talk about this great feature.

Tags: , ,

.Net | Technical

Do You Know About T4 (Text Template Transformation Toolkit) Code Generation In Visual Studio?

by Vahid 14. April 2009 03:15
Working with Microsoft products always has some surprises, now be it a defect, missing functionality or an unknown cool new feature. What's the story? Well recently i was listening to a DotNetRocks show in which i heard the word "T4" which is something regarding to code generation in Visual Studio 2008! i was like, what is this? How come that i have not heard it before? Anyway I was really surprised. So as a code generation passionate i did some R&D about it and here is the outcome.  What is T4? T4 is a code generator built right into Visual Studio. To be clear, we HAVE THIS NOW on our system. So now is the right time to introduce code generation to our company. this means If we are doing something twice or more, manually, in our project, we should stop it and generate it instead. However, there is an issue with this technology and that's the fact that Microsoft does not support it completely as of now and this reason why it is kind of hidden in VS. There's no item templates in File | New Item and there's no intellisense or syntax highlighting. However you don't need this, but if you want really get the most out of T4, first, have a look at "T4 Editor Community Edition." That'll get you some basic coloring.

Now, let's start doing something with T4. go into Visual Studio and create a new Console(or any other type) Application and add a Text File. Then rename it something with a .tt extension. You'll get a warning. Click OK


Now, look in Solution Explorer at the .tt file. If you're using C#, you'll have a sub .cs file, or if you're using VB, a sub .vb file. That's the file that will hold the result of the generation. This is the same visual metaphor used to the express the template/generated file relationship with .designer files you've seen elsewhere in Visual Studio. If you look in the Properties for the .tt file, you'll see it's using a CustomTool listed as the "TextTemplatingFileGenerator." This custom tool extensibility point is how things like XSD and WSDL code generators hook in to generate their artifacts.T4 can generate any kind of text file, not just code. You can use it in your projects, as above, or you can call T4 from the command-line. In the following example, I use Damien's T4 templates against the sample Chinook Database.

Notice that I've named the .tt file the same as the .dbml, so Damian's code can find it. I also continue to let original LINQ to SQL generate it's .designer.cs file, but make that file's Build Action "None" so it's not ever compiled. That effectively puts Damian's code in charge. Here's a screenshot showing a bit of Damian's T4 template using the syntax highlighting from the Clairus T4 Visual Studio free download. It looks like a lot like ASP.NET Web Forms. The code blocks are where your logic is and outside the code blocks is the template for whatever you want to generate. Notice how Damien gets input and sets output. You have full control; you can read files off the file system, from with your project, etc. He sets the output extension also. In this example his generated file is Chinook.generated.cs.


anyway i believe this would be great technology for code generation and we will be hearing much more about it. following are some good resource which i have found in internet and thought of sharing them with you. hope you like them:

*       Creating your first code generator *       Troubleshooting code generation errors *       Debugging code generation files *       Creating reusable code generation templates *       Creating complex code generators *       Reusing code generators on multiple projects *       How to create a simple T4 template *       How to use T4 to generate .config files *       How to use T4 to generate Decorator classes *       How to use T4 to generate CRUD stored procedures *       How to use T4 to generate strongly-typed navigation class in ASP.NET *       How to use T4 to generate strongly-typed AzMan wrapper *       How to generate multiple outputs from single T4 template *       T4 template for generating ADO.NET Entity Framework Stored Procedures  T4 script for generating ADO.NET Entity Framework Views *       T4 template for generating LINQ to SQL Data Context *       T4 template for generating WiX source files *       T4 template for generating SQL view from C# enumeration *       MSBuild task for transforming T4 templates *       T4 template for generating state machines in C# *       T4 Toolbox project in CodePlex


Tags: , ,

.Net | Technical