*** When a New Article posted, get Notification to the email that you give below: ***

Monday, July 21, 2014

[ C# ] - App.config file in c# windows application


1. Introduction


Let us say you are developing an Internet modem device monitor utility application. The duty of the application will be monitoring for Upload and download activity of the modem. When there is heavy download say 500KB per second of download for past 10 Minutes, the device should intimate that to a user. The intimation can be done either by blinking a Red LED modem device or by making continues beep or by making the entire desktop with red transparent overlay (System got RED by download J). But, which option the utility should chose from? Now I hear you are saying keep it as an application setting.

In old days, Legacy windows desktop software uses section based Initialization configuration files (INI files) and application reads and writes from it. The settings are placed on sections which are nothing but grouping the settings under certain category. Now in dot net days, the INI files are replaced as application CONFIG files. Application settings are placed in this XML format application configurations files. In this article I will explain how configuration files can be accessed by the application with an example.


2. Configuration File Hierarchy


The configuration file has a hierarchy and the application will search for required settings based on this hierarchy. Have a look at the below picture:



The first thing to be noted is that Web Application looks for settings in the “web.Config” whereas windows desktop application will look for the settings in the “App.Config” file. Let us say a web server machine Johns-Kitten is hosting three web sites and all three web sites are from the same publishers.  Now the settings common to all three web sites goes to “Root.Web.Config” and settings specific to one web site or solution goes to web.config file.

The settings, which are common to both web application and desktop application, can go in “Machine.config” file. The settings defined in the bottom most overrides the settings given in the above level. For example, the setting given in the web.config overrides the settings given in the “Machine.Config” file (i.e.) if same setting is defined in both the machine.config and web.config, web.config setting takes the precedence. In this article we are going to explore how do we use the App.Config file in desktop c# windows applications.


3. About the Example


Have a look at the below application screen shot:


Clicking the “Application Setting” button marked in the picture (as 4), will retrieve the application settings from the App.config file and displays that in the Display Output (Marked as 1).  A key will specify the setting that needs to be retrieved and that key will be entered in the textbox marked as 3. Clicking the button “Get Connection string” (Marked as 2) will retrieve the connection string defined in the app.config file and displays that in the display output. Specifying the name of the connection string will retrieve the connection string.  In our sample, connection string name defined in the App.config file is referred by the checkboxes marked as 5 in the screen shot.

 4. Create the Project


Create a Windows C# application called ReadConStr. Once the exe project is created we can store all the application settings for this ReadConStr.exe into a configuration file called App.Config and read the settings from it through the “system.configuration” assembly. To add this assembly to the ReadConStr ptoject:

1)     Open the Solution Explorer
2)     Right Click the Reference node
3)     Click on the “Add Reference…” menu item from the context menu.

This will display an “Add Reference” dialog. You can pick the System.Configuration assembly from this dialog as shown in the below screen shot. Once you pick the System.Configuration from the add reference dialog, the reference is added to the project and you can examine that by expanding the reference node.


After adding the reference, add the using statement to make use of the application configuration file:

//Sample 01: Required Config Entries
using System.Configuration;


5. Add Appsettings and ConnectionString


OK. Our application is ready to read configuration settings and where is the configuration file? We should add this configuration file to the application.  To add the application configuration file to the project follow the steps listed below:
1) Go to “Solution Explorer”
2) Right click the project name “ReadConStr” and chose “Add=>New Item…”





3) In the “Add New Item” dialog, select the option, “Application Configuration File” and leave the default name “App.Config” as it is. And click on the “Add” button. This will add the application configuration file to your project.


Once the configuration file (App.config) is added to the project, we can place our application wide project settings into this configuration file. To add the application settings, open the app.config file from the solution explorer and add the following code:

The application keeps all the settings inside the AppSettings tags. The setting goes with a key value pairs. For example the application will ask for the setting by providing the key say “Key_4” and gets the corresponding setting value say, Value_5.  Like application settings, Connection string occupies a separate section as shown below:


