How to setup selenium c# web automation project

Recently wen automation is one of popular area and it is good to know about it. Today i am going to show you how to automate testing with Selenium web driver.

What is Selenium?

Selenium automates browsers. That’s it! What you do with that power is entirely up to you. Primarily, it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration tasks can (and should!) also be automated as well.

Selenium has the support of some of the largest browser vendors who have taken (or are taking) steps to make Selenium a native part of their browser. It is also the core technology in countless other browser automation tools, APIs and frameworks.

(Source : http://www.seleniumhq.org/)

I am using visual studio 2013 professional.

Step 01: Setup Unit Testing project

Create unit test project

Step 02: Manager NuGet Packages

  • Selenium WebDriver
  • Selenium WebDriver Support classes
  • Selenium WebDriver Chrome Driver

wen_driver_and_support_classes

Step 03: Let’s add one html file. We can use this file to test. But in real world scenarios, we have to use QA server URL. For demo purpose I will use static html file.

html_file

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1 id="hello">Hello world</h1>
    <input type="button" value="Hello" class="btnHello" onclick="return alert('Hello by button click'); "/>
</body>
</html>

Now we will two methods into out unit testing class.
1. We will click the button
2. We will try to find an element which is not there

Here is out TestClass

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Chrome;
using System.Threading;
using System.IO;
using OpenQA.Selenium;

namespace WebAutomationUnitTest
{
	[TestClass]
	public class UnitTest
	{
		[TestMethod]
		public void TestMethod1()
		{
			using (var driver = new ChromeDriver())
			{
				try
				{
					string curDir = Directory.GetCurrentDirectory();
					driver.Url = new Uri(String.Format("file:///{0}/Index.html", curDir)).ToString();
					driver.Navigate();

                    var element = driver.FindElement(By.ClassName("btnHello"));
                    element.Click();

                    Thread.Sleep(5000);
				}
				catch (Exception)
				{

					throw;
				}

				
			}
		}

        [TestMethod]
        [ExpectedException(typeof(NoSuchElementException))]
        public void TestUndefinedElement()
        {
            using (var driver = new ChromeDriver())
            {
                try
                {
                    string curDir = Directory.GetCurrentDirectory();
                    driver.Url = new Uri(String.Format("file:///{0}/Index.html", curDir)).ToString();
                    driver.Navigate();

                    var element = driver.FindElement(By.ClassName("btnHello_not"));
                    element.Click();

                }
                catch (Exception)
                {

                    throw;
                }


            }
        }
	}
}

And lets run the test cases.

passed

OK. Lets say there is a element which will load by ajax. In that case we have to wait until the element is visible. In this king of scenario you have to use WebDriverWait option.

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("btnDynamic")));
IWebElement element = driver.FindElement(By.Id("btnDynamic"));
element.Click();

You can download the project in here and test

