NameValueSectionHandler a handy value parser between config files

I am going to explain a feature that will definitely come in handy in configuration files. Its about the NameValueSectionHandler.

Add the following section to the <configsections> in your web.config file.

<section name=”databaseSettings” type=”System.Configuration.NameValueSectionHandler” />

Now you get your own section with the name of databaseSettings.

   <add key="db.datasource" value="myservername" />
   <add key="db.user" value="root" />
   <add key="db.password" value="******" />
   <add key="db.database" value="Databasename" />

What happen here is making these key value pairs accessible in another config file. Same thing as AppSettings section except that AppSettings are been used in the application code itself, and this databaseSettings section I am going to use in another config file.

I am using springframework, so in my DataAccess layer I have a database-config.xml file, and that is the place where database configuration sections are available. If I had just placed the config values in the xml itself then it would be compiled at the time of deployment, and will not let me update later, unless I do a new release/compiled code.

With the help of above approach, I am able to do as follows,

<db:provider id="DbProvider" provider="MySql.Data.MySqlClient"
 connectionString="server=${db.datasource};User Id=${db.user}; database=${db.database}; password=${db.password}; Persist Security Info=True"/>

Now I have nothing to worry, the db configuration section is in the xml file and values are in the web.config file.

Syntax in accessing the variable is ${ PARAMNAME }


Happy coding!!!