A little fun with T4 Templates
So, if you haven’t heard yet about T4, it’s a built-in DSL tool that comes pre-packaged with Visual Studio starting with the 2005 version. Even though T4 can look a bit scary, it can be very useful if you need to generate code on the fly within Visual Studio. I will leave it up to Scott Hanselman to fill you in on all the details since he has an excellent blog post on what T4 is an where you can go for more information.
Last week I wanted to generate a object wrapper around the <appSettings> section in my web.config/app.config file and after doing the same thing over and over again by generating a public read-only property for each setting, I decided to use T4 to read the <appSettings> section and generate a class all the properties that would become the wrapper around the ConfigurationManager.AppSettings[“…”] calls to retrieve the settings. To my surprise, this was pretty easy to do. I did a C# and VB.Net version and here is the C# version of the T4 template.
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ import namespace="Microsoft.VisualBasic" #>
<#@ template language="VBv3.5" debug="True" hostspecific="True" #>
<#@ output extension=".g.cs" #>
<#
Dim projectNamespace as String = "SettingsGenerator"
Dim fileName as String = "app.config"
Dim path as String = ""
Try
path = Host.ResolvePath(fileName)
Catch
Try
If fileName.ToLower() = "app.config" then
fileName = "web.config"
Else If fileName.ToLower() = "web.config" then
fileName = "app.config"
End If
path = Host.ResolvePath(fileName)
Catch
path = "<< App.config or Web.config not found within the project >>"
End Try
End Try
#>
//------------------------------------------------------------------------------
// FileName = <#= path #>
// Generated at <#= Now.ToLocaltime() #>
//
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
// NOTE: Please use the Add a Reference to System.Configuration assembly if
// you get compile errors with ConfigurationManager
// </auto-generated>
//------------------------------------------------------------------------------
using System.Configuration;
public static class AppSettings {
<#= RenderApplicationSettings(path) #>
}
<#+
Public Shared Function RenderApplicationSettings(ByVal path as String) as String
If Not File.Exists(path) Then Return ""
Dim sb as New StringBuilder()
Dim doc as XDocument = XDocument.Load(path)
For Each result as XElement in doc...<appSettings>.<add>
sb.Append(vbTab)
sb.Append("public static string " + result.@key + "{")
sb.AppendLine()
sb.AppendLine(vbTab + vbTab + "get {")
sb.AppendFormat("{0}return ConfigurationManager.AppSettings[""{1}""];{2}", vbTab + vbTab + vbTab, result.@key, vbCrLf)
sb.AppendLine(vbTab + vbTab + "}")
sb.Append(vbTab)
sb.AppendLine("}")
sb.AppendLine()
Next
Return sb.ToString()
End Function
#>
Click the download images below to download the templates for both VB and C#. Until next time…
Happy Programming!
Hi,
Where is the C# T4 Template. The other one is also coded in VB
Hi, both templates are written in VB; but they generate different course code. So, I guess I should have clarified; but It should matter that much what the template is written in; but the end result.
But, it should be pretty easy to convert the template languages to C#
Hi,
Yes I have noticed, anyway I am not familiar with VB that much how do you convert this line to C# anyway?
For Each result as XElement in doc….
I’m talking about the “doc….”
Unfortunately that is VB.net specific. I write c# as well; but when it comes to XML, VB.net rules because of the simple “axes” methods and XML literals. Have a look at this as a resource
http://msdn.microsoft.com/en-us/library/bb387055.aspx