Windows UI Automation


Windows UI Automation Tutorial


Windows provides a programmatic interface to automate various elements.
Windows Automation saves time and effort in executing regression test cases.

Let us start with an example to automate calculator perform a simple operation of  2+5

  • Step 1:Open Visual Studio and create a new console application
  • Step 2:Navigate Tools>NuGet Package Manger>Manage Nuget Packages for solution... and click on it
  • Step 3:In the search bar find system.windows.automation and add UIaComWrapper to current solution












  • Step 4:  Add "using System.Windows.Automation;" namespace
  • Step 5:Now open calculator
  • Step 6:In visual studio navigate to TOOLS>SPY ++(x64)
  • Step 7:In the Microsoft Spy++ pop up window click on Find window
  • Step 8:Now drop the pointer to 2 in calculator  and click on ok





















  • Step 9:Now in the Inspect window click on properties.

  • Step 10:In the properties note down the control id value and convert it into decimal


                     
In this case on conerting 84(HEX) TO DECIMAL we get 132


  • Step 11:Repeat from steps 7 to 10 to find control id value for digit "5" "=" and "+" respectively

Final Program


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Automation;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using System.IO; 
 namespace Windows_UI 
{
  class Program { static void Main(string[] args) 
    { Program automate = new Program(); 
      //Calls automate function 
        automate.Func();
    } 
 public void Func() 
  { 
     AutomationElement _calculatorAutomationElement, r2, rplus, r5, requal;
      Process _calculatorProcess; 

     //Opens Calculator 
   _ calculatorProcess = Process.Start(@"calc.exe");

    int ct = 0;

    do 
      {
         //Finds if automation element is available 
         _calculatorAutomationElement = AutomationElement.RootElement.FindFirst              (TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Calculator"));                   ++ct;

           Thread.Sleep(100); 
      } 
    while (_calculatorAutomationElement == null && ct < 50); 

      //Finds the digit 2 through automation ID 
      r2 =_calculatorAutomationElement.FindFirst(TreeScope.Descendants,newPropertyCondition (AutomationElement.AutomationIdProperty, "132")); 




      //Presses the digit 2 GetInvokePattern(r2).
       Invoke(); Thread.Sleep(100);

      //Finds the digit + through automation ID
        rplus = _calculatorAutomationElement.FindFirst (TreeScope.Descendants,newPropertyCondition (AutomationElement.AutomationIdProperty, "93"));


         //Presses the digit + 
          GetInvokePattern(rplus).Invoke(); 
          Thread.Sleep(100); 

      //Finds the digit 5 through automation ID 

          r5=_calculatorAutomationElement.FindFirst(TreeScope.Descendants,newPropertyCondition (AutomationElement.AutomationIdProperty, "135")); 


      //Presses the digit 5
       GetInvokePattern(r5).Invoke();
       Thread.Sleep(100);
      
      //Finds the equal operation through automation ID 
         requal = _calculatorAutomationElement.FindFirst(TreeScope.Descendants,newPropertyCondition (AutomationElement.AutomationIdProperty, "121")); 


      //Presses the equal symbol 
      GetInvokePattern(requal).Invoke(); 
       Thread.Sleep(100); 

    } 

    //This function clicks the automation element InvokePattern                                      GetInvokePattern(AutomationElement element)

          { 
            return element.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
          } 
    }

 }

HOME


Automation Tutorial















Selenium automates web browsers.
To begin tutorial click on the button.












Automate the boring day to day windows tasks.
To learn about Windows UI Automation click on the button.















Automate various tasks on many Virtual Machines simultaneously.
To learn about VM Workstation automation click on the button.












To learn about essential C# tricks needed for automation click on the button

Vmware Automation


VMware Automation




Vmware provides inbuilt support to automate various operations on a virtual machine such as taking snapshot,starting VM,Running program in VM and so on. The vmrun command is used to control Virtual machines. It provides support both to WorkStation and VSphere client.

 This tutorial is dedicated to control Virtual Machines only on WorkStation.


Getting started with VMRUN command


