Monday, August 24, 2009

T4 - Text Template Transformation Toolkit

At the Lansing Day of .NET I saw a presentation about Microsoft's T4 (Text Templating Transformation Toolkit).  At the time I couldn't think of where I could use this tool to be more DRY because dry folks go over big at parties :)  Some of the examples given were in generating documentation and in generating a data layer.  There are tools specifically for those tasks so that didn't sit well with me.


Our current product is a web product and we sometimes use the session to pass data between our pages.  It was a lot of redundant typing and I figured T4 could help.


The template takes a list of strings and makes a static class exposing the strings as constants.  These strings are used as keys to pull data out of the session.  Some of the keys need post processing when the data is pulled out.  In this implementation I'm doing that via reflection but after writing it I figure a dictionary could do the trick and be faster.


Put this text in a .tt file and save it.  It will generate a .cs file shown below:




<#@ template language="C#v3.5" debug="true" #>
<#@ output extension="cs" #>

namespace tt
{
    /// <summary>
    /// Used to store keys to lookup session data.  This should ensure we don't have collisions and can easily refactor.
    /// </summary>
    /// <remarks>
    /// This class is autogenerated by SessionKeys.tt.  Do not modify this file!
    /// </remarks>
    public static class SessionKeys
    {
<# foreach ( string constant in GetConstants())
{
string[] inputs = constant.Split(',');

for (int i = 1; i < inputs.Length; i++)
                {
string attribute = inputs[i].Trim();
if(attribute.Length > 0)
{
WriteLine("[" + inputs[i].Trim() + "]");
}
                }

WriteLine("public const string " + inputs[0].ToUpper() + " = \"" + inputs[0] + "\";");
}
#>

    }
}

<#+
///<summary>
/// provides constants for SessionKeys.cs.  Some constants need attributes to be processed.
/// This is done via Attributes in the namespace UrbanScience.Si2.Module.LeadReporting.Utilities.
/// The format of the strings in this list should be IDENTIFIER, Attribute, Attribute, Attribute....
///</summary>
private string[] GetConstants()
{

return new string[]
{
"Name,InputAllowsWildCard",
"StartDate",
"EndDate",
"StateList, CleanMultipleInput",
};
}
#>



Here is the generated class:

namespace tt
{
    /// <summary>
    /// Used to store keys to lookup session data.  This should ensure we don't have collisions and can easily refactor.
    /// </summary>
    /// <remarks>
    /// This class is autogenerated by SessionKeys.tt.  Do not modify this file!
    /// </remarks>
    public static class SessionKeys
    {
            [InputAllowsWildCard]
public const string NAME = "Name";
public const string STARTDATE = "StartDate";
public const string ENDDATE = "EndDate";
[CleanMultipleInput]
public const string STATELIST = "StateList";
           
    }
}

No comments: