Thursday, May 16, 2013

Using PageObject in Selenium WebDriver C#.Net



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.PageObjects;
using NUnit.Framework;

namespace BusinessCreation
{
     [TestFixture]
    class PayCalculator
    {
        IWebDriver driver;
        SelectElement PayCycleSelect;
        IList<IWebElement> TaxOption;
        IList<IWebElement> TableValList;

        [FindsBy(How = How.Name)]
        private IWebElement income;

        [FindsBy(How = How.Name)]
        private IWebElement paycycle;

        [FindsBy(How = How.XPath,Using="//Div[@class='optionsBlock']")]
        private IWebElement OptionsDiv;

        [FindsBy(How = How.XPath, Using = "//Div[@class='resultContainer']/table[@class='resultTable']/tbody/tr")]
        private IWebElement TableContents;
        public PayCalculator(IWebDriver driver)
        {
            this.driver = driver;
        }
        public void IncomeValue(IWebDriver driver, string strSalary)
        {
            income.Clear();
            income.SendKeys(strSalary);
        }

        public void TermSelection(IWebDriver driver, string strSelectVal)
        {
            PayCycleSelect = new SelectElement(paycycle);
            PayCycleSelect.SelectByValue(strSelectVal);
        }

        public void CalculateOptions(IWebDriver driver, string strTaxOption)
        {
            TaxOption = OptionsDiv.FindElements(By.XPath("//Div[@class='optionsBlock']/fieldset/input[@class='options']"));
            foreach(IWebElement option in TaxOption)
            {
                if (option.GetAttribute("value") == strTaxOption)
                {
                    option.Click();
                }
            }

        }

        public IList<IWebElement> GetTableData()
        {
            TableValList = TableContents.FindElements(By.XPath("//Div[@class='resultContainer']/table[@class='resultTable']/tbody/tr"));
            Console.WriteLine(TableValList.Count);
            IList<IWebElement> TableItems = TableContents.FindElements(By.XPath("//Div[@class='resultContainer']/table[@class='resultTable']/tbody/tr/td"));
            foreach (IWebElement item in TableItems)
            {
                Console.WriteLine("Item: " + item.GetAttribute("id") + " Value: " + item.Text);

            }

            return TableItems;
        }

     
    }
    class Program
    {
        static void Main(string[] args)
        {
            IWebDriver driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://www.paycalculator.com.au/");
            PayCalculator PayCalc = new PayCalculator(driver);
            PageFactory.InitElements(driver,PayCalc);
            PayCalc.IncomeValue(driver, "200000");
            PayCalc.TermSelection(driver, "monthly");
            PayCalc.CalculateOptions(driver, "foreigner");
            PayCalc.GetTableData();
            Console.ReadLine();
        }
    }
}


Monday, April 1, 2013

Method to write test result to Excel c#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
namespace BusinessCreation
{
    class WritingToExcelSheet
    {
        static void Main(string[] args)
        {
            string FileName = @"C:\Users\chery\Desktop\Openings_AU.xlsx";
            string SheetName = "Sheet2";
            WriteExcelValues(FileName,SheetName,"Warning");
            WriteExcelValues(FileName,SheetName,"Fail","Desc1",true);
            WriteExcelValues(FileName,SheetName,"Pass", "Desc2", true);
            WriteExcelValues(FileName,SheetName,"Warning", "Desc3", true);
            WriteExcelValues(FileName,SheetName,"###", "Desc4", true);
            WriteExcelValues(FileName,SheetName,"Warning", "Desc5", true);
            //WriteExcelValues("Fail2", true);
            //WriteExcelValues("Fail3", true);
            //WriteExcelValues("Fail4", true);
            //Console.ReadLine();
        }