  • Pre-Requistes:
    • .Have a workstation installed on your host machine
    • Install any Virtual machine of your choice in the WorkStation
    • Locate the path of vmrun.exe file.
      • 32 Bit Machine -The default location is C:\Program Files \VMware\VMware VIX
      • 64 bit machine -The default location is C:\Program Files (x86)\VMware\VMware VIX
    • Locate path of .vmx or .vmtm file
      • The default path is C:\Documents and Settings\<username>\My Documents\My Virtual Machines\Windows 8X62\Windows 8x64.vmx
  • Steps 1: In the host machine where workstation is installed open command prompt in administrator mode.

  • Step 2: Navigate and open vmrun.exe.     
           In this case it is located in C:\Program Files (x86)\VMware\VMware VIX
  • Step 3:Now type vmrun in the command prompt.
            If successful you should get a list of Vmrun commands.



Vmrun Commands:

The commonly used commands are shown below:






Example:To perform the following tasks:

  1.          Start VM with a known username and password
  2.          Run calculator program in VM
  3.          Take snapshot of the VM



  •     The below command starts the vm where username is "gpb" and password is "a"
    •  vmrun  -gu gpb -gp a start "C:\Users\gpb\Documents\Virtual               Machines\Windows 8 x64(2)\Windows 8 x64 (2).vmx"
  •      The below command runs calaculator program
    •  vmrun  -gu gpb -gp a runprograminguest "C:\Users\gpb\Documents\Virtual Machines\Windows 8 x64 (2)\Windows 8 x64 (2).vmx" -nowait -interactive "C:\Windows\system32\calc.exe"

  •     The following command takes a snapshot with snapshot name as demo
    •     vmrun snapshot "C:\Users\gpb\Documents\Virtual Machines\Windows 8 x64 (2)\Windows 8 x64 (2).vmx"  demo



To run all these commands together we can store these commands in a batch file and execute the corresponding batch script.


To learn about creating batch files click on next tutorial!

Basics of BATCH File

Basics of BATCH(.BAT) File













Introduction

A batch file is a script file in windows.
It is a plane text file which contains series of commands which needs to be executed by command line interpreter.
Batch files have .bat as extension.


Steps to create a batch file:

Step 1:Create a new text document
Step 2:Rename the file as per your choice and in the extension replace ".txt" by ".bat"
Step 3:Now Right click on the bat file and click on edit
Step 4:Type commands which needs to be executed and save the file.



Basic Commands:

  • cls -This command is used to clear the screen
  • ECHO - This command is used to display output to screen
    • The other variants of ECHO are:
                1.ECHO OFF- Doesnt display DOS commnads on the screen
                2.ECHO ON- Displays DOS commands on the screen
  • .Timeout seconds-It waits for specified amount of time(Seconds) before executing next command.User can skip the timer by pressing any key
  • .Pause - Pauses the running of a batch file and displays the message "Press any key to continue ..." on the screen
    •  The other variants of Pause commands are:
               1.pause {Displays "Press any key to continue ...".}

       2.pause < nul {Waits with no comment.}

               3.pause Do you want to continue? {Displays "Do you want to continue?" with                     "Press any key to continue ..." on the next line.}.
  • SET- Set will view the DOS environment or create, change, or delete environment values.
         

Generate Random Number in C#


Generate Random number in C#



C# provides random class which is defined in System.random namespace which is used to generate random numbers.


 Methods

  1.  Next()- Returns a random non negative integer value.
  2.  Next(int minvalue,int maxvalue)- Returns a random number between the specified range.         Exclusive of the maxvalue 
  3.  NextBytes()- Fills the array of specified array of bytes with random numbers.
  4.  NextDouble()- Returns a random number between 0.0 to 1.0

Example

 Random number =new Random(); 

 //To generate random integer 
 int any_integer =number.Next();


 //Generate random integer from 1-12 
 int mont=number.Next(1,13);


 //Generate a random double number between 0.0 to 1.0 
 double numb =number.NextDouble(); 


  //Generate random numbers in specified array
              Byte[] b = new Byte[10];
              number.NextBytes(b);

            //Print the array
                for(int m=0;m<10;m++)

