Welcome Guest Donate | Search | Active Topics | Members | Log In | Register

How to programmatically access, modify, and save the configuration of an .NET application? Options
lingy
Posted: Thursday, July 29, 2010 10:00:31 AM

Rank: Administration
Groups: Administration , Member

Joined: 5/8/2009
Posts: 1,576
Points: 5,631

Since .NET Framework 2.0, a set of new and enhanced configuration APIs have been shipped into the .NET Framework, these APIs let you programmatically access, modify, and save the configuration of an application using minimal code.

This topic explores these APIs by providing examples on how to use them in your .NET applications.

Sponsor
Posted: Thursday, July 29, 2010 10:00:31 AM


lingy
Posted: Thursday, July 29, 2010 10:06:40 AM

Rank: Administration
Groups: Administration , Member

Joined: 5/8/2009
Posts: 1,576
Points: 5,631

ConfigurationManager Class

The ConfigurationManager class provides seamless programmatic access to configuration files and configuration sections. Using the methods and properties of this class, you can open configuration files and retrieve configuration sections from within your application.

The ConfigurationMangager class's major functionality falls into three categories.

  1. Quick access to the appSettings and connectionStrings sections of the current application's default configuration file, which you access through properties such as AppSettings and ConnectionStrings.
  2. Access to a specific configuration section from the current application's default configuration file, using methods such as:
    •  GetSection
    • GetWebAppSection, and
    • RefreshSection.
  3. The ability to open different types of configuration files such as <AppName>.exe.config, machine.config, and web.config so you can update them programmatically through methods such as:
    •  OpenMachineConfiguration
    • OpenMappedMachineConfiguration
    • OpenExeConfiguration
    • OpenMappedExeConfiguration
    • OpenWebConfiguration, and
    •  OpenMappedWebConfiguration
lingy
Posted: Thursday, July 29, 2010 11:15:51 AM

Rank: Administration
Groups: Administration , Member

Joined: 5/8/2009
Posts: 1,576
Points: 5,631

Retrieving Connection Strings in the Application Configuration File

One of the most common questions ASP.NET developers have is how and where to store connection strings.
Since .NET Framework 2.0, a new configuration section called <connectionStrings> is introducted into the application configuration file which lets you store connection strings securely in a .NET application.

The following code shows you how to read the connection strings that is stored inside the <connectionStrings> section in an app.config file. First, you need to prepare your app.config file:

<connectionStrings>
    <add name="DataAccessQuickStart" providerName="System.Data.SqlClient"
              connectionString="server=(local);database=EntLibQuickStarts;Integrated Security=true" />
</connectionStrings>

The following code retrieves all connection strings from the app.config file using the ConnectionStrings property of the ConfigurationManager class.

using System.Configuration;

class Program
{
    static void Main()
    {
        GetConnectionStrings();
        Console.ReadLine();
    }
    static void GetConnectionStrings()
    {
        ConnectionStringSettingsCollection settings =
            ConfigurationManager.ConnectionStrings;

        if (settings != null)
        {
            foreach(ConnectionStringSettings cs in settings)
            {
                Console.WriteLine(cs.Name);
                Console.WriteLine(cs.ProviderName);
                Console.WriteLine(cs.ConnectionString);
            }
        }
    }
}
lingy
Posted: Thursday, July 29, 2010 11:17:27 AM

Rank: Administration
Groups: Administration , Member

Joined: 5/8/2009
Posts: 1,576
Points: 5,631

Creating a generic ConfigurationElementCollection class in C#

There is no generic version of the ConfigurationElementCollection in the .NET Framework. When you want to a ConfigurationElementCollection instance to hold your ConfigurationElement-derived objects, the typical solution is to write your own collection class named XXXConfigurationElementCollection, inheriting from ConfigurationElementCollection, and ensuring your XXX object inherits from ConfigurationElement, that means if you have a lot customized ConfigurationElement elements, you have to write a lot of corresponding collection classes.

Since the the generics support in .NET Framework 2.0, there is a easy way to do this: Instead of writting a lot of corresponding collection classes, you can create a generic ConfigurationElementCollection class. The following code demonstrates how to do this in C#:

//The ConfigurationElementCollection<T> provides a simple generic implementation of 
//ConfigurationElementCollection.
public class ConfigurationElementCollection<T> : ConfigurationElementCollection, IEnumerable<T>
 where T : ConfigurationElement, new()
{
 public void ForEach(Action<T> action)
 {
  for (int index = 0; index < Count ; index++)
  {
   action(Get(index));
  }
 }

 public T Get(int index)
 {
  return (T)base.BaseGet(index);  } 
 
 public void Add(T element)
 {
  BaseAdd(element, true);
 }
 public T Get(string key)
 {
        return BaseGet(key) as T;
 } 

    public bool Contains(string key)
 {
        return BaseGet(key) != null;
 }
    public void Remove(string key)
 {
        BaseRemove(key);
 }

 public void Clear()
 {
  BaseClear();
 }
 public new IEnumerator<T> GetEnumerator()
 {
  return new GenericEnumeratorWrapper<T>(base.GetEnumerator());
 }

 protected override ConfigurationElement CreateNewElement()
 {
  return new T();
 }
 protected override object GetElementKey(ConfigurationElement element)
 {
        return ((T)(element)).ToString();
 }
}

