I’ve written before about generic methods to access configuration values. As nice as such generics are, there is still one major issue – you’ll still have to use strings as configuration value keys. Which means there is a possibility to get an invalid key name by accident – or even worse, wrong value from the configuration. Such problems will often come out only after the project has been shipped.
One – and preferred – solution is to use Settings instead of AppSettings. These are strongly typed and can be accessed via keys (Properties.Settings.Default.SomeNiceSetting) – while the values are still in the configuration file (section <applicationSettings>).
Unfortunately, we cannot always use Settings, for several reasons.
So, I got fed up by having to memorize or copy the keys, do casting and so forth – and decided to figure out some better way to get the AppSettings values. After some other ideas, I ended up with two T4 templates.
First approach: string fields
- <#@ template debug="false" hostspecific="true" language="C#" #>
- <#@ assembly name="System.Configuration" #>
- <#@ assembly name="System.Core" #>
- <#@ import namespace="System.Configuration" #>
- <#@ import namespace="System.Linq" #>
- using System.Configuration;
-
- namespace <your-namespace-here>
- {
- public static class AppSettings {
- <#
- var configurationFileMap = new ExeConfigurationFileMap();
- configurationFileMap.ExeConfigFilename = this.Host.ResolvePath("Web.config");
- var configuration = ConfigurationManager.OpenMappedExeConfiguration(configurationFileMap, ConfigurationUserLevel.None);
- foreach(string key in configuration.AppSettings.Settings.AllKeys.Where(x => !x.Contains(":")))
- { #>
- public static readonly string <#= key #> = ConfigurationManager.AppSettings["<#= key #>"];
- <#} #>
- }
- }
This is my first approach – generate a static AppSettings class, which has readonly static string fields for all the AppSetting keys (note the !x.Contains(“!”) bit – that is to avoid the ASP.NET MVC keys).
This has both benefits and disadvantages over the second template – namely, you’ll get string values and will have to convert them to the required data type yourself. When someone messes up configuration (i.e. instead of “40” types in “4O” then obviously the cast to integer will fail), you have the option to fail gracefully – fall back to default value or such.
You can also combine this approach with generic methods linked above – i.e. use the t4 template to create constant strings for keys and send the now-hardcoded keys to generic method for appropriate handling.
Second approach: strongly typed properties
- <#@ template debug="false" hostspecific="true" language="C#" #>
- <#@ assembly name="System.Configuration" #>
- <#@ assembly name="System.Core" #>
- <#@ import namespace="System.Configuration" #>
- <#@ import namespace="System.Linq" #>
- <#@ import namespace="System.Globalization" #>
- using System.Configuration;
-
- namespace <your-namespace-here>
- {
- public static class AppSettings {
- <#
- var configurationFileMap = new ExeConfigurationFileMap();
- configurationFileMap.ExeConfigFilename = this.Host.ResolvePath("Web.config");
- var configuration = ConfigurationManager.OpenMappedExeConfiguration(configurationFileMap, ConfigurationUserLevel.None);
- foreach(KeyValueConfigurationElement setting in configuration.AppSettings.Settings)
- {
- if (setting.Key.Contains(":")) //these are ASP.NET MVC keys
- continue;
-
- string settingType;
- int i; bool b; decimal d;
- if (int.TryParse(setting.Value, out i))
- settingType = "int";
- else if (bool.TryParse(setting.Value, out b))
- settingType = "bool";
- else if (decimal.TryParse(setting.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out d))
- settingType = "decimal";
- else { #>
- public static string <#= setting.Key #> { get { return ConfigurationManager.AppSettings["<#= setting.Key #>"]; }}
- <# continue; } #>
- public static <#= settingType #> <#= setting.Key #> { get { return <#= settingType #>.Parse(ConfigurationManager.AppSettings["<#= setting.Key #>"]); }}
- <# } #>
- }
- }
Second approach tries to guess the appsetting type by trying to cast the value into several common types (int, boolean and decimal in the code above) and create the AppSettings class property in an already correct type.
This could be improved in several ways – for example, use TryParse() in non-string properties, use IConvertible and so forth. You probably need add your own types, too.
As an example, here is my test <appSettings>:
- <appSettings>
- <add key="TestDecimal" value="6.02214129" />
- <add key="TestBoolean" value="True" />
- <add key="TestInt" value="420" />
- <add key="TestString" value="Alea jacta est" />
- </appSettings>
and output from the template:
public static class AppSettings {
public static decimal TestDecimal { get { return decimal.Parse(ConfigurationManager.AppSettings["TestDecimal"]); }}
public static bool TestBoolean { get { return bool.Parse(ConfigurationManager.AppSettings["TestBoolean"]); }}
public static int TestInt { get { return int.Parse(ConfigurationManager.AppSettings["TestInt"]); }}
public static string TestString { get { return ConfigurationManager.AppSettings["TestString"]; }}
}
You’ll have to add the AppSettings.tt template to the root folder of your application – or modify the this.Host.ResolvePath("Web.config") accordingly.
One thing that you have to note is that the configuration XML keys can have symbols that are not allowed in C# field/property names, such as the aforementioned colons in ASP.NET MVC keys. Best approach is probably to remove such symbols from field names, but not from the key names in return statements, as latter can handle just fine code such as ConfigurationManager.AppSettings["I:Really:Suck:At:Naming!"].
Another problem is that I was unable to get the template generation to auto-run when the Web.config changes. I tried to follow an old answer from Stack Overflow, but no dice. If you have any ideas/suggestions about this or other possible improvements, please post them to the comments – meanwhile you’ll just need to right-click on AppSettings.tt in Visual Studio and choose “Run custom tool” (if that option is missing, set in AppSettings.tt file properties “Custom Tool” to “TextTemplatingFileGenerator”).