(https://github.com/uwudamith/WebAutomationUnitTest)

Simple json editor using c#

editor

I have created a sample project to read json file, edit and save into another file using c# and Newtonsoft.Json library. If anyone want this kind of implementation, you can download project and continue. I have added the sample json file with the project into my Github repository.

Github repository

I have json file format like below.

{
"tasks": [{
"AccountName": "testaccount",
"AccountKey": "0de5edbc-6a02-4450-a139-33d4e760a257",
"ContainerName": "1234",
"RootPath": "/",
"DaysOfHistoryToKeep": 10
}, {
"AccountName": "test2",
"AccountKey": "f15c414b-734a-4a4e-b1a6-eb0794df4e46",
"ContainerName": "2345",
"RootPath": "/",
"DaysOfHistoryToKeep": 15
}]
}

According to that json structure, i am going to build my object structure like below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JsonEditor
{
    public class Task
    {
        public string AccountName { get; set; }
        public string AccountKey { get; set; }
        public string ContainerName { get; set; }
        public string RootPath { get; set; }
        public int DaysOfHistoryToKeep { get; set; }
    }
}

And I have Tasks class which contains list of Task classes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JsonEditor
{
    public class Tasks
    {
        public List<Task> tasks { get; set; }
    }
}

This is how program going to read the json file and convert into list and bind into grid.

Stream myStream = null;
            OpenFileDialog theDialog = new OpenFileDialog();
            theDialog.Title = "Open Text File";
            theDialog.Filter = "JSON files|*.json";
            theDialog.InitialDirectory = @"C:\";
            if (theDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if (theDialog.FileName.Trim() != string.Empty)
                    {
                        using (StreamReader r = new StreamReader(theDialog.FileName))
                        {
                            string json = r.ReadToEnd();
                            Tasks items = JsonConvert.DeserializeObject(json);
                            dgTasks.DataSource = items.tasks;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }

And convert grid data into json file.

Tasks tasks = new Tasks();
            tasks.tasks = (List)dgTasks.DataSource;
            
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.InitialDirectory = @"C:\";
            saveFileDialog1.Filter = "JSON Image|*.json";
            saveFileDialog1.Title = "Save a JSON File";

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(saveFileDialog1.FileName, JsonConvert.SerializeObject(tasks));
            }

Please download the project and use it in your projects. You have to add exception handling into this project.

How to extend c# ArrayList class

Sometimes we want to extend generic classes in c#. Here i have extended ArrayList in c# and overrided remove functions. I have also added Events to this class and if anyone interested you can go to my GitHub account and check.

Here is the extended class

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AnimalList
{

    // A delegate type for hooking up change notifications.
    //public delegate void MyAnimals_AnimalRemoved(MyAnimalList collection, Animal item);
    public delegate void MyAnimals_AnimalRemoved(object sender, AnimalListEventArgs e);

    /// <summary>
    /// MyAnimalList class only accept Animal types
    /// </summary>
    public class MyAnimalList : ArrayList
    {
        // An event that clients can use to be notified whenever the
        // elements of the list change.
        public event MyAnimals_AnimalRemoved AnimalRemoved;

        // Invoke the Changed event; called whenever list changes
        protected virtual void OnChanged(object sender, AnimalListEventArgs e) 
         {
             if (AnimalRemoved != null)
                 AnimalRemoved(this, e);
         }

         // Override some of the methods that can change the list;
         // invoke event after each
         public void Remove(int value)
         {
             MyAnimalList list = this;
             if (value > list.Count)
             {
                 MessageBox.Show(value+" is not a valid index", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 return;
             }
             AnimalListEventArgs args = new AnimalListEventArgs((Animal)list[value]);
             OnChanged(this, args);
             base.Remove(value);
         }

         // Override some of the methods that can change the list;
         // invoke event after each
         public override void RemoveRange(int from,int to)
         {
             ArrayList list = this.GetRange(from, to);
             foreach(var animal in list)
             {
                 OnChanged(this, new AnimalListEventArgs((Animal)list[list.IndexOf(animal)]));
             }
             base.RemoveRange(from,to);
         }

         // Override some of the methods that can change the list;
         // invoke event after each
         public override void RemoveAt(int value)
         {
             MyAnimalList list = this;
             OnChanged(this, new AnimalListEventArgs((Animal)list[value]));
             base.RemoveAt(value);
         }

        /// <summary>
        /// Override + operator 
        /// </summary>
        /// <param name="list"></param>
        /// <param name="animal"></param>
        /// <returns></returns>
        public static MyAnimalList operator +(MyAnimalList list,Animal animal)
        {
            list.Add(animal);
            return list;
        }

        public new void Add(object value)
        {
            Type t = value.GetType();
            if (t.Equals(typeof(Animal)))
            {
                 base.Add((Animal)value);
            }
            else
            {
                MessageBox.Show("Only Animal type objects can be added to the MyAnimalList collection", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
           
        }
    }
}

And also i have extended EventArgs class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AnimalList
{
   public class AnimalListEventArgs:EventArgs
    {
       private readonly Animal animal;

       public AnimalListEventArgs(Animal animal)
       {
            this.animal = animal;
       }

       public Animal Animal
        {
            get { return this.animal; }
        }
    }
}

Here is my program class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AnimalList
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("||-- Starting animal program -- ||");

            MyAnimalList MyAnimals = new MyAnimalList();
            MyAnimals.AnimalRemoved += new MyAnimals_AnimalRemoved(ListChanged);

            MyAnimals.Add(new Animal(AnimalType.Amphibian, "Frog"));
            MyAnimals.Add(new Animal(AnimalType.Bird, "Eagle"));
            MyAnimals.Add(new Animal(AnimalType.Fish, "Bass"));

            MyAnimals += new Animal(AnimalType.Invertebrate, "Worm");
            MyAnimals += new Animal(AnimalType.Mammal, "Lion");
            MyAnimals += new Animal(AnimalType.Reptile, "Snake");

            MyAnimals.Add("dog");

            MyAnimals.Remove(5);
            MyAnimals.RemoveAt(3);
            MyAnimals.RemoveRange(1, 2);
            MyAnimals.Remove(5);

            foreach (Animal animal in MyAnimals)
            {
                MessageBox.Show("You still have a " + animal.AnimalName + " (" + animal.AnimalType + ")", "CS559 - Assignment 2", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        // This will be called whenever the list changes.
        private static void ListChanged(object sender, AnimalListEventArgs e)
        {
            MessageBox.Show(e.Animal.AnimalName +" was removed from the list.", e.Animal.AnimalType+" Removed", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

How to read excel file using c#

Today I am going to show you how read excel file using c# and create folders based on excel file. Sometimes we may want to create many folders/sub folders based on business requirement and copy files into respective directory. So I am going to show how to do this using c# .net language. For this project i am using

  • Microsoft Visual Studio 2013
  • .net framework 4.5
  • ExcelDataReader library ( You can find it here)
  • Sample excel file which contain sample data set

Here is my project structure.

structure
Project Structure

Sample output

sample_output_parent
Parent folders
sample_output_child
Child folders

I have created sample console application to perform this task. I haven’t add exception handling for this code and feel free to optimize code and use it.

using Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FolderProject
{
    /// <summary>
    /// Author : Damith Wanninayake
    /// Excel 4.5 library url:https://github.com/ExcelDataReader/ExcelDataReader
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            FileStream stream = File.Open(ConfigurationManager.AppSettings["sourceFile"], FileMode.Open, FileAccess.Read);
            string basePath = ConfigurationManager.AppSettings["basePath"];

            // Reading from a OpenXml Excel file (2007 format; *.xlsx)
            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

            // DataSet - Create column names from first row
            excelReader.IsFirstRowAsColumnNames = true;
            DataSet result = excelReader.AsDataSet();

            // Getting distinct values
            var distinctValues = result.Tables[0].AsEnumerable()
                        .Select(row => new
                        {
                            Mem = row.Field<double>("Mem#"),

You can find the completed project which contains excel file in here. Please note that i am not the author of the excel file.

Create Responsive + Bootstrap + SignalR + ASP.NET MVC c# + AngularJS Real time dashboard

Hi all. Let’s create responsive dashboard using
– AngularJS
– Bootstrap
– SignalR
– Highcharts

This sample project based on tons of resources on internet.I have listed few of them below. You can download this project on GitHub (https://github.com/uwudamith/Dashboard). Feel free to download and modify the dashboard project.
Entire prototype has developed using SignalR services. Server will push data into the client without refreshing the browser. That is the beauty of Real Time applications. All charts are based on Highcharts. Layout based on Bootstrap css, so it is responsive by default.

Runtime

ServerPerformance

customer

Charts

SiganalR hub proxy factory

var signalRHubProxy = function ($rootScope, signalRServer) {
    
    function signalRHubProxyFactory(serverUrl, hubName, startOptions) {
        var connection = $.hubConnection(signalRServer);
        var proxy = connection.createHubProxy(hubName);
        connection.start(startOptions).done(function () { });

        return {
            on: function (eventName, callback) {
                proxy.on(eventName, function (result) {
                    $rootScope.$apply(function () {
                        if (callback) {
                            callback(result);
                        }
                    });
                });
            },
            off: function (eventName, callback) {
                proxy.off(eventName, function (result) {
                    $rootScope.$apply(function () {
                        if (callback) {
                            callback(result);
                        }
                    });
                });
            },
            invoke: function (methodName, callback) {
                proxy.invoke(methodName)
                    .done(function (result) {
                        $rootScope.$apply(function () {
                            if (callback) {
                                callback(result);
                            }
                        });
                    });
            },
            connection: connection
        };
    };

    return signalRHubProxyFactory;
};

Calling the factory from angular controller

var serverPerformanceController = function ($scope, signalRHubProxy) {

    $scope.RamCpu = {
        RamUsage: '0',
        CpuUsage: '0',
        Total:'0'
    };

    var clientPushHubProxy = signalRHubProxy(
       signalRHubProxy.defaultServer, 'MyHub',
           { logging: true });

    clientPushHubProxy.on('serverPerformanceDetails', function (data) {
        $scope.RamCpu = data;
        var x = clientPushHubProxy.connection.id;
    });
};

Injecting service into chart controller

// Declare angular application
var dashboardApp = angular.module('dashboardApp', ['ui.bootstrap', 'highcharts-ng']);

// Service declaration
dashboardApp.service('chartdataService', ['$rootScope', '$http', chartdataService]);

// Factory declaration
dashboardApp.factory('signalRHubProxy', ['$rootScope', signalRHubProxy]);

// Controllers declaration
dashboardApp.controller('chartController', ['$scope', '$log', '$timeout', '$interval', 'chartdataService', 'signalRHubProxy', chartController]);

Binding data into html pages

<div class="row" ng-controller="serverPerformanceController">
    <div class="col-md-3">
        <div class="panel panel-warning text-center">
            <div class="panel-body">
                <h1 class="text-info">{{RamCpu.RamUsage}} MB</h1>
            </div>
            <div class="panel-footer panel-info">Available RAM</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="panel panel-warning text-center">
            <div class="panel-body">
                <h1 class="text-info">{{RamCpu.CpuUsage}} %</h1>
            </div>
            <div class="panel-footer panel-info">Total RAM</div>
        </div>
    </div>
</div>

Background timer application

public class BackgroundServerTimeTimer : IRegisteredObject
    {
        private readonly Timer _timer;
        private readonly Timer _timer1;
        private readonly IHubContext _hubContext;

        public BackgroundServerTimeTimer()
        {
            HostingEnvironment.RegisterObject(this);
            _hubContext = GlobalHost.ConnectionManager.GetHubContext();
            _timer = new Timer(OnTimerElapsed, null,TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5));
            _timer1 = new Timer(OnTimerElapsed1, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
        }

        private void OnTimerElapsed(object sender)
        {
            _hubContext.Clients.All.monthlyRainFall(DashboardData.GetChartDataForDashboard());
            _hubContext.Clients.All.customerInformations(DashboardData.GetCustomerInformations());
        }
        private void OnTimerElapsed1(object sender)
        {
            var server = new ServerPerformanceUtility();

           _hubContext.Clients.All.serverPerformanceDetails(server.GetServerPerformance());

        }

        public void Stop(bool immediate)
        {
            _timer.Dispose();
            _timer1.Dispose();
            HostingEnvironment.UnregisterObject(this);
        }
    }

Simple way to understand or explain dependency injection

Recently, I have been trying to learn about anjular.js and mean while i am reading this tutorial (http://learn-angular.org/#!/lessons/a-simple-app) i saw a great answer about describing what is dependency injection. This was the great and simple answer i have ever read. Some one has asked

How to explain dependency injection to a 5-year old?

and simple answer given by John Munsch was

When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn’t want you to have. You might even be looking for something we don’t even have or which has expired.

What you should be doing is stating a need, “I need something to drink with lunch,” and then we will make sure you have something when you sit down to eat.

Wow that is great answer isn’t it?

jsplumb

What is jsPlumb

jsPlumb is a data visualization library available for most popular JavaScript libraries like jQuery, MooTools,Vanilla JS, YUI3. There are lot of features available on jsPlumb and has lots of examples over internet and they have a good documentation.

jsPlumb provides a means for a developer to visually connect elements on their web pages. It uses SVG or Canvas in modern browsers, and VML on IE 8 and below. The latest version is 1.6.4.

 

The project started out life on Google Code and was hosted there up until April 30, 2013. From May 1st, 2013, jsPlumb lives on GitHub only.

 

If you’re new to jsPlumb, please do take the time to read the documentation. There are a few integration issues that you should be aware of: z-index needs special attention, for example.

You can find running demos in here (http://jsplumb.org/demo/home/jquery.html) and licensed under the MIT license.

Browser Compatibility

jsPlumb runs on everything from IE6 up. There are some caveats, though, because of various browser/library bugs:

  • jQuery 1.6.x and 1.7.x have a bug in their SVG implementation for IE9 that causes hover events to not get fired.
  • jQuery 2.0 does not support IE 6,7 or 8.
  • Safari 5.1 has an SVG bug that prevents mouse events from being passed through the transparent area of an SVG element (Safari 6.x does not seem to have the same problem)
  • MooTools has a bug when using SVG in Firefox 11

 

Go ahead and try this awesome library for one of your projects

 

References