Utilizing Config File In C#.NET Application


 Utilizing Config File In C#.NET Application  
 

In a software applications, there are sometimes several values, that need to be changed sometimes, like database connection information, API access credential information, directory path etc. I am talking about both desktop and web applications. In case of C#.NET applications, there are a default XML file for putting such settings values, its web.config for Web application and app.config for desktop applications. If we don’t put those dynamic values here, we would had to compile the applications every time we need to change it!!!!

This is specially a big issue in case of product level developments, which are distributed to customers and each customer sets different values. Although many code can used without compiling like asp.net website or a php web application, but still using hard-coded settings is a terrible things, to other new developers to that application also where he has to find those inside the core code. There are a lot others disadvantages too. Simply, I will strictly recommend to use an external file for storing those app settings(either on a text/xml file, or if even a code file, should be dedicated for configurations settings only).

Microsoft .NET platform provide a very easy and efficient way to manage these application settings. By default a “.config” file is associated with every new desktop/web project. This file is in xml formatting which are serialized/deserialized in c# objects automatically. In this small tutorial, I will try to show you how to use and retrieve these configuration values(on app.config or web.config) from config file in c# code examples. I will use term ‘config file’ to refer to ‘app.confg/web.config’.

Settings Values On Config File In C# Project:

There are generally two kinds of scenario, First, you want to store only a single value for a specific settings. Second, you need a couple of values to set for a specific settings. You should use two different kind of ways to meet these needs.

Single Value Settings:
To store a single value, you should put it inside ‘<appSettings>’ section. Like as follows:

<appSettings>
    <add key="SettingKey1" value="Settings 1 Value"/>
    <add key="SettingKey2" value="Settings 2 Value"/>
</appSettings>

Retrieving these values are pretty straight forward, just use as like following code snippet where you need it:

string value1 =  ConfigurationManager.AppSettings["SettingKey1"];
string value2 =  ConfigurationManager.AppSettings["SettingKey2"];

use should have ‘System.Configuration’ name space in that code file. You can also use ‘WebConfigurationManager’ instead of ‘ConfigurationManager’ with namespace ‘System.Web.Configuration’ in case of asp.net web application.

Multiple Value Settings:
To store more than one values in a specific settings, you should use ‘<configSections>’ section. You will need the following parts implemented:

  • Add a section name and its class name(with name space) in the <sectionConfigs> area in the config file.
  • Add new tag with section name with different attribute names and their values in the config file.
  • Implement a class that extends ConfigurationSettings class.

Here is sample code for the config file:


<configSections>
 <section name="mySettings1" type="myProject.Libraries.MySettings1"/>
<section name="mySettings2" type="myProject.Libraries.MySettings2"/>
 </configSections>

<mySettings1
 key1="Key 1 value"
key2="Key 2 value"
 />
<mySettings2
 key1="Key 1 value"
key2="Key 2 value"
 />

Few things to remember in this stage:

  • Should be at the beginning of all others configurations.
  • Custom tag name must match the name of section

The class file should contain some getter setters , same number of the attribute names for a section, like as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

namespace myMVC.Libraries.FB
{
    public class MySettings : ConfigurationSection
    {
        [ConfigurationProperty("key1", IsRequired = true)]
        public string Key1
        {
            get
            {
                return (string)this["key1"];
            }
        }
    }
}

Now we are all set to use those settings from our application. Just use like following code samples when you want to retrieve those values:

 var settings = ConfigurationManager.GetSection("mySettings");
 MySettings current;
 if (settings != null)
 {
     current = settings as MySettings;
     string valueToUse = current.ApiKey;
//use the value
 }

With this, you can store multiple values for a specific settings in a separate section on the configuration file. And of course, you won’t have to recompile you application while changing these values
as this are being read on run time when needed. So, if you are working on a .NET application, you should definitely always use this configuration file for storing dynamic settings values instead of using
as hard-coded and on any other kind of file like .txt files etc. Happy coding :)

Comments

  1. M.S.Patil says

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.Data.SqlClient;

    public partial class datagrid : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
    //SqlConnection conn = new SqlConnection(“data source=localhost\\sqlexpress;Initial Catalog=patil;Integrated Security=SSPI”);
    string con = ConfigurationManager.ConnectionStrings[“patil”].ConnectionString;
    SqlConnection conn = new SqlConnection(con);
    string sqlsrting = “spr_displaydata”;
    SqlCommand cmd = new SqlCommand(sqlsrting, conn);
    SqlDataAdapter Dataadpt = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    Dataadpt.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();

    }

    }

    WEB.CONFIG File:

Trackbacks

Leave a Reply