Friday 26 June 2015

Handling drop down List in Selenium Webdriver with C#

     Click Here To Download Code 

      To Handle dropDownlist in selenium webdriver, We have to use "SelectElement" class in c#.Net.
It is located in package of "OpenQA.Selenium.Support.UI".

There are different representation of "Select" class in C#.Net and Java.

In C#:
Ex:
     SelectElement  se  = new SelectElement( element ) ;

In Java:
Ex:
     Select se = new select( element ) ;

We can Select element/option from DropDown List by 3-ways:
  1. SelectByIndex( int )       -   Select an option by index position.
  2. SelectByValue( String )  -   Select an option by the value.
  3. SelectByText( String )    -   Select an option by displayed Text.

To demonstrate how to handle drop down list. I am going to consider "Facebook" application. Because it has three drop down list 1-Month  2-Day & 3-Year(Birthdate).
In Below example I want to select Jun 21 1984 as a Birthdate,


Example:
using System;
using NUnit.Framework;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

namespace SleniumWebDriverWithCSharpTutorial
{
    [TestFixture]
    public class HandlingDropDownList
    {
        IWebDriver driver = null ;
        IWebElement element = null ;

        [SetUp]
        public void SetUP()
        {
            driver = new FirefoxDriver();
            driver.Manage().Window.Maximize();
            driver.Url = "http://facebook.com";
        }

        [Test]
        public void TestDropDownList()
        {
            //wait for to get Facebook Home page title
            WebDriverWait wait = new WebDriverWait(driver,TimeSpan.FromSeconds(10));
            wait.Until(ExpectedConditions.ElementIsVisible(By.Id("month")));

            //Handling Drop Down List to select Birth Month as "Jun".
            SelectElement se = new SelectElement(driver.FindElement(By.Id("month")));
            foreach (IWebElement item in se.Options)
            {
                if (item.Text == "Jun")
                {
                    item.Click();
                    break ;
                }                   
            }
     
           //Set previous element reference to b=null
            se = null ;
            //select By using Index Position
            se = new SelectElement(driver.FindElement(By.Id("day")));
            se.SelectByIndex(21);


            //Set previous element reference to b=null
            se = null ;
            //Select By Using Value
            se = new SelectElement(driver.FindElement(By.Id("year")));
            se.SelectByValue("1984");           
        }

        [TearDown]
        public void TearDown()
        {
            if (element != null)
                element = null ;
            driver.Close();
        }
    }
}









Click Here To Download Code

Sunday 14 June 2015

Page Object Model For Selenium WebDriver

 Click Here to  Download Complete Project


Page Object Model Framework in Selenium:

              Page Object Model Framework has now a days become very popular test automation framework in the industry and many companies are now adopting it because of its easy test maintenance and reduces the duplication of code. 
  • The main advantage of Page Object Model is that if the UI element / Controls changes for any page, it doesn't require us to change any Tests . 
  • We just need to change only the code within the page objects. This framework is mostly used with Selenium. 
  • It is one Design Pattern for Selenium Code.
  • It Provides the clean separation page code from Test code.

             In Page Object Model we are going to Create a Separate class for separate Web Page. In that class we are going to map UI elements as a object and their respective action on these controls such as "signIn" or "sign-Up" or "Forget password".

Each action on a page (controls) can be represented as a method in their respective class. so Finally we can say that - "Each page has respective class containing UI element(Locators of each element on that page ) and their respective actions as a "Method" in that class.  

See in a below screen shot-
        Here I am considering facebook applicatios "HomePage". I have Used POM framework to Test Facebook Application. I have written Three Test. we will see in later part......
 


UI Element and their Locators:

        static IWebDriver driver = null;
        static IWebElement element = null;
        //(UIObject) Locators for Login/SignIn
        static By userName = By .Id("email");
        static By Password = By .Id("pass");
        static By LogIn = By .XPath("//input[@type='submit'][@value='Log In']");
              
        // (UIObject) Locators for to Register a New User on Facebook Application
        static By FirstName = By .Id("u_0_1");
        static By LastName = By .Id("u_0_3");
        static By Email = By .Id("u_0_5");
        static By ReEmail = By .Id("u_0_8");
        static By NewPassword = By .Id("u_0_a");
        static By Month = By .Id("month");
        static By Day = By .Id("day");
        static By Year = By .Id("year");
        static By GenderFemale = By .Id("u_0_d");
        static By GenderMale = By .Id("u_0_e");
        static By SignUp = By .Id("u_0_i");