                Console.Write(b[m]+"\t");



Generate GUID number

GUID represents a globally unique identifier. It is used to create a unique key.
Syntax: Guid.NewGuid();
Example:
string key = Guid.NewGuid().ToString(); Console.WriteLine(key);



Click on the button to learn about bat file

Click on this Image to begin Selenium Tutorial
Click on this Image to begin Windows UI Automation tutorial
Click on this Image to begin VMWorkStation tutorial
Click on this Image to see cool c# tricks

Inspect Elements in Selenium


Inspect Elements in Selenium



WebElement represents an HTML element.
HTML elements are written with a start tag, with an end tag, with the content in between:
 < tagname > content < /tagname >


Browser tools for inspecting web elements:

  • Firefox browser:To inspect an element in firefox browser either right click on the desired element and select inspect  element(Q) or Press F12 and drop cursor to the desired element.
  • Chrome Browser:To inspect an element in chrome browser either right click on the desired element and select inspect  or Press F12 and drop cursor to the desired element.
  • Internet Explorer:To inspect an element in IE browser either right click on the desired element and select inspect or Press F12 and go to DOM Explorer tab to inspect an element.

Example: Let us learn to inspect elements in www.google.com using FireFox web browser.

Step 1: Open firefox browser
Step 2: Go to www.google.com
Step 3: Now press F12 function key.
Step 4: To inspect an element click on the cursor in the emulator tab and drop it to the desired element of choice. In this case we drop in google search bar as shown below



































Step 7:  A block of code gets highlighted as shown in the figure.Now identify  elements such as ID,CLASS,CLASSNAME,TAGNAME in the block

Step 8: Copy the value of the available element and use it in your code.
         
Example:In this case we get the value of ID as "gs_htif0"
//Find search bar and send "Hey"
IWebElement search = chrome.FindElement(By.Id("gs_htif0"));
 search.SendKeys("hey");



In our next tutorial let us learn to find Xpath of a webelement using FireBug and FirePath.

Contents

WebElements in Selenium


WebElements in Selenium


Selenium provides IWebElement interface through which user controls the elements in the page.

The IWebElement type exposes the following members:

  • Displayed - Gets a value whether or not this element is displayed.
  • EnabledGets a value indicating whether or not this element is enabled.
  • Location - Gets a point object containing the coordinates of the upper-left corner of this element relative to the upper-left corner of the page.     
  • Selected - Gets a value indicating whether or not this element is selected.
  • Size - Gets a Size object containing the height and width of this element.
  • TagName - Gets the tag name of this element. 
  • Text - Gets the inner Text of this element, without any leading or trailing whitespace, and with other white space collapsed.

The Methods available are as follows

  1.  Clear- Clears the content of this element.
  2.  Click- Clicks this element.       
  3.  FindElement- Finds the first IWebElement using the given method.
  4.  FindElements- Finds all the  IWebElement within the current context using the given                                         mechanism
  5.  GetAttribute- Gets the value of the specified attribute for this element.           
  6.  GetCssValue- Gets the value of a CSS property of this element.
  7.  SendKeys -  Simulates typing text into the element.      
  8.  Submit  - Submits this element to the web server.            

findElement method of WebDriver returns WebElement.
 The findElement() method accepts something as a Parameter/Argument and which is By Object. By is the mechanism used to locate elements within a document with the help of locator value.


Locating Element using By Strategy
Locating elements in WebDriver is done by using the findElement(By.locator()) method.
 The findElement methods take a locator or query object called ‘By’.
"BY" strategies in c# are listed below:

