Code generation using T4 Templates

In the current project I am working we have to write lot of Business Entity classes, all of them got same structure of code, like lot of GET / SET code for Properties, and all these classes implemented by INotifyPropertyChanged interface. So we have to write the lot of same stuff repeatedly. Few days back one of my local user group friend introduced me an impressive feature from MS Visual Studio called T4 (Text Templating Transformation Toolkit) templates. The T4 is a text transformation technology developed by Microsoft and used mostly for code generation by products like Microsoft DSL Tools. If you are using Visual Studio 2005, you need to install the SDK for T4 support, and in Visual Studio 2008 it comes pre-installed (Standard Edition and more).
You can get more information about T4 from MSDN

Here is an example of a simple T4 template, which will create a Business Entity class with the INotifyPropertyChanged interface implementation. The T4 template is nothing but simple Text files with some C# code.

  1. First you need to add a Text file, with the extension (.tt)
  2. Solution Explorer

    Solution Explorer

  3. Double click on the File, it will give you a warning like this. Click OK, it will generate a CS File (by default it is C#, you can modify to VB if you wish) under this template.
  4. Security warning

    Security warning

  5. Lets add some code for the template.
  6. < #@ template language="C#" #>
    < #@ output extension="cs" #>
    

    These two directives indicates the Template Language in C# and output of the template is also in C#. You can also use output extension htm, if you want to generate HTML files.
    Now we are creating the basic class structure

    using System;
    using System.ComponentModel;
    public class < #= this.className #> : INotifyPropertyChanged
    {
    }
    < #+
    string className = "Sample";
    #>
    

    These tags called Statement Blocks, and are used to enclose control code. And the tags called Class feature Blocks, which helps you to give features to the output class. The T4 Engine will use this take all the features from the template and Generate the class. And if you save the template again the security warning will come, say Yes, it will create the class file with basic structure, if you try to compile it will show some build error(s) like,missing the implementation of INotifyPropertyChanged interface, so let’s add the implementation.

    using System;
    using System.ComponentModel;
    public class < #= this.className #> : INotifyPropertyChanged
    {
    #region INotifyPropertyChanged Implementation
    public event PropertyChangedEventHandler PropertyChanged;
    protected void onPropertyChanged(string propertyName)
    {
    if (this.PropertyChanged != null)
    {
    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    }
    #endregion
    }
    < #+
    string className = "Sample";
    #>
    

    Now add the implementation of Properties(class features). For this first I created two-dimensional array, like this,

    string[,] properties = {{"int","userId"},{"string","comments"}};
    

    in this I have two properties. Now add some code in the Template to generate the variables and Properies. Here is the full implementation.

    < #@ template language="C#" #>
    < #@ output extension="cs" #>
    
    using System;
    using System.ComponentModel;
    
    public class  : INotifyPropertyChanged
    {
    &lt;#
    for (int idx = 0; idx
    private  _;
    &lt;#
    }
    CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
    TextInfo textInfo = cultureInfo.TextInfo;
    for (int idx = 0; idx
    
    public
    {
    get
    {
    return this._;
    }
    set
    {
    if(this._ != value)
    {
    this._ = value;
    this.onPropertyChanged("");
    }
    }
    }
    
    #region INotifyPropertyChanged Implementation
    
    public event PropertyChangedEventHandler PropertyChanged;
    protected void onPropertyChanged(string propertyName)
    {
    if (this.PropertyChanged != null)
    {
    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    }
    
    #endregion
    }
    

    And here is the output from it.

    using System;
    using System.ComponentModel;
    
    public class Sample : INotifyPropertyChanged
    {
    private int _userId;
    private string _comments;
    
    public int Userid
    {
    get
    {
    return this._userId;
    }
    set
    {
    if (this._userId != value)
    {
    this._userId = value;
    this.onPropertyChanged("Userid");
    }
    }
    }
    
    public string Comments
    {
    get
    {
    return this._comments;
    }
    set
    {
    if (this._comments != value)
    {
    this._comments = value;
    this.onPropertyChanged("Comments");
    }
    }
    }
    
    #region INotifyPropertyChanged Implementation
    
    public event PropertyChangedEventHandler PropertyChanged;
    protected void onPropertyChanged(string propertyName)
    {
    if (this.PropertyChanged != null)
    {
    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    }
    
    #endregion
    }
    

    You can import (add reference) to assemblies in template like using Import directive.
    You can get more information about T4 directives from Statement Syntax in MSDN.

    Happy Coding :)

This entry was posted in .Net, .Net 3.0 / 3.5, Visual Studio and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>