Enterprise Library – Configuration Application Block – Patterns and Practices

Armed with our knowledge of XML Serialization, we can certainly start creating a solution for accessing and persisting global settings in our ASP.NET application.  However, we may want to back up a bit and look at the Configuration Application Block created by the Microsoft Patterns and Practices Group.  Even if we decide not to use the application block, we certainly want to at least understand how it works so we can justify our decision to our boss or client – but even more important, the guys at the next .NET Pub Club or Code Brew meeting!


After reading the documentation, one essentially runs the Enterprise Library Configuration Application to help create the configuration information that needs to be placed in the application’s config file.


 


Configuration Application Block


 


Notice that the application block comes with an XML File Storage Provider and an XML Serializer Transformer.  Heck, this sounds like XML Serialization to me, so learning it was time well spent.


After making the configurations and saving the results, we end up getting two files: configtest.config (with the configuration information) and a blank sitesettings.config file.  The configuration information looks like this:


 


Configuration Settings
<configuration>
<configSections>
<section name=enterpriselibrary.configurationSettings
type
=Microsoft.Practices.EnterpriseLibrary.Configuration.
ConfigurationManagerSectionHandler,
Microsoft.Practices.EnterpriseLibrary.Configuration, Version
=1.0.0.0,
Culture
=neutral,
PublicKeyToken
=null />
</configSections>
<enterpriselibrary.configurationSettings
xmlns:xsd
=http://www.w3.org/2001/XMLSchema
xmlns:xsi
=http://www.w3.org/2001/XMLSchema-instance
applicationName
=configtest
xmlns
=http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/configuration>
<configurationSections>
<configurationSection name=SiteSettings encrypt=false>
<storageProvider xsi:type=XmlFileStorageProviderData
name
=XML File Storage Provider
path
=sitesettings.config />
<dataTransformer xsi:type=XmlSerializerTransformerData
name
=Xml Serializer Transformer>
<includeTypes />
</dataTransformer>
</configurationSection>
</configurationSections>
<keyAlgorithmStorageProvider xsi:nil=true />
<includeTypes />
</enterpriselibrary.configurationSettings>
</configuration>

 


I copy over a couple of the Configuration Application Block DLL’s as shown above and run Snippet Compiler to test it out. Here is the code:


 


Using the Configuration Application Block
using System;
using Microsoft.Practices.EnterpriseLibrary.Configuration;

public class SiteSettings
{
#region Private Members

private string _name;
private string _url;
private string _emailAddress;

#endregion

#region Properties

public string Name
{
get { return _name; }
set { _name = value; }
}

public string Url
{
get { return _url; }
set { _url = value; }
}

public string EmailAddress
{
get { return _emailAddress; }
set { _emailAddress = value; }
}

#endregion
}

public class TestClass
{
public static void Main()
{
SiteSettings siteSettings
= new SiteSettings();

siteSettings.Name = DavidHayden.com;
siteSettings.Url
= http://www.davidhayden.com/;
siteSettings.EmailAddress
= nospam@nospam.com;

ConfigurationManager.WriteConfiguration(SiteSettings, siteSettings);

SiteSettings mySettings = ConfigurationManager.GetConfiguration(SiteSettings) as SiteSettings;

if (mySettings != null)
{
Console.WriteLine(
Name = {0}, mySettings.Name);
Console.WriteLine(
Url = {0}, mySettings.Url);
Console.WriteLine(
Email Address = {0}, mySettings.EmailAddress);
Console.ReadLine();
}
}
}


 


Here is the now populated sitesettings.config file with the global application settings:


 


Global Application Configuration Settings
<?xml version=1.0 encoding=utf-8?>
<SiteSettings>
<xmlSerializerSection type=SiteSettings, configtest,
Version=0.0.0.0, Culture=neutral, PublicKeyToken=null>
<SiteSettings xmlns:xsd=http://www.w3.org/2001/XMLSchema
xmlns:xsi
=http://www.w3.org/2001/XMLSchema-instance>
<Name>DavidHayden.com</Name>
<Url>http://www.davidhayden.com/</Url>
<EmailAddress>nospam@nospam.com</EmailAddress>
</SiteSettings>
</xmlSerializerSection>
</SiteSettings>

 


This looks like the same output as the previous XML Serialization Example.  Man, this is sweet!  Not only are the results basically the same, but I have totally abstracted the storage of the global application settings so that I could change it in the future.  Notice that all my references to anything concerning XML are gone.  I like this better.  Besides, anytime you can use the word “Enterprise” in a sentence has got to be worth something :)

This entry was posted in Application Blocks. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