  1. By ID
    • id(String id) : By – This is the most efficient and preferred way to locate an element, as most of the times IDs are unique.
    •  It takes a parameter of String which is a Value of ID attribute and it returns a BY object to findElement() method.
    • With this strategy, If no element has a matching id attribute, a NoSuchElementException will be raised.
    • Command – driver.findElement(By.id(“Element ID”));
    • Example: WebElement element = driver.findElement(By.id("submit"));
  2. By Name
    • name(String name) : By – This is also an efficient way to locate an element but again the problem is same as with ID that UI developer make it having non-unique names on a page or auto-generating the names. 
    • It takes a parameter of String which is a Value of NAME attribute and it returns a BY object to findElement() method.
    • With this strategy, the first element with the name attribute value matching the location will be returned. If no element has a matching name attribute, a NoSuchElementException will be raised.
    • Command – driver.findElement(By.name(“Element NAME”));
    • Example:WebElement element = driver.findElement(By.name("firstname"));
  3. By ClassName
    • className(String className) : By – This finds elements based on the value of the CLASS attribute. It takes a parameter of String which is a Value of CLASS attribute and it returns a BY object to findElement() method.
    • If an element has many classes then this will match against each of them.
    • Example: WebElement parentElement = driver.findElement(By.className("button"))
  4. By TagName
    • tagName(String name) : By – With this you can find elements by their TAGNAMES. It takes a parameter of String which is a Value of TAG attribute and it returns a BY object to findElement() method.
    • Command – driver.findElement(By.tagName(“Element TAGNAME”));
    • Example: WebElement element = driver.findElement(By.tagName("button"));
  5.  By LinkText & PartialLinkText
    • linkText(String linkText) : By – With this you can find elements of “a” tags(Link) with the link names. Use this when you know link text used within an anchor tag. It takes a parameter of String which is a Value of LINKTEXT attribute and it returns a BY object to findElement() method.
    • Command – driver.findElement(By.linkText(“Element LINKTEXT”));

      Command – driver.findElement(By.partialLinkText(“Element LINKTEXT”));
  6. By XPath
    • xpath(String xpathexpression) : By – It is most popular and majorly used locating element technique or the easiest way to locate element in WebDriver. It takes a parameter of String which is a XPATHEXPRESSION and it returns a BY object to findElement() method.
    • Command-driver.findElement(By.xpath(“Element XPATHEXPRESSION”));
    • Example:driver.findElement(By.xpath(“.//*[@id='Email']”));

SendKeys
  • The send Keys method is used to send keystrokes to web elements such as textbox,password box etc.
  • Syntax: element.SendKeys(String text);
  • Example:element.SendKeys("abc");



Program: Login to Facebook account with email as"abc@mail.com" and password as "junk"

using OpenQA.Selenium; 
using OpenQA.Selenium.Chrome; 
using OpenQA.Selenium.Support.UI;
 using System;
 namespace hello_world
 {
    class Program 
     { 
         static void Main(string[] args)
           { //open facebook page
              IWebDriver driver = new ChromeDriver();  
              driver.Navigate().GoToUrl("https://www.facebook.com/"); 
              
              //Find email field and send abc@mail.com      
              IWebElement email = driver.FindElement(By.Id("email"));
              email.SendKeys("abc@mail.com");                                                            

              //Find password field and send junk
              IWebElement pass = driver.FindElement(By.Id("pass"));
              pass.SendKeys("junk"); 

              //Click on Login button
              IWebElement submit_btn = driver.FindElement(By.Id("u_0_l"));
              submit_btn.Click(); 
           }
     }
 }

In our next tutorial let us learn about Implicit and Explicit wait methods in selenium!

Read data from Excel sheet for WebDriver


Read data from excel sheet to use it in webDriver


During testing we often need to execute the same Test cases with different Test Data.
The Test Data can be obtained from various sources such as text file,excel file and so on.
In this tutorial we will learn to extract(read) data from an excel sheet and use it in our webdriver.

Example:Let us login to facebook account by reading Email and Password present in the excel sheet.


Step 1:Go to "c:\temp" folder and create a new Microsoft excel worksheet with name as "demo.xlsx"



























Step 2 :Open "demo.xlsx" spreadsheet and enter Email and password as shown below








Step 3:Open Visual Studio and click on Tools>NuGet Package Manger>Manage Nuget Packages for solution...

Step 4:In the search bar search "Excel" and download and install Microsoft.Office.Interop.Excel into the current solution.
























Step 5: In the namespace section add

               using excel = Microsoft.Office.Interop.Excel;

Step 6: Add the below code snippet
             
                //Creates a new instance of Excel
Excel.Application xlApp = new Excel.Application();
         //Opens demo.xlsx
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Temp\demo.xlsx");
         //Selects the first Sheet
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
        //Finds the range of cells used in the sheet
Excel.Range xlRange = xlWorksheet.UsedRange;



Step 7: To get the data in a specified cell  use xlRange.Cells[i, j].value2;
            where i and j being row and column index.

Step 8: Store the value obtained  from cell as a string             

                            String email, pass;
                 //get userid in first cell
                email = xlRange.Cells[1, 1].value2;
                 //get password in present cell
                pass= xlRange.Cells[1, 2].value2;

Step 9: Use the obtained data in Selenium WebDriver.



Complete program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing; using OpenQA.Selenium; // This is Selenium namespace using OpenQA.Selenium.Chrome;//Use this namespace when you are automating in google chrome using System.Threading; 
using OpenQA.Selenium.Support.UI; 
using Excel=Microsoft.Office.Interop.Excel;

 namespace First_Program
  { 
    class Program
    { 
      static void Main(string[] args)
       { // Create a new excel application instance 
         Excel.Application xlApp = new Excel.Application();
        //Open demo sheet 
         
       Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\temp\demo.xlsx");   
        //select the first sheet in demo.xlsx 
        Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];

        //Find the range of cells used 
         Excel.Range xlRange = xlWorksheet.UsedRange; 

          string email, pass; 
         //get userid in first cell email = xlRange.Cells[1, 1].value2; 
          //get password in present cell pass= xlRange.Cells[1, 2].value2; 

           IWebDriver driver = new ChromeDriver(); 
           driver.Navigate().GoToUrl("https://www.facebook.com");
                    driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMilliseconds(10000)); 

                    driver.FindElement(By.Id("email")).SendKeys(email);            
                   driver.FindElement(By.Id("pass")).SendKeys(pass);            
                   driver.FindElement(By.Name("u_0_l")).Click();
                   Thread.Sleep(1000);
              }
    }

 }

Implicit and Explicit Wait in Selenium



Implicit and Explicit wait in Selenium



We often get openQA.Selenium.NoSuchElementException when we are trying to perform an action on html elements before they are even loaded.
To avoid this exception selenium provides two type of wait methods:-
1.Implicit Wait
2.Explicit wait


Implicit wait
An implicit wait is used to tell the WebDriver to wait for a certain amount of time when trying to find an element or elements if they are not available.
The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.


Example:To wait for implicitly for 5 seconds before we click on "Sign in" button in "www.google.com"

IWebDriver chrome = new ChromeDriver(); //Opens chrome browser                    
chrome.Navigate().GoToUrl("https://google.com");//Opens www.google.com


//waits for 5 seconds until "Sign in" button is available          

chrome.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));

 //Finds "Sign in" button
 IWebElement sign_btn = chrome.FindElement(By.Id("gb_70"));
   

 //Clicks on "Sign in" Button       
 sign_btn.Click();


