Using Configuration Sections to Customize Application Settings and Serializing Them to External Config Files
.NET configuration files provide a very useful mechanism for specification of runtime settings for applications, web sites and web pages. Probably, the biggest benefit of configuration files is that settings can be changed dynamically without having to recompile the application. Every time the application is loaded for the first time settings within the configuration files are cached. Thereafter at the event of any change the settings are re-cached. If there are any custom settings that users might want to add, the AppSettings configuration section can be used to add key value pairs and then later read or changed from within the application programmatically. However, by creating custom Configuration Sections settings can be organized in a more ordered fashion. Also, you can have greater control over the structure and types of the properties of your configuration section rather than having simple key and value pairs.
In this blog post, we'll focus on creating a custom Configuration Section by deriving a class from ConfigurationSection, setting desired properties programmatically and then serializing it to a configuration file. To avoid re-caching of the entire web.config file (or App.config in case it is not a web application) we will serialize our section to an external file so that changes made to our section do not cause re-caching of the all the settings within web.config, leading to better performance.
Let’s say we need to specify as part of the configuration settings the URLs of two images that would form the header and footer of all the web pages in our application. Of course, this can be achieved without using configuration at all but for the sake of learning we will go ahead and use this example.
So let’s begin.
Start Visual Studio and create a new Website. For our specific example we’ll call it CustomConfigSectionExample.
Add the following to default.aspx.
<asp:Label ID="Label1" runat="server" Text="Header URL"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text="Footer URL"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
Next, we shall create our custom configuration class. And call it WebPageConfiguration. The structure of the class is relatively simple. It has two properties HeaderImageURL and FooterImageURL, both of type string. Notice that the class derives from System.Configuration.ConfigurationSection. Also, notice the ConfigurationProperty tags on each of the properties.
public class WebPageConfiguration : ConfigurationSection
{
public WebPageConfiguration()
{
}
[ConfigurationProperty("headerImageURL", IsRequired = true)]
public string HeaderImageURL
{
get
{
return (string)this["headerImageURL"];
}
set
{
this["headerImageURL"] = value;
}
}
[ConfigurationProperty("footerImageURL")]
public string FooterImageURL
{
get
{
return (string)this["footerImageURL"];
}
set
{
this["footerImageURL"] = value;
}
}
}
Let us now add a definition for our custom configuration section in the web.config file. In case, we wish to new-up an object of the configuration section and then serialize it to the configuration ile we would not need to add this definition. However, for our example since we would be reading a section and THEN changing its properties this definition is required.
<section name="MyWebPageSettings" type="WebPageConfiguration, App_Code" />
Next would be creation of an external config file to which the settings would be serialized. As explained above, using external files leads to better performance if the settings within it are to be changed very frequently. The external file MUST have a root element else the compiler will complain. Even if you wish to new-up an object of the configuration section the external file cannot be empty. Our file called “external.config” would contain the following root element. “MyWebPageSettings” would be the name of our configuration section.
<MyWebPageSettings/>
Finally we’ll add some code to the Button1_Click method associated with the Button on our default.aspx page. This can be done either in the .cs file associated with the .aspx page or the .aspx page itself. The purpose of this method is to take as input the strings entered on the two text boxes on our page and set them as the values of the properties within our configuration section.
First we get a handle to the configuration object and then extract the section named “MyWebPageSettings”. Next we set the properties to some values and save the configuration object. Invoking the Save() method causes the new values to be serialized to file. Notice how the ConfigSoure property is used. Its purpose it to specify the name of the external config file.
Configuration config = WebConfigurationManager.OpenWebConfiguration("/CustomConfigSectionExample");
WebPageConfiguration webPageConfigurationSection =
(WebPageConfiguration)config.GetSection("MyWebPageSettings");
webPageConfigurationSection.HeaderImageURL = TextBox1.Text;
webPageConfigurationSection.FooterImageURL = TextBox2.Text;
webPageConfigurationSection.SectionInformation.ConfigSource = "external.config";
config.Save();
Build and browse the page default.aspx. You should be able to enter strings in the textboxes, push the button and see changes made in the config files.
Let’s first take a look at web.config. You should be able to see the following:
<MyWebPageSettings configSource="external.config" />
This merely tells where the section can actually be found.
The external.config file should be changed to the following:
<MyWebPageSettings headerImageURL="string1" footerImageURL=" string2" />
If you change the values and push the button again you should be able to see the changes immediately without the need for any recompilation.
If you need an overview of the ASP.NET Configuration API http://msdn.microsoft.com is an excellent resource and if you have any specific questions about Configuration please let me know. Hope this information was helpful!
Assad Safiullah
Software Development Engineer in Test
ASP.NET QA Team