When you want a collection of your ConfigurationElement-derived objects, you can use the above generic class like this:

[ConfigurationProperty(_tableTaskSortOrdersProperty)]
public ConfigurationElementCollection<TableTaskSortOrderElement> SortOrderElements
{
    get
    {
        return (ConfigurationElementCollection<TableTaskSortOrderElement>)this[_sortOrdersProperty];
    }
}

Note: You must override the ToString() method of your custom ConfigurationElement class to return a unique value. The generic ConfigurationElementCollection uses the ToString() method to obtain a unique key for each element in the collection.

public class TableTaskSortOrderElement : ConfigurationElement
{

    private const string _positionProperty = "position";
    private const string _columnNameProperty = "columnName";
    private const string _directionProperty = "direction";
    [ConfigurationProperty(_positionProperty, IsRequired = true)]
    public string Position
    {
        get
        {
            return (string)this[_positionProperty];
        }
        set
        {
            this[_positionProperty] = value;
        }
    }

    [ConfigurationProperty(_columnNameProperty, IsRequired = true)]
    public string ColumnName
    {
        get
        {
            return (string)this[_columnNameProperty];
        }
        set
        {
            this[_columnNameProperty] = value;
        }
    }
    [ConfigurationProperty(_directionProperty, IsRequired = true)]
    public string Direction
    {
        get
        {
            return (string)this[_directionProperty];
        }
        set
        {
            this[_directionProperty] = value;
        }
    }

    public override string ToString()
    {
        return this.Position;
    }
}

 

lingy
Posted: Monday, August 02, 2010 11:36:58 PM

Rank: Administration
Groups: Administration , Member

Joined: 5/8/2009
Posts: 1,576
Points: 5,631

Getting Application Configuration File in C#

The following example demonstrates how to use the ConfigurationFile property in the AppDomainSetup class to get the path and name of the configuration file for a C# application.

using System;
using System.Reflection;

class MyDomain
{
  public static void Main()
  {
     Console.WriteLine("Application base is: ", newDomain.SetupInformation.ApplicationBase);
     Console.WriteLine("Configuration file is: ", newDomain.SetupInformation.ConfigurationFile);

     Console.WriteLine("Application name is: ", newDomain.SetupInformation.ApplicationName);
  }

}
lingy
Posted: Monday, August 02, 2010 11:43:14 PM

Rank: Administration
Groups: Administration , Member

Joined: 5/8/2009
Posts: 1,576
Points: 5,631

How to Read and Write Configuraiton Data in App.config and Web.config Without Using Enterprise Library?

Since .NET Framework 2.0, the new added class ConfigurationManager in System.Configuration namespace can be used to read and write configuraiton information in App.config and Web.config without using the complicated Enterprise Library Configuration Block in your application.

The ConfigurationManager class allows you to access machine(machine.config), application(app.config, web.config), and user configuration information. This class replaces the ConfigurationSettings class, which is deprecated.

If your application needs read-only access to its own configuration, it is recommended that you use of the GetSection method. This method provides access to the cached configuration values for the current application, which has better performance than the Configuration class. To write to the configuration files, use one of the Save methods.

The following code demonstrates how to use ConfigurationManager to read and writing configuration data from App.config in C#.

//App.config

<configuration>
  <configSections>
    <section name="EditorSettings" type="TestApp.EditorFontData, TestApp, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null" />
  </configSections>
  <EditorSettings name="Verdana" size="24" style="2" />
</configuration>

 

//EditorFontData.cs

 public class EditorFontData : ConfigurationSection
 {  

  public EditorFontData()
  {         
  }

    [ConfigurationProperty("name")]
  public string Name
  {
      get { return (string)this["name"]; }
   set{ this["name"] = value; }
  }

    [ConfigurationProperty("size")]
  public float Size
  {
   get{ return (float)this["size"]; }
   set{ this["size"] = value; }
  }

    [ConfigurationProperty("style")]
  public int Style
  {
      get { return (int)this["style"]; }
   set{ this["style"] = value; }
  }

  // ....
 }

 

 

Reading configuratiopn data from App.config

 using System.Configuration;

...

private void readConfigDataButton_Click(object sender, System.EventArgs e)
{
  EditorFontData configData = ConfigurationManager.GetSection("EditorSettings") as EditorFontData;
  ....
 
}

Writing configuratiopn data to App.config

 using System.Configuration;

...

private void writeConfigDataButton_Click(object sender, System.EventArgs e)
{
  EditorFontData configData = new EditorFontData();

  if (fontDialog.ShowDialog() == DialogResult.OK)
  {
    configData.Name = fontDialog.Font.Name;
    configData.Size = fontDialog.Font.Size;
    configData.Style = Convert.ToInt32(fontDialog.Font.Style);

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    config.Sections.Remove("EditorSettings");
    config.Sections.Add("EditorSettings", configData);
    config.Save();
 
    ....

  }
}

Users browsing this topic
Guest


Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.


© 2010 Canaware Solutions. All rights reserved.
Powered by Canaware Forum version 2.4