Explicit wait
An explicit wait is code you define to wait for a certain condition to occur before proceeding further in the code.
The worst case of this is thread.sleep(), which sets the condition to an exact time period to wait.


Syntax:Thread.sleep(int milli_sec);


In our Next tutorial let us learn about select class in Selenium


Finding Xpath using FireBug and FirePath


Find Xpath using FireBug and FirePath



To find Xpath let us follow the below steps:
  • Step 1: Open Mozilla FireFox Browser
  • Step 2: Download and Install FIREBUG  and restart the browser
  • Step 3:Download and Install FIREPATH  and restart the browser
  • Step 4:Now click on firebug icon in the command tool bar as shown in the below figure


















  • Step 5:In the firebug pop up screen click on "firepath" as shown in the below figure

























  • Step 6:To find Xpath click on the cursor icon and place it on the desired element in the page.




















  • Step 7: Finally use the XPATH obtained in your code.


In our next tutorial let us learn about WebElements in detail!

Select Class in Selenium


Select Class in Selenium



Selenium supports “Select” class, which provides useful methods for interacting with select options. User can perform operations on a select drop-down and also de-select operation using the below methods.

Note: Add using OpenQA.Selenium.Support.UI; in namespace Section

SelectByIndex 
Syntax: select.selectByIndex(Index);
Purpose:  To Select the option based on the index given by the user.
There is an attribute called "values" which will have the index values.

SelectByValue
Syntax: select.selectByValue(Value);
Purpose:  To Select the options that have a value matching with the given argument by the user.

