Generating a settings class from XML with T4
March 25, 2010
I’ve just posted a couple of T4 templates on CodePlex which you can use to generate a Settings class from XML. You get a compiled class which handles type checking, thread safety and loading and saving the settings to your database. You’ll never again have to worry about unloading your application when settings are updated.
A note about the 2 templates
There are 2 T4 templates:
- one for multiple sites (see Subdomains for a single application with ASP.NET MVC)
- and one for single sites. If you’re not sure which one you need, it’s probably the “single site” one :)
How it works
The XML:
<settings>
<group name="Appearance">
<group name="Colors">
<setting name="ContentBG" type="string" default="#FFFFFF" />
</group>
</group>
<group name="Authentication">
<group name="LDAP">
<setting name="Enabled" type="bool" />
<setting name="Servers" type="string[]" />
<setting name="Domain" type="string" />
<setting name="Port" type="int?" default="389" />
</group>
</group>
</settings>
What you get
/* Getting the settings object */
var settings = Settings.Get(); // for single site
// var settings = Settings.ForSite(Site.ID); // for multi-site setup
/* getting various settings */
var color = settings.Appearance.Colors.ContentBG; // var color is now set to a string, containing "#FFFFFF"
int? ldapPort = settings.Authentication.LDAP.Port; // ldapPort is now 389
/* setting various settings */
settings.Appearance.Colors.ContentBG = "#CCCCCC";
color = settings.Appearance.Colors.ContentBG; // color is now set to "#CCCCCC"
settings.Authentication.LDAP.Port = null; // all the settings values are type-safe
settings.Authentication.LDAP.Port = 636;