Respective Action on UI element:
         /// <summary>
        /// Set the user Name to be Logged in.
        /// </summary>
        /// <param name="UserName">
UserName to be Log-In</param>
        public static void setUserName(String UserName)
        {
            driver.FindElement(userName).SendKeys(UserName);
        }

        /// <summary>
        /// Set the Password, in the password field of facebook application.
        /// </summary>
        /// <param name="UserPassword">
Password of user wants to Log-in.</param>
        public static void setUserPassword(String UserPassword)
        {
            driver.FindElement(Password).SendKeys(UserPassword);
        }

        /// <summary>
        /// Clcik on Login In Button.
        /// </summary>
        public static void ClickLogin()
        {
            driver.FindElement(LogIn).Click();
        }

Advantages of Framework:

  • The biggest advantage of the software framework is that it reduces the time and energy in developing any software.
  • There is clean separation between test code and page specific code such as locators.
  • Code Maintainability
  • More Readability.
  • Less Error Prone.
  • Seperation of Concern.
  • Framework follow design pattern, so when you use these frameworks you’ve to follow their coding convention which makes your code clean and extensible for future purpose.
  • Framework separates business logic from user interface making the code cleaner and extensible.
  • Frameworks help you to develop the project rapidly, if you know one framework well then you’ll never worry about the project deadline.

