How to use appSettings and connectionStrings in C#


For the developers in C# the most useful file is the App.Config or the Web.Config file and the most used settings in appSettings. You can use any name for the configuration file. Even you can use Multiple configuration file in you application.

This configuration file is an XML file havingĀ  .config extension. The .NET Framework provides the System.Configuration.ConfigurationManager.AppSettings namspace which lets you to retrieve appSettings elements from the configuration file. Data is stored in key/value pairs as shown in this sample .config file:

<appSettings>
<add key="ServiceName" value="TestĀ  Service"/>
<add key="ServiceDisplayName" value="Test Display Service"/>
<add key="ServiceDescription" value="Test Description"/>
</appSettings>

Now, to read this appSettings you need to include System.Configuration (2.0) in to your application.

Here is a sample code that reads the required appSettings for your application:

String _serviceName = ConfigurationManager.AppSettings[“ServiceName”].Trim();
String _serviceDisplayName = ConfigurationManager.AppSettings[“ServiceDisplayName”].Trim();
String _serviceDesc = ConfigurationManager.AppSettings[“ServiceDescription”].Trim();

Now, you can use all these 3 variables as you like in your application. You can also use a NULL value check before assignment like this:

String _serviceDesc = (null != ConfigurationManager.AppSettings[“ServiceDescription”].Trim())
? ConfigurationManager.AppSettings[“ServiceDescription”].Trim() : “Default Value”;

The following example code reads all the appSettings from the config file in your application:

    // Get the AppSettings section.        
    // This function uses the AppSettings property
    // to read the appSettings configuration 
    // section.
    public static void ReadAppSettings()
    {
      try
      {
        // Get the AppSettings section.
        NameValueCollection appSettings =
           ConfigurationManager.AppSettings;

        // Get the AppSettings section elements.
        Console.WriteLine();
        Console.WriteLine("Using AppSettings property.");
        Console.WriteLine("Application settings:");

        if (appSettings.Count == 0)
        {
          Console.WriteLine("[ReadAppSettings: {0}]",
          "AppSettings is empty Use GetSection command first.");
        }
        for (int i = 0; i < appSettings.Count; i++)
        {
          Console.WriteLine("#{0} Key: {1} Value: {2}",
            i, appSettings.GetKey(i), appSettings[i]);
        }
      }
      catch (ConfigurationErrorsException e)
      {
        Console.WriteLine("[ReadAppSettings: {0}]",
            e.ToString());
      }
    }

In some cases you might want to save user input to your appSettings. So, you need to create new appSettings Dynamically or Change an existing one. The following code section demonstrates how to create a new appSettings section. I believe the modification part can be done by looking at these 2 examples:

    // Create the AppSettings section.
    // The function uses the GetSection(string)method 
    // to access the configuration section. 
    // It also adds a new element to the section collection.

    public static void CreateAppSettings()
    {
      // Get the application configuration file.
      System.Configuration.Configuration config =
        ConfigurationManager.OpenExeConfiguration(
              ConfigurationUserLevel.None);

      string sectionName = "appSettings";

      // Add an entry to appSettings.
      int appStgCnt =
          ConfigurationManager.AppSettings.Count;
      string newKey = "NewKey" + appStgCnt.ToString();

      string newValue = DateTime.Now.ToLongDateString() +
        " " + DateTime.Now.ToLongTimeString();

      config.AppSettings.Settings.Add(newKey, newValue);

      // Save the configuration file.
      config.Save(ConfigurationSaveMode.Modified);

      // Force a reload of the changed section. This
      // makes the new values available for reading.
      ConfigurationManager.RefreshSection(sectionName);

      // Get the AppSettings section.
      AppSettingsSection appSettingSection =
        (AppSettingsSection)config.GetSection(sectionName);

      Console.WriteLine();
      Console.WriteLine("Using GetSection(string).");
      Console.WriteLine("AppSettings section:");
      Console.WriteLine(
        appSettingSection.SectionInformation.GetRawXml());
    }

ConnectionStrings:

To Read a connectionString from app.config / web.config you can use the following code:

public string GetConnectionString(string str)
{
//variable to hold our return value
string conn = string.Empty;
//check if a value was provided
if (!string.IsNullOrEmpty(str))
{
//name provided so search for that connection
conn = ConfigurationManager.ConnectionStrings[str].ConnectionString;
return conn;
}
//In all other cases return null
return null;
}

This method will return the named connection string. The Key Name needs to be pass to the method as input , else it will return null.

Assuming you have the following in your config file:

<connectionStrings>
<add name=”MyConnString1″ connectionString=”<connection string 1>” providerName=”<provider1>” />
<add name=”MyConnString2″ connectionString=”<connection string 2>” providerName=”<provider2>” />
</connectionStrings>

Here, we have 2 separate connectionStrings. You can have as many as you want. To use it, you just need to call the above method with the name like this:

String _connecitonString = GetConnectionString("MyConnectionString1");

if(null != _connecitonString){
//Your code
//
}

Now if you want to read all Connection Strings then you need to use the following code:

    // Get the ConnectionStrings section.        
    // This function uses the ConnectionStrings 
    // property to read the connectionStrings
    // configuration section.
    public static void ReadConnectionStrings()
    {

      // Get the ConnectionStrings collection.
      ConnectionStringSettingsCollection connections =
          ConfigurationManager.ConnectionStrings;

      if (connections.Count != 0)
      {
        Console.WriteLine();
        Console.WriteLine("Using ConnectionStrings property.");
        Console.WriteLine("Connection strings:");

        // Get the collection elements.
        foreach (ConnectionStringSettings connection in
          connections)
        {
          string name = connection.Name;
          string provider = connection.ProviderName;
          string connectionString = connection.ConnectionString;

          Console.WriteLine("Name:               {0}",
            name);
          Console.WriteLine("Connection string:  {0}",
            connectionString);
         Console.WriteLine("Provider:            {0}",
            provider);
        }
      }
      else
      {
        Console.WriteLine();
        Console.WriteLine("No connection string is defined.");
        Console.WriteLine();
      }
    }

You can read more about appSettings and connectionStrings in MSDN.

Advertisements

How to Get the Time Difference / Total run time of an application in C#


In the practical world of coding you’ll come around a situation when you want to know how long it takes your application to finish. This is very useful to judge the user experience. Depending on the time it takes you can also think of modifying the code to remove extra loops or time consuming methods so that the application can run faster.

Here is how I did it:

First at the beginning of every coding I have instantiated a new Date object:

DateTime _startdt = DateTime.Now;

and at the end of the application I again instantiate another date object:

DateTime _enddt = DateTime.Now;

Now, we can get the difference between them by just using Timespan class:

TimeSpan ts = _enddt – _startdt;

You can now display the difference in human readable format:

Console.WriteLine(“Total Time taken >> ” +
” Day :” + ts.Days +
” Hour(s) :” + ts.Hours +
” Minute(s) :” + ts.Minutes +
” Second(s) : ” + ts.Seconds +
” Milli Second(s) : ” + ts.Milliseconds
);

This is very short but useful trick for us. Hope you’ll like it.