Generate an AppSettings wrapper using T4 templates.

The “Text Template Transformation Toolkit“, more friendly T4,  it is a code generation tool bundled in Visual Studio since the 2008, so if you are using VS2010 as I am doing there’s no need to look around, is already there. In a nutshell, the T4 allow to generate one or more files using a source and a template. More ore less like XSLT but with the difference that it comes with a template based syntax, using C# and the ability to read and write on different sources than XML. The procedure is straight forward:

image image image
Add a *.tt file to the project. After writing the required code for the transformation in the template, by right clicking on the file we will spot and execute the command “Run Custom Tool”. Get the output. In this case the generated file is T4AppSettings.gen.cs.

The focus is on the tags <# #> , what’s inside the hashes is the business logic of the T4 and what’s outside is plain text ready to be printed out. A simple example of a T4 template is the T4AppSettings file:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="SampleKey1" value="SampleValue1" />
    <add key="SampleKey2" value="SampleValue2" />
    <add key="SampleKey3" value="SampleValue3" />
  </appSettings>  
</configuration>
<#@ template language="C#" debug="true" hostspecific="True"#>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ assembly name="System.Configuration" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ import namespace="System.Linq" #>
<#@ output extension=".gen.cs" #>
using System.Configuration;

public class AppSettingsHelper
{
<# 

    string configFilePath = Host.ResolvePath("app.Config");

            XDocument xmlDoc = XDocument.Load(configFilePath);

            List<XElement> elements = (from settings in xmlDoc.Descendants("appSettings")
                                      select settings.Element("add")).ToList();
            
            var attributes = (from settings in xmlDoc.Descendants("appSettings")
                             from add in settings.Elements("add")
                             from atts in add.Attributes("key")
                             select atts.Value);
                             
foreach (var attribute in attributes)
{                                       
#>
        public string <#= attribute #>
        {
            get
            {
                return ConfigurationManager.AppSettings["<#= attribute #>"];
            }
        }
                          
<#
}
#>
}

After having located the app.Config file (we can use the Host class to resolve the project path) the appSettings keys are loaded in a list with a linq to xml query, and then iterated, for each key a property with the same name will be created in the generated class. Alternatively to the linq approach it is possible to change the path of the config file for the ConfigurationManager class. In this way with ConfigurationManager.AppSettings.AllKeys we can get all the key names.

Anyway, let’s see the output class:

using System.Configuration;

public class AppSettingsHelper
{
        public string SampleKey1
        {
            get
            {
                return ConfigurationManager.AppSettings["SampleKey1"];
            }
        }
                          
        public string SampleKey2
        {
            get
            {
                return ConfigurationManager.AppSettings["SampleKey2"];
            }
        }
                          
        public string SampleKey3
        {
            get
            {
                return ConfigurationManager.AppSettings["SampleKey3"];
            }
        }
}

For more information, you can find pretty much everything about T4 templates at these link:

For code coloring check the community edition of VisualT4 at : http://www.visualt4.com/downloads.html




No Comments


You can leave the first : )



Leave a Reply

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