4 minute read

When you write a .NET application, to manage configuration settings is often required. These configuration settings can have a "user" or "application" scope.

User settings can be different for each user will use the application, instead application parameter is fixed and defined for the entire machine.

Visual Studio 2005 (and 2008 as well) allows, adding a "settings" item to the solution/project to manage easily this kind of settings.

To create a settings item you can use the context menu on a project and select "new item"->"Settings File".

Visual Studio generates a class derived from System.Configuration.ApplicationSettingsBase, and a "app.config" file that contains an XML where you can find default values for all settings you'll define.

As shown below, from Visual Studio, is trivial add a setting using the visual interface:

image

In this case I added an "Age" setting of integer type with default value of 35.

Each time I add a setting, Visual Studio does 2 operations:

(1) it modifies *.designer.cs file related to my settings adding:

 1: [global::System.Configuration.UserScopedSettingAttribute()] 
 2: [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 
 3: [global::System.Configuration.DefaultSettingValueAttribute("35")] 
 4: public int Age { 
 5:  get { 
 6:  return ((int)(this["Age"])); 
 7:  } 
 8:  set { 
 9:  this["Age"] = value; 
 10:  } 
 11:  }

(2) It modifies app.config file adding:

 1: <ConsoleApplication1.NicolSettings> 
 2:  <setting name="Age" serializeAs="String"> 
 3:   <value>35</value> 
 4:  </setting> 
 5: </ConsoleApplication1.NicolSettings> 

As you can seem the default value (35) is present in both class and .config files. Is this redundant? No! infact in this way the .exe or the .dll generated file already contains his default settings and can word without the external (global) configuration file.

This means that:

  • If I run the application without the corresponding .config file in his directory, the settings class will use the default setting provided inside the code
  • If I run the application with the .config file present in his directory, the application will use the value provided in the XML

So the usefullnes of .config file is clear where there is the requirement to override one of default value hard-coded in the application with a new applicatin wide setting.

Technorati Tag: ,