SelectByText
Syntax: select.selectByText(Text);
Purpose: To Select all options that display text matching the given argument.
It will not look for any index or value, it will try to match the VisibleText (which will display in dropdown)

deselectByIndex  
Syntax: select.deselectByIndex(Index);
Purpose: To Deselect the option at the given index. The user has to provide the value of index.

 deselectByValue  
Syntax: select.deselectByValue(Value);
Purpose: To Deselect all options that have a value matching the given argument.

 deselectByVisibleText  
Syntax: select.deselectByVisibleText(Text);
Purpose: To Deselect all options that display text matching the given argument.

deselectAll
Syntax: select.deselectAll();
Purpose: To Clear all selected entries.
This works only when the SELECT supports multiple selections.
It throws NotImplemented eError if the "SELECT" does not support multiple selections. In select it mandatory to have an attribute multiple="multiple"


Example:To select (day,month,year) in birthday field in "WWW.FACEBOOK.COM"


IWebDriver chrome = new ChromeDriver(); //Open chrome browser chrome.Navigate().GoToUrl("https://facebook.com"); //open facebook website
 //wait until elements are available 
chrome.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));

//To select date AND SELECTBYVALUE
 var day = chrome.FindElement(By.Id("day"));
 var select_day = new SelectElement(day); 
 select_day.SelectByValue("2"); 


 //To select month by SELECTBYTEXT
 var month = chrome.FindElement(By.Id("month")); 
 var select_month = new SelectElement(month); 
 select_month.SelectByText("Oct");


 //To select year by SELECTBYINDEX
 var year = chrome.FindElement(By.Id("year"));
 var select_year = new SelectElement(year); 
 select_year.SelectByIndex(5);


In our next tutorial let us learn about cookies!


Cookies in Selenium


Cookies in Selenium


An HTTP cookie is a small piece of data sent from a website and stored in the user's web browser while the user is browsing.
Cookies were designed to record the user's browsing activity.

The following Cookie methods are widely used in selenium:

Add Cookie
Method Name: addCookie(Cookie cookie)
Syntax: driver.Manage().Cookies.addCookie(arg0);
Purpose: To add a specific cookie into cookies. If the cookie's domain name is left blank, it is assumed that the cookie is meant for the domain of the current document.
Parameters: cookie - The name of the cookie to add.

Delete Cookie
Method Name: deleteCookie(Cookie cookie)
Syntax: driver.manage()Cookies.deleteCookie(arg0);
Purpose: Delete a cookie from the browser's "cookie jar". The domain of the cookie will be ignored.
Parameter: Cookie

Delete Cookie with Name
Method Name: deleteCookieNamed(java.lang.String name)
Syntax: driver.manage().Cookies.deleteCookieNamed(arg0);
Purpose: Delete the named cookie from the current domain. This is equivalent to setting the named cookie's expiry date to sometime in the past.
Parameters: name - The name of the cookie to delete

Delete All Cookies
Method Name: deleteAllCookies()
Syntax: driver.manage().Cookies.deleteAllCookies();
Purpose: It will delete all the cookies for the current domain.
Parameters: N/A

Get Cookies
Method Name: getCookies()
Syntax: driver.manage().Cookies.getCookies();
Purpose: Get all the cookies for the current domain..
Returns: A Set of cookies for the current domain.

Get the Cookie with Specific Name
Method Name: getCookieNamed(java.lang.String name)
Syntax: driver.manage().Cookies.getCookieNamed(arg0);
Purpose: To Get a cookie with a given name.
Parameters: name - the name of the cookie
Returns: It will return the cookie value for the name specified, or null if no cookie found with the given name


In our Next Tutorial let us learn to capture screenshot in selenium!

Capture Screenshot In Selenium

Capture Screenshot in Selenium


During our day to day testing we often need to capture screenshots for reporting purposes. Selenium provides an interface named as ITakesScreenshot which takes screenshot of the webDriver.

Syntax: ((ITakesScreenshot)driver).GetScreenshot();

Program: To capture screenshot of www.facebook.com and save the image as "FB.PNG" in "c:\Temp folder".