In the above case, the database connection strings are enclosed between ConnectionStrings tags. The application specifies the “name” and retrieves the connection string and/or provider details. In the above example, by knowing the name “XYZ1”, the application can get connection string “XYZ2” and provider name “XYZ3”. If you are not expertise in connection string, Watch the below video to place connection string in your App.Config file:





6. Reading AppSettings from App.Config


The event handler for the “Application Setting” button is given below:

//Sample 02: Read Application settings
private void btnAppSettings_Click(object sender, EventArgs e)
{
    string setting = ConfigurationManager.AppSettings[txtKey.Text];
    if (setting == null)
        setting = "Setting not found";
    txtDisplayOutput.Text = setting;
}

The ConfigurationManager has the collections AppSettings, ConnectionStrings. In this event handler we refer the AppSettings map and retrieve the required setting value by supplying the key. The key will be specified text box noted as 3 in the application screen shot. The retrieved value is shown in the result display area.


7. Reading ConnectionString from App.Config


Now have a look at the code below, which reads the connection string setting from the App.Config file:

//Sample 03: Read Connection String
private void btnConString_Click(object sender, EventArgs e)
{
    //3.1 Declarations
    ConnectionStringSettings setting_constr = null;
    string con_str = "";

    //3.2 Get Connetion String for Pubs and/or NorthWnd
    if (chkPubs.Checked == true)
    {
        setting_constr = ConfigurationManager.ConnectionStrings["Pubs"];
        con_str = setting_constr.ConnectionString + Environment.NewLine;
    }
    if (chkNWnd.Checked == true)
    {
        setting_constr = ConfigurationManager.ConnectionStrings["NWind"];
        con_str = con_str + setting_constr.ConnectionString;
    }
    if (con_str == "")
        con_str = "Specify either Pubs or NWnd";

    //3.3 Display the output
    txtDisplayOutput.Text = con_str;
}

The above code runs the when the “Get Connection String” button is clicked in the form. Here also we refer the ConnectionStrings map from the ConfigurationManager object to get the corresponding ConnectionStringSettings object. This connection string map requires the name as key. Look at our sample connection strings in the app.config; XYZ1 and abc1 are the name of the connection strings. The actual connection string is then retrieved from this ConnectionStringSettings object. In our example, we assign the ConnectionStringSetting object into setting_constr when the corrospoding checkbox is checked. The “ConnectionString” property from this setting_constr will be referred to get actual connection string text. Once we have connection string setting that will be displayed in the display output.


8. Changing the fore color of display area


Now let us assign the fore color for the output display area. This setting shows a real-time example of how the configuration file will be used to change application behavior without re-compiling it. Have a look at the below code which reads the fore color setting from the configuration file and sets the multi-line textbox accordingly:


//Smaple 4: Applicaion Background Color
private void frmAppConfig_Load(object sender, EventArgs e)
{
    //4.1: Read setting
    string ColorSetting = ConfigurationManager.AppSettings["FontColor"];
    Color ForeColor;

    //4.2 Have a relevent Color
    if (ColorSetting == "Red")
        ForeColor = Color.Red;
    else if (ColorSetting == "Blue")
        ForeColor = Color.Blue;
    else
        ForeColor = Color.Green;

    //4.3 Assign it to the Text Display
    txtDisplayOutput.ForeColor = ForeColor;
}

The above code is written in the form load event handler. The code is similar to what you saw in the section 6, but here we use the application setting to change the behaviour of the textbox. Or simply, the text display color of the textbox will get changed based on the color setting given in the application configuration file.


9. Running the Application – Video


The below given video shows the how the example works with the application configuration file. This video also shows changing the behavior of the textbox just by changing the configuration file.

Video: Running the Application 
Source Code: Download

C++ Articles

DISCLAIMER

The opinions expressed herein are my own personal opinions and do not represent my current or previous employer's view in anyway