How to setup Page Object Model In Visual Studio ( Selenium with C# & NUnit )

Pre-requisite:

  • Visual studio Any version (I have used 2012).
  • NUnit 2.6.4
  • Selenium webdriver (selenium-server-standalone-2.46.0.jar)

Steps to Create:

Open Visual Studio
1- Select New Project -> select Visual C# -> select Class Library. give Name as PageObjectModel.
     Add the  references for Selenium

2- Select the Solution and right click add->New Project->Test->Unit Test.
Add the references for NUnit Testing Framework.

Description:
  • The Class Library project contains the selenium code ( Webpage UI Element and their respective actions )
.
The Next, Test project contains the Test  code only.

  • The  standard says Your class Library should be depends on selenium and your Test should be independent.


Project Structure:
    See the below screen shot for Project structure in a project. 



=============================================================================================
Class library project Contains Following files:

Browser.cs : Common file used to set the Browser while executing the Test.

HomePage.cs: Contains the "Login" and "sign-Up" Actions

AfterLogin.cs: Contains the "UpdateStatusOnfacebook" & "Loggedout" actions.

RegisterPage.cs: Contains the "getTitle" action.

Test Project contains following files:

AfterLoginTest.cs: Test the functionality of Successful "Login" and after "UpdateStatusOnfacebook".

HomePage.cs:Test the functionality of "Login" successful and "RegisterNewUser".

Project Code:

File Browser.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.IE;


namespace PageObjectModel
{
    public class Browser
    {
        static IWebDriver driver = null ;

        public static String BrowserName = null ;


        /// <summary>
        /// set the Browser in which Application should be opened.
        /// </summary>
        /// <param name="BName">Enter the Name of Browser</param>
        /// <returns>Newly created instance of Respective Browser</returns>

        public static IWebDriver SetBrowserName(String BName)
        {
            switch (BName)
            {
                case "firefox":
                    {
                        driver = new FirefoxDriver();
                        break;
                    }
                case "chrome":
                    {

                        driver = new ChromeDriver("G:\\Selenium\\LatestDriver\\chromedriver_win32");
                        break;
                    }
                case "ie":
                    {
                        driver = new InternetExplorerDriver("G:\\Selenium\\LatestDriver\\IEDriverServer_Win32_2.46.0");
                        break;
                    }
                default:
                    {
                        driver = null;
                        break;
                    }
            }
            return driver;
        }

        /// <summary>
        /// Close the current Browser/Application
        /// </summary>

        public static void Close()
        {
            driver.Close();
        }
    }
}


File HomePage.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.IE;


namespace PageObjectModel
{
    public class HomePage
    {

        static IWebDriver driver = null;
        static IWebElement element = null;
        //(UIObject) Locators for Login/SignIn
        static By userName = By .Id("email");
        static By Password = By .Id("pass");
        static By LogIn = By .XPath("//input[@type='submit'][@value='Log In']");


        // (UIObject) Locators for to Register a New User on Facebook Application
        static By FirstName = By .Id("u_0_1");
        static By LastName = By .Id("u_0_3");
        static By Email = By .Id("u_0_5");
        static By ReEmail = By .Id("u_0_8");
        static By NewPassword = By .Id("u_0_a");
        static By Month = By .Id("month");
        static By Day = By .Id("day");
        static By Year = By .Id("year");
        static By GenderFemale = By .Id("u_0_d");
        static By GenderMale = By .Id("u_0_e");
        static By SignUp = By .Id("u_0_i");


        /// <summary>
        /// Constructor to initialize set the browser for Homepage
        /// </summary>
        /// <param name="driverr">Tell us on which Browser the application is going to open</param>

        public HomePage(IWebDriver driverr)
        {
            driver = driverr;
        }

        /// <summary>
        /// Set the Browser on which the application is to be Run/Test.
        /// </summary>
        /// <param name="BrowserName">Name of browser to be Set</param>
        /// <returns>Instance of newely set Browser</returns>

        public static IWebDriver setbrowser(String BrowserName)
        {
            driver = Browser.SetBrowserName(BrowserName);
            return driver;
        }

        /// <summary>
        /// Set the URL of an Application to be Test
        /// </summary>
        /// <param name="url">URL of Your Application under Test.</param>

        public static void SetURL(String url)
        {
            driver.Manage().Window.Maximize();
            driver.Navigate().GoToUrl(url);
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
        }

        /// <summary>
        /// Set the user Name to be Logged in.
        /// </summary>
        /// <param name="UserName">UserName to be Log-In</param>

        public static void setUserName(String UserName)
        {
            driver.FindElement(userName).SendKeys(UserName);
        }

        /// <summary>
        /// Set the Password, in the password field of facebook application.
        /// </summary>
        /// <param name="UserPassword">Password of user wants to Log-in.</param>

        public static void setUserPassword(String UserPassword)
        {
            driver.FindElement(Password).SendKeys(UserPassword);
        }

        /// <summary>
        /// Clcik on Login In Button.
        /// </summary>

        public static void ClickLogin()
        {
            driver.FindElement(LogIn).Click();
        }

        /// <summary>
        /// Click on Logged in Button after filling UserName and Password field.
        /// </summary>
        /// <param name="userName">User Name of User</param>
        /// <param name="Password">Password of User.</param>
        /// <returns>Return/Directed to the Next page after successful of Registering the User.</returns>

        public static AfterLogin ClickOnLogin(String userName, String Password)
        {
            setUserName(userName);
            setUserPassword(Password);
            ClickLogin();
            return new AfterLogin(driver);
        }

        /// <summary>
        /// Get the Title/Constant String from Home Page to Identify each page from each other.
        /// </summary>
        /// <returns></returns>

        public static String getTitle()
        {
            return driver.Title;
        }

        //II Test Part 
        // second part of Action in a HomePage is  Register a User

        /// <summary>
        /// Set the New User name to be Register.
        /// </summary>
        /// <param name="firstName">Enter First name of User</param>

        public static void SetRegisterUserFirstName(String firstName)
        {
            driver.FindElement(FirstName).SendKeys(firstName);
        }

        /// <summary>
        /// Set the New User Last Name to be Register.
        /// </summary>
        /// <param name="lastName">last Name of New User</param>

        public static void SetRegisterUserLastName(String lastName)
        {
            driver.FindElement(LastName).SendKeys(lastName);
        }

        /// <summary>
        /// Set the Email of New user for Verification.
        /// </summary>
        /// <param name="eMail">Enter Email of New user for verification</param>

        public static void SetEmail(String eMail)
        {
            driver.FindElement(Email).SendKeys(eMail);
        }

        /// <summary>
        /// Re-Enter the mail
        /// </summary>
        /// <param name="reEmail">Re-Enter the mail of new user </param>

        public static void SetReEMail(String reEmail)
        {
            driver.FindElement(ReEmail).SendKeys(reEmail);
        }

        /// <summary>
        /// Set the Password for Facebook login for new user
        /// </summary>
        /// <param name="newPassword">Enter New password</param>

        public static void SetNewPassword(String newPassword)
        {
            driver.FindElement(NewPassword).SendKeys(newPassword);
        }

        /// <summary>
        /// Select the Month from Drop Down List.
        /// </summary>
        /// <param name="month">Enter your Birth Month  </param>

        public static void SelectMonth(String month)
        {

            SelectElement select = new SelectElement(driver.FindElement(Month));
            foreach (IWebElement item in select.Options)
            {
                if (item.Text.Contains(month))
                    item.Click();
            }
        }

        /// <summary>
        /// select  the year of Your Birth from Drop DownList.
        /// </summary>
        /// <param name="year">Enter Your year of Birth.</param>

        public static void SelectYear(String year)
        {
            SelectElement select = new SelectElement(driver.FindElement(Year));
            foreach (IWebElement item in select.Options)
            {
                if (item.Text.Contains(year))
                    item.Click();
            }
        }

        /// <summary>
        /// Select Birth day from drop DownList.
        /// </summary>
        /// <param name="day">Enter your Birthday.</param>

        public static void SelectDay(String day)
        {
            SelectElement select = new SelectElement(driver.FindElement(Day));
            foreach (IWebElement item in select.Options)
            {
                if (item.Text == day)
                    item.Click();
            }
        }

        /// <summary>
        /// select Your Gender
        /// </summary>
        /// <param name="gender">select Male / Female</param>

        public static void selectGender(String gender)
        {
            String genderr = gender.ToLower();
            element = driver.FindElement(GenderMale);
            if (element.Text.ToLower() == genderr)
            {
                element.Click();
            }
            else
            {
                element = driver.FindElement(GenderFemale);
                element.Click();
            }
            element = null;
        }

        /// <summary>
        /// Click on signUp Button
        /// </summary>

        public static void ClickSignUp()
        {
            driver.FindElement(SignUp).Click();
        }

        /// <summary>
        /// Register  the new User with His/Her details.
        /// </summary>
        /// <param name="firstName">Name of User.</param>
        /// <param name="lastname">Last Name Of User.</param>
        /// <param name="eMail">Existing Email of User.</param>
        /// <param name="reEmail">Re-Enter the Existing E-mail.</param>
        /// <param name="newPassword">Enter New Password to access facebook Application</param>
        /// <param name="month">month of Birth.</param>
        /// <param name="day">Birth Day</param>
        /// <param name="year">Birth Year</param>
        /// <param name="gender">male/Female</param>
        /// <returns>Return or Redirect to register Page.</returns>

        public static Registerpage RegisterNewUser(string firstName, String lastname, String eMail, String reEmail, string newPassword, String month, string day, string year, String gender)
        {
            SetRegisterUserFirstName(firstName);
            SetRegisterUserLastName(lastname);
            SetEmail(eMail);
            SetReEMail(reEmail);
            SetNewPassword(newPassword);
            SelectMonth(month);
            SelectDay(day);
            SelectYear(year);
            selectGender(gender);
            ClickSignUp();
            System.Threading.Thread.Sleep(5000);
            return new Registerpage(driver);
        }


    }
}


Click Here to  Download Complete Project

 

See Also:

Wednesday 10 June 2015

implicit and explicit wait in selenium

There are two types of wait in Selenium

Implicit & Explicit

Types of Wait In Selenium

Implicit:

  1. Selenium Web Driver has borrowed the idea of implicit waits from Watir.
  2. An implicit wait is to tell Web Driver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available.
  3. We should note that implicit waits will be in place for the entire time the browser is open or whole life of Webdriver object.
  4. This means that any search for an elements on the page could take the time the implicit wait is set for.
  5. This Time is applicabe to each individual instuction / Statement in test.
  6. Default implicit wait is 0.

Java Code:
WebDriver driver = null;
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

C# Code:
IWebDriver driver = null;
driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));