        public static void WriteExcelValues(string FileName, string SheetName, string ResultStatus, string ResultVal = "Desc", bool InsertToExstCloumn = false)
        {
            Excel.Application ExcelApp;
            Excel.Workbook WorkBook;
            Excel.Worksheet WorkSheet;
            ExcelApp = new Excel.Application();
            ExcelApp.Visible= true;
            WorkBook = (Excel.Workbook)ExcelApp.Workbooks.Open(FileName);
            WorkSheet = WorkBook.Worksheets[SheetName];
            WorkSheet.UsedRange.Columns.AutoFit();
            //Finding the last used row and column
            Excel.Range last = WorkSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
            Excel.Range range = WorkSheet.get_Range("A1", last);
            int lastUsedRow = last.Row;
            int lastUsedColumn = last.Column;
            if (InsertToExstCloumn == true)
            {
                if (lastUsedColumn == 1 && lastUsedRow==1)
                {
                    WorkSheet.Cells[1, lastUsedColumn].Value = "Result " + 0;
                    WorkSheet.Cells[1, lastUsedColumn].Font.Bold = true;
                    WorkSheet.Cells[1, lastUsedColumn].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
                    WorkSheet.Cells[1, lastUsedColumn].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
                }
                int count = 1;
                for (int i = 1; i <= WorkSheet.UsedRange.Rows.Count; i++)
                {
                    if (WorkSheet.Cells[i, lastUsedColumn].Value != null)
                    {
                        count = count + 1;
                        Console.WriteLine(count);
                    }
                 }
                Console.WriteLine(count);
                if (ResultStatus == "Pass")
                {
                    WorkSheet.Cells[count, lastUsedColumn].Value = "Pass: "+ResultVal;
                    WorkSheet.Cells[count, lastUsedColumn].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen);
                 
                }
                else if (ResultStatus == "Fail")
                {
                    WorkSheet.Cells[count, lastUsedColumn].Value = "Fail: "+ResultVal;
                    WorkSheet.Cells[count, lastUsedColumn].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
                    //WorkSheet.Cells[count, lastUsedColumn].Color = "Red";
                }
                else if (ResultStatus == "Warning")
                {
                    WorkSheet.Cells[count, lastUsedColumn].Value = "Warning: " + ResultVal;
                    WorkSheet.Cells[count, lastUsedColumn].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                    //WorkSheet.Cells[count, lastUsedColumn].Color = "Red";
                }
                else if (ResultStatus == "###")
                {
                    WorkSheet.Cells[count, lastUsedColumn].Value = " " + " ";
                    //WorkSheet.Cells[count, lastUsedColumn].Color = "Red";
                }
             
            }
            else
            {
             
                WorkSheet.Cells[1, lastUsedColumn + 1].Value = "Result " + (lastUsedColumn);
                WorkSheet.Cells[1, lastUsedColumn + 1].Font.Bold=true;
                WorkSheet.Cells[1, lastUsedColumn + 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
                WorkSheet.Cells[1, lastUsedColumn + 1].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
                if (ResultStatus == "Pass")
                {
                    WorkSheet.Cells[2, lastUsedColumn + 1].Value = "Pass: " + ResultVal;
                    WorkSheet.Cells[2, lastUsedColumn + 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen);
                }
                else if (ResultStatus == "Fail")
                {
                    WorkSheet.Cells[2, lastUsedColumn + 1].Value = "Fail: " + ResultVal;
                    WorkSheet.Cells[2, lastUsedColumn + 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
                }
                else if (ResultStatus == "Warning")
                {
                    WorkSheet.Cells[2, lastUsedColumn + 1].Value = "Warning: " + ResultVal;
                    WorkSheet.Cells[2, lastUsedColumn + 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                }
                else if (ResultStatus == "###")
                {
                    WorkSheet.Cells[2, lastUsedColumn + 1].Value = " " + " ";
                    //WorkSheet.Cells[count, lastUsedColumn].Color = "Red";
                }
             
            }
            WorkBook.Save();
            WorkBook.Close();
            ExcelApp.Quit();
        }
    }
}

Method to read data from Excel Sheet in C#.net

In-order to work on excel operations from c# need to add a reference Microsoft.Office.Interop.Excel
and should use the name space reference as using Excel = Microsoft.Office.Interop.Excel

Find below the c# method, ReadExcelValues to read data from an Excel sheet specifying the following inputs,
Inputs
"FileName - name of the file", 
"SheetName - name of the file",
"ColumnNumber - array[] input with column numbers"
"ColumnNumber - array[] input with column numbers,
 "Header - specify if column header value is required in the result"
Return Value
Method returns a two dimensional array with values from excel


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
namespace BusinessCreation
{
    class ReadingFromExcel
    {
        static string[,] ExcelValList;
        static int[] ColumnNames = new int[2];
        static void Main(string[] args)
        {
            string FileName =@"C:\Users\chery\Desktop\Openings_AU.xlsx";
            string SheetName= "Sheet1";
            ColumnNames[0]= 1;
            ColumnNames[1]= 2;
            ExcelValList = ReadExcelValues(FileName, SheetName, ColumnNames,false);
            for (int i = 0; i < ExcelValList.GetLength(0); i++)
            {
                for (int j = 0; j < ExcelValList.GetLength(1); j++)
                {
                    if (ExcelValList[i, j] != null)
                    {
                        Console.WriteLine(ExcelValList[i, j]);
                    }
                    //Console.WriteLine("i :" + (i) + " j: " + (j));
                }
            }
            Console.ReadLine();
        }

