Posts Tagged ConfigurationManager

Configuring applications using System.Configuration namespace

Every non trivial application has any kind of configuration. For instance, you might need to store applications state, network settings, database connection string or alternate application behavior in some way. One approach to handle this is to write from scratch your own configuration infrastructure. The other one is to use configuration classes from System.Configuration namespace, which created exactly for this purpose.

The pros for using second approach are obvious:

· Ease of use.

· Allows manipulate configuration data in object oriented way.

· As an official part of .NET framework, this is tested, supported Microsoft code, ready to use. Why waste a time and make your own one??

Beside all these reasons, there is one more: configuration standard. Any Microsoft class which has to be configured, using standard app.config file. Microsoft Enterprise Library uses app.config as well – I will talk about it in my next posts. Therefore, by creating your own configuration files, you risking having “Configuration Hell”. Maintaining number of configuration files is the proven receipt for errors. Even if you have only 10 desktops across a network to install your application on, it is very difficult to configure them all. The task to create configuration application, which will know to handle all your configuration files (each could be in different structure), is nearly impossible. I personally know one guy, whose mission is to create such a configuration utility. The problem is, he need to configure something that has around 20 different configuration files. Each file completely different. He trying to solve this already more than year. Each time that he thinks he done, he receiving changes about configuration files structure and doing all from the beginning again.

Lets talk now about configuration standards. The standard file which used for configuration is “app.config”. After you building your application, it changing its name to “yourAppName.exe.config”. You may have machine.config for all machine, and/or user.config per every user. App.config contains number of predefined sections, and it can contain custom sections as well. There is a partial list of possible predefined sections:

  • You can specify connection strings.
  • Specify which CLR version your app should use.
  • Specify location of assemblies.
  • Configure Remoting (WCF in 3.0).
  • Security and Administration

Some of these settings (such as remoting) can be configured using mscorcfg.msc tool.

Couple examples of app.config files can be found here: http://blogs.msdn.com/suzcook/archive/2004/05/14/132022.aspx

Lets talk now about code. System.Configuration namespace provides everything you might need to configure any average application.

ConfigurationManager class, which is new in framework 2.0, provides all functionality to retrieve, use, modify, validate and store back your custom settings – ready to use out of box. ConfigurationManager retrieves settings in object oriented way, which is very cool. And you can use it, to retrieve any predefined sections, such as connection strings. This mean, you will have only one entry point in code, to handle every kind of configuration: both predefined and custom.

Here are examples which demonstrate retrieving and manipulating predefined sections: connection strings and any application settings:

Note: Don’t forget to reference System.Configuration.dll

 

Example about retrieving configuration string:
http://msdn2.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings(VS.80).aspx

 

Example about retrieving application settings:
http://msdn2.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings(VS.80).aspx

 

But the most interesting part is custom configuration. To illustrate how to do this, I created demo application. It heavy commented, so I will explain here only basic idea:

 

  1. Define configuration object, just how you want it to be.
  2. Derive from ConfigurationSection class, which located in System.Configuration namespace (actually it can derive from ApplicationSettingsBase, but I not covering this here).
  3. For each configuration value, create property and decorate it with ConfigurationProperty attribute. This will connect object’s property to value in configuration file.
  4. Retrieve it using ConfigurationManager class.

 

That’s all. Everything else is already being handled by base ConfigurationSection class. Optional step: in addition, you can decorate object’s property by attributes derived from ConfigurationValidatorBase. Override CanValidate and Validate methods, and you get configuration value validation. Performance considerations: Validate is called in 3 cases:

  1. Creation of configuration object (in case it has default values).
  2. Setting value.
  3. Saving object.

 

In application I prepared, I have object “Profile”. It contains full name, which is First Name and Last Name. In addition it has address, which consists from street name and building number.

 

This is how I define configuration object for full name section (NameSection):

public class NameSection : ConfigurationSection
{
[ConfigurationProperty("LastName", IsRequired = false, DefaultValue = "NotGiven")]
public string LastName
{
get
{
return (string)base["LastName"];
}
set
{
base["LastName"] = value;
}
}

[ConfigurationProperty("FirstName", IsRequired = false, DefaultValue = "NotGiven")]
public string FirstName
{
get
{
return (string)base["FirstName"];
}
set
{
base["FirstName"] = value;
}
}
}

 

In app.config, this will look as the following:

 

<Profile>
<FullName LastName =”NotGiven” FirstName=”NotGiven”/>
</Profile>

 

In case you want change structure of the xml, just override DeserializeSection and SerializeSection methods. In case you want create configuration application to manipulate configuration file – now it is fairy trivial task – just use the same classes.

 

Last words – thread safety: ConfigurationSection class is not thread safe, so you responsible to handle this in your multithreaded application.

Additional information and examples can be found here.

2 comments December 22, 2007


Categories

Top Posts

Tags

.NET addin app.config ArrayList bug CAB Configuration ConfigurationManager ConfigurationSection ContentControl ContextMenu CTime; DateTime custom keys DataBinding DataContext Data templates debugging equals gethashcode GUI Hashtable interlocked Invoke lock lock free memcpy MFC multithreading multithreading; lock free override performance SCSF serialization Smart Client Software Factory Styles System.Configuration unsafe virtual functions Visual Studio wait free WinAPI WinForms WinForms\WPF Integration World of Warcraft World of Warcraft; Addon

Archives