Enroll in Selenium Training

In this chapter, we will learn about Configurations and see How to Manage and Read Configuration File in C# using ConfigurationManager. Before that let's just understand what do we meant by Configuration and why any framework should have a nice Configuration Management System. In any Automation testing project or any development project, there are numerous applications or environment Urls, DataBase Connections, Folder Paths & other Environmental Properties. All these data can be called as Project Configurations.

Manage And Read Configurations using ConfigurationManager in C#

I can cover this topic very quickly with providing the code but I thought it might be helpful to others if I provided a good details on Configurations. As I've been working with .NET configuration files for a year now, I understand that sometimes it becomes very annoying due to unmanaged configurations.

We always use Urls, DB Connection String & Folder paths in any automation project. But when we design Frameworks, we should set the these data for once and use it many time. Whenever there is a situation to change in configurations just need to change the main configuration at one place.

Let's take an example of the current scenario of what we are automating. In the test script of the last chapter,  the Url of the application was hard coded in the test script. Suppose there are many test scripts and now the Url of the application is supposed to change from test environment to staging environment. All the test scripts need to updated before running the test. But if the Url is store in the configuration file, there will be just one change in config file. This is why it is very necessary to understand How to Manage and Read Configuration File in C# using ConfigurationManager.

There are different ways to maintain the Configuration file, I will be discussing a few of them but the important one. It will be up to the project need that which way should be followed:

  1. Read Configuration using ConnectionStrings from App.Config
  2. Read Configuration using AppSettings from App.Config
  3. Read Configuration from External Config file

ConfigurationManager Class

ConfigurationManager is the class which helps to read data from configurations. Provides access to configuration files for client applications.

Namespace: System.Configuration

To use the ConfigurationManager class, your project must reference the System.Configuration assembly. By default, some project templates, like Console Application, do not reference this assembly so you must manually reference it.

using System.Configuration;

This class provides two properties:

  • AppSettings: Gets the AppSettingsSection data for the current application's default configuration.
  • ConnectionSettings: Gets the ConnectionStringsSection data for the current application's default configuration.

Location of the Config File

In the project explorer at the right side, notice the file App.config. open this file, this is the default configuration settings file of your project. Any new settings should go in this.

How to Read Connection String in C# using ConfigurationManager

Connection strings can be stored as key/value pairs in the connectionStrings section of the configuration element of an application configuration file. Child elements include add, clear, and remove.

Lets just see that how to read the DataBase String from the configuration file. The following configuration file fragment demonstrates the schema and syntax for storing a connection string. The name attribute is a name that you provide to uniquely identify a connection string so that it can be retrieved at run time. The connectionString is the database string with username and password.

App.config File

<configuration>
		<connectionStrings>
				<add name="DBConnection" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;Pooling=False"/>
		</connectionStrings>
</configuration>

The code in c# to read the config strings will be like this:

var dbString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;

This is how we read data from the Config file using ConnnectionString. But is that looks OK to you? Does it look nice to store application Url in the COnnectionString. Because connectionString is basically meant to store DataBase connection strings. Let see how to use config file for storing application Urls and Folder paths efficiently.

How to Read AppSettings in C# using ConfigurationManager

This is a little different from what we have learned above. appSettings attribute is used to store the data in the Key/Value pair.

App.config File

<configuration>
    <appSettings>
          <add key="URL" value="https://www.store.demoqa.com"/>
		  <add key="FolderPath"="C:\Users\lakshay.sharma\Downloads\"/>
    </appSettings>
</configuration>

To read the Url from the above config file, use the below code:

var url = ConfigurationManager.AppSettings["URL"];

var folderPath = ConfigurationManager.AppSettings["FolderPath"];

NOte: Folderpath could be any path which is needed in the framework, for example path to save the reports or the screenshot.

How to Read Configurations from External Config file in C# using ConfigurationManager

Think of a situation where a project have many Urls, ConnectionStrings & Filepaths. It can be very messy to put all the settings under just one file. ConfigurationManager class gives us the capability to create another config file of the project and separate project settings. Let's say you want to keep all the DB Connections in the separate file.

