Understanding App.config and using Configuration Manager: GetSection vs. ConnectionString

419 Views Asked by At

For some context, I want to open a connection to a database and execute some queries.

Here's my App.config:

    <dbservers>
        <connectionStrings>
            <add name="Cube_ConnectionString" connectionString="OLEDB; Datasource=http://cube.com; Initial Catalog=BP" />
        </connectionStrings>
        <queries>
            <add connectionStringName="CubeConnectionString" usedBy="DataAccessor" connectionString="" />
        </queries>
    </dbservers>

This is how I intend to retrieve the connectionString:

    System.Configuration.ConfigurationManager.ConnectionStrings["Cube_ConnectionString"].ConnectionString;

I am wondering whether GetSection or ConnectionString would be best to use. And what would be returned for both of them? How do these two methods function within nested XML such as this?

Additionally, what's the purpose of putting queries in the app.config?

Thanks in advance

1

There are 1 best solutions below

3
On BEST ANSWER

I don't think that ConnectionStrings will work unless you put them in the standard section for those. If you want a custom <dbservers> section, you'll have to use GetSection instead.

This functionality is a bit awkward, but highly useful. How to: Create Custom Configuration Sections Using ConfigurationSection is a useful guide for this.

Essentially this boils down to creating a class that inherits from ConfigurationSection, and adding the proper attributes (from the above guide):

public class PageAppearanceSection : ConfigurationSection
{
    // Create a "remoteOnly" attribute.
    [ConfigurationProperty("remoteOnly", DefaultValue = "false", IsRequired = false)]
    public Boolean RemoteOnly
    {
        get
        { 
            return (Boolean)this["remoteOnly"]; 
        }
        set
        { 
            this["remoteOnly"] = value; 
        }
    }

    // Create a "font" element.
    [ConfigurationProperty("font")]
    public FontElement Font
    {
        get
        { 
            return (FontElement)this["font"]; }
        set
        { this["font"] = value; }
    }

    // Create a "color element."
    [ConfigurationProperty("color")]
    public ColorElement Color
    {
        get
        {
            return (ColorElement)this["color"];
        }
        set
        { this["color"] = value; }
    }
}

...and then adding a reference to your section in the app/web.config:

<configuration>
  <configSections>
    <section name="dbservers" type="Namespace.DbServersSection, YourAssembly"/>
  </configSections>
</configuration>