7 Responses to Enterprise Library – Configuration Application Block – Patterns and Practices

  1. Val says:

    There is also restriction that different sections should be placed in different storage locations, because section name is used as a tag name for the top

    element. At least this is so in current version implementation (Jan 2005).

  2. Marsha says:

    If the configuration section – i.e. SiteSettings encrypt property is set to encrypt=true in EL Configuration Console will the storage provider file be encrypted? When "SiteSettings" encrypt is set to true, I keep getting System.Security.Cryptography.CryptographicException: Length of the data to decrypt is invalid error even though the File Key Algorithm Storage Provider is configured. And the .config file is not encrypted. Thanks.

  3. David Hayden says:

    Hi Nate,

    The only "gotcha" about web.config is that changing it causes a restart of the application. You really don’t want global settings in web.config that change often and don’t require an application restart. If you are essentially adding settings to web.config that rarely or never change, that is fine. Volatile settings should be tossed in an XML file or database, depending on your application needs.

    The application block is cool, but could be overkill for smaller applications. I tend to use separate XML files and my own serialization which I showed in a separate post. You can add the global settings to the cache with a dependency on the XML file to remove it from the cache when a change is detected. This is part of my web page inheritance model that I will toss up sometime this weekend I hope. It is pretty basic and gives you another option for your web applications.

  4. Nate says:

    First, thanks for the great stuff every day David.

    Would you use this method for setting storage in an ASP.NET application over the web.config file? If so, why? Advantages/disadvantages?

  5. David Hayden says:

    You’re absolutely right, Sam. If you plan on always persisting your objects to XML, then certainly the Configuration Application Block is overkill and we can build a similar solution that requires less configuration settings and can output less XML.

    The application block provides a bit more functionality, however, than what I have mentioned. The "Encrypt" attribute is necessary, because you can actually specify and create your own encryption algorithms. I assume they would need this attribute to know when to encrypt and decrypt the information.

    The application block also allows you to create and specify other storage providers and data transformers. It happens to come with XML-based solutions now, but you can certainly roll your own solutions to work with a database, etc. The hope is that others will also roll their own solutions and we could share efforts. The code in your application would stay the same and all you would do is make modifications to the config file specifying the new storage providers and data transformers.

    The application block will also fire off events if changes occur to the underlying storage provider so you can reload any changes in your application.

    Then you have the warm-and-fuzzy benefits that may or may not interest some people. Such as the fact that the solution is community supported and thus will have bug fixes and come out with new enhancements as time goes on (we hope!). From an employer’s perspective, it also makes it easier to swap out developers and contract out work if code isn’t so much developer or company specific, but more standard in nature.

    All-in-all, however, your comments are valid. Sometimes these application blocks can be overkill and if one has a good solution already in-house, this may not be the way to go. However, for those people who don’t have a solution and can’t or don’t have time to write a solution themselves, it took me all of about 30 minutes to get this running.

  6. Sam says:

    Ok, that was kinda a crappy comment, but I was leaving work. :)

    What don’t I like about this? Well, it really has nothing to do with configuration, so I think the name is misleading. Serialization can get ugly pretty fast for configuration files though. No defaults. Look at the encrypt attribute for example. Why does that even need to be there?

    Instead you could write an XmlActivator that takes in an XmlDocument and returns you an instance based on Type specified in the document. Basically your document would look pretty much like sitesettings.config, except with the root tag have the type attribute. Then you can get rid of the xmlSerializerSection and SiteSettings sub elements. Like so: (here’s hopin’ this works)

    &lt;SiteSettings type="SiteSettings, configtest"&gt;

    &lt;Name&gt;DavidHayden.com&lt;/Name&gt;

    &lt;Url&gt;http://www.davidhayden.com/&lt;/Url&gt;

    &lt;EmailAddress&gt;nospam@nospam.com&lt;/EmailAddress&gt;

    &lt;/SiteSettings&gt;

    &lt;/code&gt;&lt;/pre&gt;

    You pass this into your XmlActivator, it parses it out (in a version a friend recently wrote you could also specify the Type for each parameter, or it would default to string if the attribute was not present though this could also be inferred from the parameter Type through reflection), and uses System.Activator to give you an instance.

    This doesn’t do the same thing though you might say. You’re right. If you want to be able to specify a different xmldocument through app.config, you’re also going to need to write a configurationSectionHandler. There lots of examples on the web, and it’s actually a whole lot easier than I thought before I wrote one, so don’t worry, if I can do it anyone can. :) Instead of all that nasty markup though, you only need your section element specifying the handler to use, and the element named in the section element. That element only needs to contain two attributes: A name for the instance, and the path to the xmldocument. Sure you could add encryption and all that, but I’d recommend you do it manually. Parsing Xml is actually really easy, and it lets you do things like default to no encryption if the attribute is missing.

    With this sort of design, for the same example, your xml files would be half the size, and you’d get the same functionality and more.

    The config app block could allow other stuff I’m not seeing here, so this is just based on what I see. I’m not familiar with it personally. But from the example it looks like the hard way to do it.

    That’s my 2c anyways. :)

  7. Sam says:

    Wow that’s ugly. :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>