        /*Input parameters for ReadExcelValues "FileName - name of the file", "SheetName - name of the file"
        Input parameters for ReadExcelValues "ColumnNumber - array[] input with column numbers"
        Input parameters for  "ColumnNumber - array[] input with column numbers, "Header - specify if column header value is required in the result"
        Return parameter multidimensional string[,] array named - ExcelValueListTemp
         */
        public static string[,] ReadExcelValues(string FileName, string SheetName, int[] ColumnNumber,bool Header)
        {
            Excel.Application ExcelApp;
            Excel.Workbook WorkBook;
            Excel.Worksheet WorkSheet;

            ExcelApp = new Excel.Application();
            ExcelApp.Visible = true;
            WorkBook = ExcelApp.Workbooks.Open(FileName);
            WorkSheet = WorkBook.Worksheets[SheetName];
            string[,] ExcelValueListTemp = new string[WorkSheet.UsedRange.Rows.Count, ColumnNumber.Length];
            for (int j = 1; j <=WorkSheet.UsedRange.Columns.Count; j++)
            {
                for (int i = 1; i <= WorkSheet.UsedRange.Rows.Count; i++)
                {
                    for (int z = 0; z < ColumnNumber.Length; z++)
                    {
                        //Consider only the columns specified in the method input "ColumnNumber - array[] input with column numbers"
                        if (j == ColumnNames[z])
                        {
                            //Flow if method input for Header is true
                            if (Header == true)
                            {
                                string str1 = WorkSheet.Cells[i, ColumnNumber[z]].Value;
                                //Condition to ignore all the null values
                                if (str1 != null)
                                {
                                    //ExcelValueListTemp.Add(ColumnNames[z].ToString() + ";" + str1);
                                    ExcelValueListTemp[i, j] = str1;
                                }
                            }
                            //Flow if method input Header is false
                            else if (Header == false)
                            {
                                if (i > 1)
                                {
                                    string str1 = WorkSheet.Cells[i, ColumnNumber[z]].Value;
                                    //Condition to ignore all the null values
                                    if (str1 != null)
                                    {
                                        ExcelValueListTemp[i - 2, ColumnNumber[z] - 1] = str1;
                                        //Console.WriteLine(ExcelValueListTemp[i - 1, ColumnNames[z] - 1]);
                                        //Console.WriteLine("i-1 :" + (i - 2) + " ColumnNames[z]-1: " + (ColumnNames[z] - 1));
                                    }
                                }
                            }
                        }

                    }
                }

            }
            WorkBook.Save();
            ExcelApp.Quit();
            return ExcelValueListTemp;

        }

    }
}

Monday, March 25, 2013

Handling a Java Script pop up dialog in Selenium WebDriver c#

A modal dialog box can be handled and suppressed by using IAlert class. Follow the code snippet below which closes a Java Script alert displayed.
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.tizag.com/javascriptT/javascriptalert.php");
driver.FindElement(By.XPath("//div/form/input[@value='Confirmation Alert']")).Click();
IAlert alert = driver.SwitchTo().Alert();
Console.WriteLine(alert.Text);
alert.Accept();
The second method to suppress a modal dialog's is to use SendKeys class of name space System.Windows.Forms and send a keyboard  Enter using SendKeys.SendWait("{Enter}")
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.tizag.com/javascriptT/javascriptalert.php");
driver.FindElement(By.XPath("//div/form/input[@value='Confirmation Alert']")).Click();
SendKeys.SendWait("{Enter}");

Sunday, March 24, 2013

Select options in a DropDown List without using "SelectElement" class - Selenium WebDriver C#

Here is an example to better illustrate how to get all the items in a Drop down list and to select an item from the drop down list.
A sample Html code for drop down list
<select>
  <option>Milk</option>
  <option>Coffee</option>
  <option>Tea</option>
</select>
Code below gets all the items from the drop down list above and selects item 'Coffee'.Logic of the code is as follows
Step 1. Create an interface of the web element tag

Step 2. Create an IList with all the child elements of web element tag Step 3. Select the Drop List item "Coffee"
using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;

namespace SeleniumTests
{
    class DropDownListSelection
    {
        static void Main(string[] args)
        {
            IWebDriver driver = new FirefoxDriver(); 
            driver.Navigate().GoToUrl("http://DropDownList.html");
            IWebElement element = driver.FindElement(By.XPath("//Select"));
            IList<IWebElement> AllDropDownList =    element.FindElements(By.XPath("//option"));
            int DpListCount = AllDropDownList.Count;
            for (int i = 0; i < DpListCount; i++)
            {
                if (AllDropDownList[i].Text == "Coffee")
                 {
                    AllDropDownList[i].Click();
                 }
            }
            Console.WriteLine(DpListCount);
            Console.ReadLine();
        }
    }
}

Generating Test Results using Selenium WebDriver C#

Its up to the discretion of the user what to do with the Selenium Webdriver automation and how to report the test results. Selenium Webdriver will give you the power to control your web browser and to automate your web application tests.
Same as how you have to program in any other automation tool the conditions for checking your pass or fail criteria for any tests, in Selenium also it has to be programmed.It is totally up to the programmer how to report their results and the template to be followed. You will have to write your own code to format and store the test results.

Retrieving data from an HTML Table Selenium WebDriver C#

Follow the below C# code to retrieve data from a table. To demonstrate this I have used a table with id="accounts" in "http://developer.yahoo.com/yui/examples/datasource/datasource_table_to_array.html".


<table id="accounts"> 
    <caption>Table in markup with data in it</caption>
    <thead> 
           <tr> 
                <th>Due Date</th> 
                <th>Account Number</th> 
                <th>Quantity</th> 
                <th>Amount Due</th> 
           </tr> 
    </thead> 
    <tbody> 
           <tr> 
                <td>1/23/1999</td> 
                <td>29e8548592d8c82</td> 
                <td>12</td> 
                <td>$150.00</td> 
           </tr> 
           <tr> 
                <td>5/19/1999</td> 
                <td>83849</td> 
                <td>8</td> 
                <td>$60.00</td> 
           </tr> 
            ... 
   </tbody> 
</table> 
Details of the code.
  1. Created a Web Element for of the By.XPath("//table[@id='accounts']/thead/tr")
  2. Created an IList with collection of all the tag web elements under the /thead/trBy.XPath("//table[@id='accounts']/thead/tr/th")
  3. Access the contents of the table head using a loop.
  4. Created a Web Element for of the By.XPath("//table[@id='accounts']/tbody/tr")
  5. Created a IList with collection of all the tag web elements under the /tbody/tr By.XPath("//table[@id='accounts']/tbody/tr/th")
  6. Access the contents of the table body using a loop.
-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;

namespace BusinessCreation
{
    class ExtractDataFromATable
    {
        static void Main(string[] args)
        {
            IWebDriver driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://developer.yahoo.com/yui/examples/datasource/datasource_table_to_array.html");
          if(driver.FindElement(By.XPath("//table[@id='accounts']/thead/tr/th")).Displayed)
            {
                IWebElement webElementHead =  driver.FindElement(By.XPath("//table[@id='accounts']/thead/tr"));
                IList<IWebElement> ElementCollectionHead = webElementHead.FindElements(By.XPath("//table[@id='accounts']/thead/tr/th"));
                foreach (IWebElement item in ElementCollectionHead)
                {
                    Console.WriteLine(item.Text);
                }
            }
            if (driver.FindElement(By.XPath("//table[@id='accounts']/tbody/tr")).Displayed)
            {
                IWebElement webElementBody = driver.FindElement(By.XPath("//table[@id='accounts']/tbody/tr"));
                IList<IWebElement> ElementCollectionBody = webElementBody.FindElements(By.XPath("//table[@id='accounts']/tbody/tr"));
                foreach (IWebElement item in ElementCollectionBody)
                {
                    string []arr= new string[4];
                    arr = item.Text.Split(' ');
                    for (int i = 0; i < arr.Length; i++)
                    {
                        Console.WriteLine(arr[i]);
                    }               
                }
            }
            Console.ReadLine();
        }
    }
}