using System; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Drawing.Imaging; //Used to save image
namespace hello_world
{
  class Program
   {
     static void Main(string[] args)
      {
        //Creates an instance of chrome browser
        IWebDriver chrome = new ChromeDriver();

        //Opens facebook webpage
        chrome.Navigate().GoToUrl("https://www.facebook.com");


        //Takes screenshot
        Screenshot ss = ((ITakesScreenshot)chrome).GetScreenshot();


        //saves in c:\Temp as FB.PNG
        ss.SaveAsFile(@"C:\TEMP\FB.PNG", ImageFormat.Png);
      }
      }
}



Result
FB.PNG Image stored in c:\Temp






























The captured image can also be stored in different format such as JPEG,BMP,GIF and so on.
Example:To store as FB.JPEG all you need to do is change the extension of file to "FB.JPEG" and use ImageFormat.jpeg
 ss.SaveAsFile(@"C:\TEMP\FB.JPEG", ImageFormat.Jpeg));


In our next tutorial let us learn to read data from EXCEL sheet and use it selenium webdriver!


Browser Navigation in Selenium


Browser Navigation in selenium


Let us look at the most important navigation commands which are frequently used while testing:

  1. Navigate GoToUrl Command
      • GoToUrl(String arg0) : void –  This method Loads a new web page in the current browser window. It accepts a String parameter and returns nothing.
      • Command  – driver.navigate().to(webpageurl);
      • Example –  driver.navigate().to("http://www.google.com");
  2. Forward Command
      • forward() : void – This method does the same operation as clicking on the Forward Button of any browser. It neither accepts nor returns anything
      • Command – driver.navigate().forward();
      • Example  – driver.navigate().forward();
  3. Back Command
      • back() : void – This method does the same operation as clicking on the Back Button of any browser. It neither accepts nor returns anything.
      • Command – driver.navigate().back();
      • Example  – driver.navigate().back(); 
  4. Refresh Command
      • refresh() : void – This method Refresh the current page. It neither accepts nor returns anything.
      • Command – driver.navigate().refresh();
      • Example  –driver.navigate().refresh();

Example:
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace hello_world
{
class Program
{
static void Main(string[] args)
{
                   //Creates a new instance of chrome browser
   IWebDriver chrome = new ChromeDriver();
                   //Navigates to google.com
   chrome.Navigate().GoToUrl("https://www.google.com");
                   //Navigates to facebook.com
   chrome.Navigate().GoToUrl("https://facebook.com");
                   //Refreshs facebook.com
  chrome.Navigate().Refresh();
                   //Goes back to google.com
  chrome.Navigate().Back();
                  //goes forth to facebook
  chrome.Navigate().Forward();
}
}
}



In the next tutorial let us learn to Inspect web elements!

First Automation Program


First Automation Program


Let us kick start automating our first program.

Program: To open www.google.com in chrome browser.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
 namespace First_Program
     {
            class Program
                {
                     static void Main(string[] args)
                       {
                          //Creates an instance of chrome browser
                          IWebDriver chrome = new ChromeDriver();

                          //Opens www.google.com in chrome browser
                          chrome.Navigate().GoToUrl("https://www.google.com");
                                            
                        }
                 }
     }


Now let us analyse the above program:

  • Importing Packages in Namespace Section
    • OpenQA.Selenium - Contains the WebDriver class needed to instantiate a new browser loaded with a specific driver
    •  OpenQA.Selenium.Chrome -  Contains the chromeDriver class needed to instantiate a chrome-specific driver onto the browser instantiated by the WebDriver class.
    • The following namespace are specific to browser:
      • using OpenQA.Selenium.Edge; //Used for Edge browser
      • using OpenQA.Selenium.IE; //Used for IE Browser
      • using OpenQA.Selenium.firefox; //Used for firefox browser
      • using OpenQA.Selenium.Opera; // Used for Opera browser
  • Main Program:
    • Iwebdriver is an interface through which user controls the browser.
       IWebDriver chrome = new ChromeDriver(); 
      //The above statement creates a new instance of google chrome browser.                  Syntax to create a new instance of various browser:-
      • IWebDriver IE = new InternetExplorerDriver();//For IE Explorer
      • IWebDriver fox = new FirefoxDriver();//For Morzilla firefox
      • IWebDriver edge = new EdgeDriver();//For Edge browser
    • chrome.Navigate().GoToUrl("Https://www.google.co.in");
      The navigate method instructs the browser to navigate to another location.
    • GoToUrl(string) method loads a webpage in the current browser window.