Explicit Wait:

  1. In explicit wait you can write custom code for a particular element to wait for particular time of period before executing next steps in your test.
  2. This provide you better option than implicit wait.
  3. WebDriver introduces classes like WebDriverWait and ExpectedConditions to enforce Explicit waits into the test scripts.
  4. It is more suitable to handle JQuery, Ajax techniques / effect.
  5. FluentWait is also comes under the Explicit wait.

Java Code:

IWebDriver driver = null;
driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("month"))));

C# code:

IWebDriver driver = null;
driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementIsVisible(By.PartialLinkText("Selenium WebDriver Practical 
Guide")));

Example of WebdriverWait in Java:

 

package airtel;

import static org.junit.Assert.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.jboss.netty.util.Timeout;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class WebdriverWaitDemo
{

    WebDriver driver = null;
    WebElement element = null;
    String actualText = null;

    @Before
    public void setUp() throws Exception
    {

        driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.get("http://www.airtel.in/mobile/prepaid/tariffs");
       
    }
   
    @Test
    public void test()
    {

        WebDriverWait wait = new WebDriverWait(driver,20);
        wait.until(ExpectedConditions.elementToBeClickable(By.id("region")));
       
        Select changeRegion = new Select(driver.findElement(By.id("region")));
        List<WebElement> regionList = changeRegion.getOptions();
        for (WebElement webElement : regionList)
        {           
           if(webElement.getText().toString().contains("Maharashtra"))
           {
             webElement.click(); 
           }
        }
       
        /***
         * Wait to see the different plans availabe for maharashtra region.
         * We will check the label Tariffs plans that are available in karnataka to Tariffs plans that are available in Maharashtra and Goa
         */

        WebDriverWait waitt = new WebDriverWait(driver,10);
        waitt.until(ExpectedConditions.elementToBeClickable(By.id("region")));
       
        element = driver.findElement(By.id("fillCircleName"));
        actualText = element.getText();
        System.out.println(actualText);
               
        Assert.assertEquals("WebDriverWait run successfully", "Below are the tariff plans available in Maharashtra and Goa", actualText);
       
    }

    @After
    public void tearDown() throws Exception
    {

        /***
         * Wait for 30 second to see the changes has done on browser or not.
         */

        Thread.sleep(20000);
        element = null;
        driver.close();
      
 
    }  

}

 

==============================================================================================

Example of FluentWait in java .


package airtel;

import static org.junit.Assert.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.jboss.netty.util.Timeout;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.google.common.base.Predicate;


public class FluentWaitDemo
{

    WebDriver driver = null;
    WebElement element = null;
    String actualText = null;

    @Before
    public void setUp() throws Exception
    {

        driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.get("http://www.airtel.in/mobile/prepaid/tariffs");
       
    }  

    @Test
    public void test()
    {
        FluentWait<By> wait = new FluentWait<By>(By.id("region"));
        wait.withTimeout(10, TimeUnit.SECONDS);
        wait.pollingEvery(1000, TimeUnit.MILLISECONDS);
       
        wait.until(new Predicate<By>()
            {
              public boolean apply(By by)
                {
                  try
                  {
                      return driver.findElement(by).isDisplayed();
                  }
                  catch (NoSuchElementException ex)
                  {
                     return false;
                  }
                }
            });
               
        Select changeRegion = new Select(driver.findElement(By.id("region")));
        List<WebElement> regionList = changeRegion.getOptions();
        for (WebElement webElement : regionList)
        {           
           if(webElement.getText().toString().contains("Maharashtra"))
           {
             webElement.click(); 
           }
        }
       

       
      
  /***
         * Wait to see the different plans availabe for maharashtra region.
         * We will check the label Tariffs plans that are available in karnataka to Tariffs plans that are available in Maharashtra and Goa
         */

     FluentWait<By> wait = new FluentWait<By>(By.id("fillCircleName"));
        wait.withTimeout(10, TimeUnit.SECONDS);
        wait.pollingEvery(1000, TimeUnit.MILLISECONDS);
       
        wait.until(new Predicate<By>()
            {
              public boolean apply(By by)
                {
                  try
                  {
                      return driver.findElement(by).isDisplayed();
                  }
                  catch (NoSuchElementException ex)
                  {
                     return false;
                  }
                }
            });

        element = driver.findElement(By.id("fillCircleName"));
        actualText = element.getText();
        System.out.println(actualText);
               
        Assert.assertEquals("WebDriverWait run successfully", "Below are the tariff plans available in Maharashtra and Goa", actualText);
       
    }

    @After
    public void tearDown() throws Exception
    {

        /***
         * Wait for 30 second to see the changes has done on browser or not.
         */

        Thread.sleep(20000);
        element = null;
        driver.close();
      
 
    }  

}

Thread.Sleep(time):

                This also comes under the Explicit time but the standard says instead of thread.Sleep(time) Use above defined class as "WebDriverwait" and "FluentWait".
Thread.Sleep(time) un-necessary creates / generates the delay in execution of your TestCase / testScript if the element is available within the time still Thread.sleep(time) will wait till the specified time. 
So we most of the time we don't know in how much amount of time an element is available,displayed or visible on the page so better to go with above defined class.

Tuesday 9 June 2015

Download file using Selenium webdriver C#

 Scenario:

1- Download a PDf file.
2- Store it on a specific Directory. In my case d:\Avinash\filename.pdf
3- Read the  Downloaded file using in C#
4- Show the Contents of each page on the screen.

Introduction:

Download a Pdf file using selenium WebDriver. I have set the preferences in firefox browser to tell the browser which kind of file is going to handle and what action should take while downloading that file.


Below example is for to dowmload the pdf file from google.com. But in my firefox their is an already integration of IDM(Internet Download Manager) with Mozilla. so whenever I will download that file the IDM's file download dialog is open.
See below screenshot.



So In my case to handle the IDM's file Download Dialog I have Used thirty party tool as "AutoIt V3" to handle windows Button or Control on Internet Download manager Dialog.

Prerequisite:

1-Visual Studio any version
2- Install / Add  "ITextSharp.dll" through the NuGet package in current project / Solution.
3- AutoIt V3 Scripting tool.
4- AutoIt Window Info.
5- NUnit Testing  framework.

Procedure:

1-Open  visual Studio.
2- Select File -> New project -> Select Test -> Select Unit Test.
3- Give project Name as "DownloadPDFandreadPDF".
4- Install "itextSharp" from Nuget.  see below ScreenShot.
     Select Tools menu-> select Library Package manager->Manage NuGet packages for Solution.
5- Remove the Existing refernce of Unit Testing and add the reference of Nunit.
     using Microsoft.VisualStudio.TestTools.UnitTesting;   - Remove It.   &
     Add    using using NUnit.Framework;
6 Add the respective references for selenium.

Code :

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using NUnit.Framework;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;
namespace DownloadPDFandreadPDF
{
    [TestFixture]
    public class DownloadPDFAndRead
    {
        IWebDriver driver = null;
        IWebElement element = null;
        FirefoxProfile FProfile = null;
        String DownloadfilePath = "d:\\Avinash";

        [SetUp]
        public void BeforeTest()
        {
            FirefoxProfile profileSetUp = FirefoxProfilesetup(DownloadfilePath);
           
            driver = new FirefoxDriver(profileSetUp);
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
            driver.Navigate().GoToUrl("http://www.google.com");
           
        }
        [Test]
        public void TestDownloadPDFAndRead()
        {
            driver.FindElement(By.Id("lst-ib")).SendKeys("selenium webdriver practical guide pdf");
            driver.FindElement(By.XPath("//button[@value='Search']")).Click();

            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            wait.Until(ExpectedConditions.ElementIsVisible(By.PartialLinkText("Selenium WebDriver Practical 
            Guide")));

            driver.FindElement(By.PartialLinkText("Selenium WebDriver Practical Guide")).Click();
            System.Threading.Thread.Sleep(5000);

            //In my case I have installed Internet Download Manager & it is configured with Firefox
            //so to handle internet download manager dialog I have used Autoit tool to handle it.


            System.Threading.Thread.Sleep(5000);
            System.Diagnostics.Process.Start("G:\\Autoit\\DownloadPDFFile.exe");
            Console.WriteLine("file Download Completed.....!");

            ReadPDF("d:\\Avinash\\9781782168850_Sample.pdf");
        }


        [TearDown]
        public void AfterTest()
        {
            element = null;
            driver.Close();
        }

        /// <summary>
        /// Set the preference in firefox. which kind of file(extension)you are downloading & how to handle  
            the download dialog.
        /// </summary>
        /// <param name="DownloadfilePath">Specify the path where to keep the downloaded PDF  
            file.</param>
        /// <returns></returns>
        public FirefoxProfile FirefoxProfilesetup(String DownloadfilePath)
        {
            FProfile = new FirefoxProfile();
            FProfile.SetPreference("browser.download.folderList", 2);
            //profile.SetPreference("browser.download.manager.showWhenStarting", true);//added
            FProfile.SetPreference("browser.download.dir", DownloadfilePath);
            FProfile.SetPreference("browser.helperApps.neverAsk.openFile",
                                    "text/csv,application/x-msexcel,application/excel,application/x-excel,application
                       /vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
            FProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk",
                                    "text/csv,application/x-msexcel,application/excel,application/x-excel,application
           /vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");

           
            FProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
            FProfile.SetPreference("browser.helperApps.alwaysAsk.force", false);
            FProfile.SetPreference("browser.download.manager.alertOnEXEOpen", false);
            FProfile.SetPreference("browser.download.manager.focusWhenStarting", false);
            FProfile.SetPreference("browser.download.manager.useWindow", false);
            FProfile.SetPreference("browser.download.manager.showAlertOnComplete", false);
            FProfile.SetPreference("browser.download.manager.closeWhenDone", false);              
            FProfile.SetPreference("browser.download.manager.showAlertOnComplete", true); //added alert 
            should show after completion

            return FProfile;
        }

        /// <summary>
        /// Read the contents of Downloaded .pdf file and prints on the screen
        /// </summary>
        /// <param name="PDFFilePath">Path to the downloaded file</param>
        public void ReadPDF(String PDFFilePath)
        {
            PdfReader reader = new PdfReader(PDFFilePath);
            String PDFContents = PdfTextExtractor.GetTextFromPage(reader, 1);
            Console.WriteLine("File length:"+ reader.FileLength);
            Console.WriteLine("No. Of pages"+reader.NumberOfPages);

             System.Text.StringBuilder sb = new System.Text.StringBuilder();
             ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();

             for (int i = 1; i < reader.NumberOfPages; i++)
             {
                 sb.Clear();
                 sb = sb.Append(PdfTextExtractor.GetTextFromPage(reader, i, its));
                 Console.WriteLine("Contents of Page{0}:{1}",i, sb);               
             }
             try
               {
                 reader.Close();
               }
             catch
               {
                 Console.WriteLine("Exception Occured while reading PDF File....!");
               }
        }

    }
}

AutoIt Code:

1- Open SciTE editor.
2- Open the AutoIt Window Info 
3- Drag and Drop the Finder tool on control which we required to handle.
                like downlad path and start button on IDM download dialog.
4- We will get the information as title , text, ControlId etc. see the below screen shot.
5- Write / paste the below code in SCiTE editor and save as .au3 extension.

AutoIt Code:

 ControlFocus("Download File Info","","Edit4");
 ControlSetText("Download File Info","","Edit4","d:\Avinash\Avinash.pdf");
 ControlClick("Download File Info","","Button1");

Excecute:

1- Compile the whole project in visual studio.
2- Open the Nunit Application from start menu.
3- Select file -> Open project ->  go to the path where current project .dll is located.
4- Select the .DLL having same name as your current Project in this case "DownloadPDFandreadPDF.dll"
5- Click on run button for execution.

Note: using thread.Sleep() will cause delay  in execution. Standard says don't use excessive. User WebdriverWait, defaultWait etc....