notes of a dotnet developer

Main menu

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:

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:

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.