Steps to read ConnectionString from External Config File using ConfigurationManager

App.config File

	  <configuration>
			<connectionStrings configSource="DBConnectionStrings.config" />
	  </configuration>

Create another config file and name it DBConnectionString.config under the same project.

DBConnectionString.config File

<connectionStrings>
		<add name="DataBaseName" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;Pooling=False/>
</connectionStrings>

To read the connection string from the above config file, use the below code:

var connString= ConfigurationManager.ConnectionStrings["DataBaseName"].ConnectionString;

Steps to read AppSettings from External Config File using ConfigurationManager

App.config File

<configuration>
		<appSettings configSource="Configurations\Environment.config" />
</configuration>

Create another config file and name it Environment.config under the same project.

Environment.config File

<appSettings>
		<add key="URL" value="https://www.store.demoqa.com"/>
</appSettings>

To read the connection string from the above config file, use the below code:

***var url = ConfigurationManager.AppSettings["URL"]; ***

Implement Configurations in Automation Framework

My favourite way of managing Framework configuration is through External files only. So that I can have separate DBConnections file, Environment Urls file or any other sort of environmental properties file. Let's just see how the Framework will look after implementing ConfigurationManager.

Add Reference to ConfigurationManager

Right Click on the References and select Add Reference... Now search for System.ConfigurationManager. Select it and this will add to your Project References.

Manage And Read Configurations using ConfigurationManager in C#

Create Configuration Folder

Right click on the project and create one new folder. Name it as Configurations.

Create Environment Config file

In the configurations folder, create one config file and name it as Environment.config. Paste the below code in the Environment file.

<appSettings>
		<add key="URL" value="https://www.store.demoqa.com"/>
</appSettings>

Modify App.config File

<configuration>
               <appSettings configSource="Configurations\Environment.config" />
</configuration>

Note: Please remove any extra character at the top from both the config file like <?xml version="1.0" encoding="utf-8" ?>

Modify LogInTest Script

LogInTest.cs Test Case

using NUnit.Framework;
using OnlineStore.PageObjects;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System.Configuration;

namespace OnlineStore.TestCases
{
    class LogInTest
    {
        [Test]
        public void Test() {

            IWebDriver driver = new FirefoxDriver();
            driver.Url = ConfigurationManager.AppSettings["URL"];     

            var homePage = new HomePage(driver);
            homePage.ClickOnMyAccount();

            var loginPage = new LoginPage(driver);
            loginPage.LoginToApplication();

            driver.Close();
        }    
    }
}

There are no changes in the LogInPage & HomePage classes, those will remain same, please take the reference of those two classes from the previous chapter. Try running your test. This time the application URL will fetch from Configuration file.

Project Solution Explorer

ConfigurationManager_3

Error: Unable to Open configSource File ‘Configurations/Environment.config’

In case you get error like this:

System.Configuration.ConfigurationErrorsException: Unable to Open configSource File ‘Configurations/Environment.config’

I suspected that the configuration file was not being copied to the output debug/release folder and so could not be found when running the application. By viewing the properties of a Environment file in Visual Studio there is a property called Copy to Output Directory that can be used to copy the configuration file automatically: Change it to Copy Always.

ConfigurationManager_2

Try running the test again, I am sure it will run this time.

Encapsulate Selenium Page Objects
Encapsulate Selenium Page Objects
Previous Article
Data Driven Testing
Data Driven Testing
Next Article
Lakshay Sharma
I’M LAKSHAY SHARMA AND I’M A FULL-STACK TEST AUTOMATION ENGINEER. Have passed 16 years playing with automation in mammoth projects like O2 (UK), Sprint (US), TD Bank (CA), Canadian Tire (CA), NHS (UK) & ASOS(UK). Currently, I am working with RABO Bank as a Chapter Lead QA. I am passionate about designing Automation Frameworks that follow OOPS concepts and Design patterns.
Reviewers
Virender Singh's Photo
Virender Singh

Similar Articles

Feedback