We finally finished Automating our first program.

In the next Tutorial let us learn more about navigation command! 

Setup Selenium in Visual Studio


Setup Selenium in Visual Studio



Steps to configure Selenium webDriver in Visual Studio:

  • Step 1:  Download and Install Visual Studio into your system
  • Step 2:  Create a new folder named as "Selenium" in "c:\" drive
  • Step 3:  Download and extract chrome driver exe and IEDriverServer exe 
  • Step 4:  Copy these .exe files to newly created Selenium folder (c:\Selenium)
  • Step 5:  Open control panel and search "Path" in search bar.
  • Step 6:  Now click on "Edit the system variables" as shown below
  • Step 7:  In system Properties pop up window click on "Environment variables..." under advanced tab.
  • Step 8: Select path and click on edit as shown below


  • Step 9: In "Edit environment Variable" window  click on "New" and add "C:\Selenium" and finally click on "OK"


  • Step 10: Open Visual Studio and click on New Project
  • Step 11: Select Console Application and enter Name of your choice(In our example its "hello world") and click on "OK"



  • Step 12: In Visual Studio navigate to Tools>NuGet Package Manager>Manage NuGet Packages for solution and click on it.


  • Step 13:Search Selenium in the search bar and  later install and add the following packages to the current solution:-
    • Selenium.WebDriver
    • Selenium.Suppport
    • Selenium.WebDriver.ChromeDriver
    • Selenium.WebDriver.IEDriver




Finally we have finished setting up selenium in Visual Studio!!!

In our next tutorial let us  automate our first program ! 


Introduction to Selenium


Introduction to Selenium




                                                               
                                                  "Selenium Automates Browser"

Selenium is an open source tool which is used for automating web applications.
It is primarily used by software testers for testing various Websites and it was developed by Jason Huggins an engineer at Thought Works in 2004.


The Key Features Of Selenium are:

  • It supports a vast number of browsers
  • It works on vast number of operating Systems
  • It supports mobile devices
  • Can execute multiple test cases in parallel
  • Open source tool
  • It supports multiple languages

Tool Suites of Selenium

Depending on the testing needs selenium is categorized into four components:

  1. Selenium IDE
    • Selenium IDE is an integrated development environment for Selenium tests.
    • Selenium IDE is a fire fox add-on that records clicks , typing and other actions to make test cases which tester can playback in the fire fox browser and export to Selenium RC.
    • Selenium IDE has the following features: record/ playback feature, debugging with step by step and break points.
    • Selenium IDE allows you to save tests as HTML, Java, Ruby scripts, or any other format. Allows you to add selenese commands as and when required.4
  2. Selenium RC
    • A solution to cross browser testing.
    • A server, written in Java and so available on all the platforms.
    • Acts as a proxy for web requests from them.
    • Client libraries for many popular languages.
    • Bundles Selenium Core and automatically loads into the browser.
    • Selenium RC is used to enhance your script.
  3. Selenium Grid
    • Selenium-Grid allows the Selenium-RC solution to scale for test suites or test suites to be run in multiple environments.
    • With Selenium-Grid multiple instances of Selenium-RC are running on various operating system and browser configurations, each of these when launching register with a hub. When tests are sent to the hub they are then redirected to an available Selenium-RC, which will launch the browser and run the test.
    • This allows for running tests in parallel, with the entire test suite theoretically taking only as long to run as the longest individual test.
  4. Selenium Webdriver
    • WebDriver is designed in a simpler and more concise programming interface along with addressing some limitations in the Selenium-RC API.
    • WebDriver is a compact Object Oriented API when compared to Selenium1.0.
    • It drives the browser much more effectively and overcomes the limitations of Selenium 1.x which affected our functional test coverage, like the file upload or download, pop-ups and dialogs barrier


C# is a powerful and elegant language to learn and in this tutorial we continue to use Selenium in C# .






In our next tutorial let us learn to setup selenium in Visual studio IDE!