Tuesday, 20 May 2014

How to connect SQL server using QTP script


1) We should know the below details before establish database connection with SQL server.


Provider = SQLOLEDB.1  (Default for all SQL server connection)
Server   = Server_Name
uid = User_ID
Password = Password for login into SQL server.
Database = Name of the database


2) QTP dont have the built-in function for access SQl server. So we can use access the data in SQL server by using ADODB connection. SO we should create object for ADODB connection and Recordset,

Set objcon=CreateObject("ADODB.Connection")
Set objrs=CreateObject("ADODB.RecordSet")

3) Establish database connection by using connection string

Syntex : 

objcon.open "Provider= Provider name (SQLOLEDB.1);Server=server_Name;uid=User_ID;Password=User_Password;Database=Database_Name;"

Example:

objcon.open "Provider=SQLOLEDB.1;Server=SQLServerName;uid=arunrajvdm;Password=arunrajvdm;Database=arunrajvdmdatabase;"

Here,

Provider = SQLOLEDB.1  (Default for all SQL server connection)
Server   = SQLServerName
uid = arunrajvdm
Password = arunrajvdm
Database = arunrajvdmdatabase


4) Execute Query

Syntex:

objrs.open "SQL_Statements",object of ADODB connection(objcon)

Example:

objrs.open "Select * from Emp",objcon


5) Access the data from database by using column_Name

we can use Fields property of Recordset object.

Syntex :

objrs.Fields("Column_Name")

Example

objrs.Fields("First_Name")



Sample Script:

Extracting the data from SQL Server database and update into the Excel


Set xl=CreateObject("Excel.Application")
Set xlwb=xl.Workbooks.Open("E:\SQLConnection.xls")
Set xlws=xlwb.Worksheets("TestData")

Set objcon=CreateObject("ADODB.Connection")
Set objrs=CreateObject("ADODB.RecordSet")

objcon.open "Provider=SQLOLEDB.1;Server=SQLServerName;uid=arunrajvdm;Password=arunrajvdm;Database=arunrajvdmdatabase;"
objrs.open "Select * from Emp",objcon

i=1
While not objrs.EOF
 xlws.Cells(i,1)= objrs.Fields("Emp_Name")
 objrs.MoveNext
 i=i+1
Wend


objrs.Close
Set objrs=nothing
objcon.Close
Set objcon =nothing

xlwb.Save
xl.Quit

Set xlws=nothing
Set xlwb=nothing
Set xl=nothing

Thursday, 15 May 2014

Generate Random Number with in given range using selenium webdriver




1) we can use java.util.Random class for generate random number.

2) nextInt(n) method used to generate any number from 0 to n.

Ex:

Random rg = new Random();
for (int idx = 1; idx <= 1000; ++idx){
int randomInt = rg.nextInt(1000);
System.out.println("Generated : " + randomInt);
}


From above Example nextInt(1000) generate random number from 0 to 1000 and display output in console.

Count Number of web Elements present in web page using selenium



1) count number of Button By using Class Name

<input id="ctrl1_btnADD" class="cart" type="submit" lang="LBLAART" flag="REMOVE" value="Acart" name="lstproduct" alt="ACart" title="Add to Cart">



List<WebElement> allElements = driver1.findElements(By.className("cart"));
System.out.println(allElements.size());



2) count number of link using xpath


<a id="HOME" href="http://arunrajvdm.blogspot.com/">
<span lang="HOME">Home</span>
</a>


List<WebElement> allElements1 = driver1.findElements(By.xpath("//a"));
System.out.println(allElements1.size());

Tuesday, 13 May 2014

Five simple steps to can check your EPF account balance

Here are five simple steps to can check your EPF account balance.

Step 1: Keep your EPFO account number handy. It is mentioned on your salary slip.

Step 2: Click the link Check Your EPF balance on the EPFO website, http://www.epfindia.gov.in/.

Check your PF balance onlineCheck your PF balance online. Picture courtesy:moeycontrol
Step 3: Select the state where your PF office is situated.

Step 4: Select the appropriate EPFO regional office. Knowing this is no rocket science. Your PF number is an alpha-numeric number and the first two letters stand for regional office. For instance, if the your PF number is DL/12345/6789 then choose DL as regional office code.

Step 5: Fill the online form with your name (as it appears on salary slip), your mobile number and your PF number. In thefirst box, you need to key in seven digits. So, in the example cited above, the set of number has only 5 digits, 12345. Here you have to add 00 in the first two boxes. Next box, fill in the three digit establishment code or leave it blank if you don't have one. Finally, the account number 6789 in the last box, and click submit.

You will receive an SMS in less than five minutes with your EPFO account balance, if your records are updated with EPFO office. Or else it will show data not found. You may have to get in touch with your employer in that case, or wait a bit longer for your data to be updated.Keep in mind that the account balance is updated up to 31/3/2012

Capture Bitmap Method in QTP



Saves the Screen capture of the object and saved with file ectension .png or .bmp depending upon the specified file extension.

Its used for store the screen capture of the test objects in QTP.


Syntax:

object.CaptureBitmap filename [override existing]

Object -> test object
Capturebitmap -> methode name
file name -> specified the full path file name with in quotes for wher we can stored the image file.
Override Existing -> True or False
        True -> the file override, if the file name already exists
        false -> defaulty QTP set as false, its not override.
Return Value : NONE

Ex:

Browser("Gmail: Email from Google").Page("Gmail: Email from Google").WebButton("Sign in").CaptureBitmap "E:\signin.bmp",True




Store screen shot hyperlink in excel using CaptureBitmap Method


Example Script:

Browser("Browser").Page("Order Summary").CaptureBitmap TestPath&"\Screenshots\"&"Number Of Access = "&NoOfAccess&".bmp",true
Linklocation =  TestPath&"\Screenshots\"&"Number Of Access = "&NoOfAccess&".bmp"
WS.Cells(i,12).value="=HYPERLINK("&""""&Linklocation&""""&","&""""&"Number Of Access = "&NoOfAccess&""""&")"


Here,

Testpath = Computer location used for save the screen shot


The above script used to capture the screen shot and saved into the perticular location. And stored as hyperlink in Excel.



Browser("Browser").Page("Order Summary").CaptureBitmap TestPath&"\Screenshots\"&Testcase&".bmp",true
Linklocation =  TestPath&"\Screenshots\"&Testcase&".bmp"
WS.Cells(i,12).value="=HYPERLINK("&""""&Linklocation&""""&","&""""&Testcase&""""&")"

Synchronization in Selenium

Synchronization is machanism for working more than one component working parellel each other.

Generally in test Automation, we can deal with two components,

1) Application under test.
2) Test Automation Tool

The above both componenets are working in different speed. So we can write the script for such a way to maintain same speed for above two components. SO that we will not encounter "Elements not found" error.

Two type of Synchronization

1) Unconditional Synchronization
2) Conditional Synchronization



1) Unconditional Synchronization

-> Here we can mention only time out value.

-> Its tell to the tool waiting for some specify amount of time.

EX: Thread.Sleep(30000)

The tool waitining for 30 sec while using above code.

Advantage : If we want to interact with third party systems like interface, its not possible to check the condition or write the condition. Here in the situation, we tell to the tool waiting for some amount of time by specified timeout value.

Disadvantage : If we specify the timeout value for 30 sec, the tool should waiting 30 sec, eventhough the application ready for 20 sec. So here the executing waiting for 10 sec unnecessarily. This is one of disadvantage for using un-conditional synchronization.




2) Conditional Synchronization

-> We specify a condition along with timeout value, so that tool waits to check for the condition and then come out if nothing happens. If the condition satisfied before timout value, its come proceed next step. So that we can avoid the tool waiting for lone time unnecessarily.

-> we have two condition synchronization

i) implicit synchronization
ii) Explicit Synchronization


i) Implicit synchronization

The implicit statement is used to tell web driver for wait certian time to find the element.

a) Element implicit Synchronization

-> We can set the default element existance timeout. Below statement will set the default object synchronization timeout as 20. This means that selenium script will wait for maximum 20 seconds for element to exist.

->If Web element does not exist within 20 seconds, it will throw an exception.

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

-> This machanism which written once and applied for entire script for find element. Its should defined once initiate the web driver.

-> Implicit wait will not work all the commands/statements in the application. It will work only for "FindElement" and "FindElements" statements.

-> We should always remember to add the below syntax immediately below the Webdriver statement.


b) Page Load Synchronization

-> We can set the default page navigation timeout. Below statement will set the navigation timeout as 50. This means that selenium script will wait for maximum 50 seconds for page to load.

-> If page does not load within 50 seconds, it will throw an exception.

driver.manage().timeouts().pageLoadTimeout(50,TimeUnit.SECONDS);



ii) Explicit Synchronization

-> We need to define the wait statement for certian condition to be satisfied until specified time period. if the webdriver find the element then it will execute.

-> we need to import WebDriverWait class using this statement.


 WebDriverWait wait = new WebDriverWait(driver, 10);

 wait.ignoring(NoSuchElementException.class);

 wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("statedropdown")));





Example code

WebDriverWait wait = new WebDriverWait(FireFoxDriver, 10);

WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className(“list-cnt”)));

visibilityOf(WebElement element) – An expectation for checking that an element, known to be present on the DOM of a page, is visible.

titleIs(java.lang.String title) – An expectation for checking the title of a page.

titleContains(java.lang.String title) - An expectation for checking that the title contains a case-sensitive substring

textToBePresentInElementValue(By locator, java.lang.String text) – An expectation for checking if the given text is present in the specified elements value attribute.

textToBePresentInElement(By locator, java.lang.String text) – An expectation for checking if the given text is present in the specified element.

stalenessOf(WebElement element) – Wait until an element is no longer attached to the DOM.

refreshed(ExpectedCondition<T> condition) – Wrapper for a condition, which allows for elements to update by redrawing.

presenceOfElementLocated(By locator) – An expectation for checking that an element is present on the DOM of a page.

presenceOfAllElementsLocatedBy(By locator) – An expectation for checking that there is at least one element present on a web page.

not(ExpectedCondition<?> condition) - An expectation with the logical opposite condition of the given condition.

invisibilityOfElementWithText(By locator, java.lang.String text) – An expectation for checking that an element with text is either invisible or not present on the DOM.

invisibilityOfElementLocated(By locator) – An expectation for checking that an element is either invisible or not present on the DOM.

frameToBeAvailableAndSwitchToIt(java.lang.String frameLocator) – An expectation for checking whether the given frame is available to switch to.

elementToBeSelected(WebElement element) – An expectation for checking if the given element is selected.

elementToBeSelected(By locator)

elementToBeClickable(By locator) – An expectation for checking an element is visible and enabled such that you can click it.


WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(“someid”)));






Fluent Wait:

Using FluentWait we can define the maximum amount of time to wait for a condition, as well as the frequency with which to check for the condition.

And also the user can configure to ignore specific types of exceptions such as "NoSuchElementExceptions" when searching for an element.

Syntax:



Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)

//Wait for the condition

      .withTimeout(30, TimeUnit.SECONDS)

        // which to check for the condition with interval of 5 seconds.

      .pollingEvery(5, TimeUnit.SECONDS)

    //Which will ignore the NoSuchElementException

      .ignoring(NoSuchElementException.class);

Thursday, 8 May 2014

Working with excel using selenium web driver (using Apache POI)

Apache POI

For Download = http://poi.apache.org/download.html


-> Apache POI is a powerful Java library to work with different Microsoft Office file formats such as Excel, Power point, Visio, MS Word etc.

-> The name POI was originally an acronym for Poor Obfuscation Implementation, referring humorously to the fact that the file formats seemed to be deliberately obfuscated, but poorly, since they were successfully reverse-engineered.

-> Apache POI library v3.8 or above. And download .Jar file like this format poi-bin-3.10 .jar in this link = http://poi.apache.org/download.html

-> Make sure to include apache poi jar file to your project. If your project uses Maven as dependency management, add following in your Pom.xml file.

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.8</version>
</dependency>
If you are not using Maven then you can directly add required JAR files in your classpath.





POI classes used for working with Excel

Apache POI main classes usually start with either HSSF, XSSF or SXSSF.

-> HSSF is the POI Project’s pure Java implementation of the Excel ’97(-2007) file format. e.g. HSSFWorkbook, HSSFSheet.

-> XSSF is the POI Project’s pure Java implementation of the Excel 2007 OOXML (.xlsx) file format. e.g. XSSFWorkbook, XSSFSheet.

-> SXSSF (since 3.8-beta3) is an API-compatible streaming extension of XSSF to be used when very large spreadsheets have to be produced, and heap space is limited. e.g. SXSSFWorkbook, SXSSFSheet. SXSSF achieves its low memory footprint by limiting access to the rows that are within a sliding window, while XSSF gives access to all rows in the document.

-> Apart from above classes, Row and Cell are used to interact with a particular row and a particular cell in excel sheet.

-> Another useful class FormulaEvaluator is used to evaluate the formula cells in excel sheet.

-> A wide range of classes like CellStyle, BuiltinFormats, ComparisonOperator, ConditionalFormattingRule, FontFormatting, IndexedColors, PatternFormatting, SheetConditionalFormatting etc. are used when you have to add formatting in a sheet, mostly based on some rules.





Similar to HSSF(Horrible SpreadSheet Format), POI has different prefix for other file formats too:

-> HSSF (Horrible SpreadSheet Format) – reads and writes Microsoft Excel (XLS) format files.
-> XSSF (XML SpreadSheet Format) – reads and writes Office Open XML (XLSX) format files.
-> HPSF (Horrible Property Set Format) – reads “Document Summary” information from Microsoft Office files.
-> HWPF (Horrible Word Processor Format) – aims to read and write Microsoft Word 97 (DOC) format files.
-> HSLF (Horrible Slide Layout Format) – a pure Java implementation for Microsoft PowerPoint files.
-> HDGF (Horrible DiaGram Format) – an initial pure Java implementation for Microsoft Visio binary files.
-> HPBF (Horrible PuBlisher Format) – a pure Java implementation for Microsoft Publisher files.
-> HSMF (Horrible Stupid Mail Format) – a pure Java implementation for Microsoft Outlook MSG files
-> DDF (Dreadful Drawing Format) – a package for decoding the Microsoft Office Drawing format.


***********************************************

Reading an excel file

Reading an excel file is also very simple if we divide this in steps.

-> Create workbook instance from excel sheet
-> Get to the desired sheet
-> Increment row number
-> Iterate over all cells in a row
-> Repeat step 3 and 4 until all data is read



Code For Reading data from .xls file

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

FileInputStream file1=new FileInputStream(new File("D:\\Selenium_Testing\\Selenium_Webdriver_Project\\Login1.xls"));
HSSFWorkbook workbook1=new HSSFWorkbook(file1);
HSSFSheet worksheet1=workbook1.getSheetAt(1);
Iterator<Row> rowiterator1=worksheet1.iterator();
while(rowiterator1.hasNext())
{
Row row1=rowiterator1.next();
Iterator<Cell> celliterator1=row1.cellIterator();
while(celliterator1.hasNext())
{
Cell cell1=celliterator1.next();
int cellType = cell1.getCellType();
switch (cellType) {
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell1.getNumericCellValue()+"\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell1.getStringCellValue()+"\t");
break;
}
System.out.println("\n");
}
}
file1.close();


Note : 
1) Change the above code from "Switch" to "if-else" statement if we have error like "case expressions must be constant expressions".
2) In Eclipse IDe, we can change "Switch" to "if-else" by clik on switch and pressing "CTRL+1".


***************************************

Code For Reading data from .xlsx file

FileInputStream file1=new FileInputStream(new File("D:\\Selenium_Testing\\Selenium_Webdriver_Project\\POI_Example.xlsx"));
XSSFWorkbook workbook1=new XSSFWorkbook(file1);
XSSFSheet worksheet1=workbook1.getSheetAt(0);
Iterator<Row> rowiterator1=worksheet1.iterator();
while(rowiterator1.hasNext())
{
Row row1=rowiterator1.next();
Iterator<Cell> celliterator1=row1.cellIterator();
while(celliterator1.hasNext())
{
Cell cell1=celliterator1.next();
int cellType = cell1.getCellType();
switch (cellType) {
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell1.getNumericCellValue()+"\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell1.getStringCellValue()+"\t");
break;
}
System.out.println("\n");
}
}
file1.close();


*************************************************************

How to write .xls file using apachi poi in selenium webdriver


We should use HSSFWorkbook and HSSFSheet class while working with .xls file.


package Model_Package;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class ExcelOperation {


public static void main(String[] args) throws IOException,FileNotFoundException {

try{
Cell searchcell=null;
FileInputStream File1=new FileInputStream("D:\\Selenium_Testing\\Selenium_Webdriver_Project\\Apache.xls");

HSSFWorkbook workbook1=new HSSFWorkbook(File1);
HSSFSheet Sheet1=workbook1.getSheetAt(0);   // Here "0" refers First WorkSheet. if "1" means its refer Seconds Sheet

Row row1=Sheet1.createRow(0);   //Here "0" indicates First Row.
searchcell=row1.createCell(0);  //Here "0" indicates first column of the specified row.

searchcell.setCellValue("Selenium");   //insert the "Selenium" text into that cell value
File1.close(); // close the input File Stream

FileOutputStream File2=new FileOutputStream("D:\\Selenium_Testing\\Selenium_Webdriver_Project\\Apache.xls");
workbook1.write(File2);
File2.close();

}
catch(Exception e)
{e.printStackTrace();}

}

}




i) How to get know last used row(End of the Text) in Excel Sheet

Integer Lastrow;
Lastrow = Sheet1.getLastRowNum();
Lastrow=Lastrow+1;



ii)  Issue while write Excel Sheet using Apache POI

We got Error while use below code to access the cell in Excel


 
  FileInputStream file = new FileInputStream(new File("C:\\testdata.xls"));  
  HSSFWorkbook workbook = new HSSFWorkbook(file);
 
  HSSFSheet sheet = workbook.getSheetAt(0);
   
  Cell searchText3 = sheet.getRow(0).getCell(0);
  searchText3.setCellValue("Test Search Keyword");
 
  file.close();
 
  FileOutputStream outFile =new FileOutputStream(new File("C:\\testdata.xls"));
  workbook.write(outFile);
  outFile.close();



The below Error while access the cell in Excel


Exception in thread "main" java.lang.NullPointerException at xltest.main(xltest.java:28)


Solution :

-> The below code is not working and return Null value.

 Cell searchText3 = sheet.getRow(0).getCell(0);

So we got the Null Pointer Exception while run the code.

-> Instead of above code we shoule use below code for access cell in Excel


Row row1=Sheet1.createRow(0);
searchcell=row1.createCell(0);







******************************************



How to write .xlsx file using apachi poi in selenium webdriver


We should use XSSFWorkbook and XSSFSheet class while working with .xlsx file.



package Model_Package;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class ExcelOperation {


public static void main(String[] args) throws IOException,FileNotFoundException {

try{
Cell searchcell=null;
FileInputStream File1=new FileInputStream("D:\\Selenium_Testing\\Selenium_Webdriver_Project\\Apache.xls");

XSSFWorkbook workbook1=new XSSFWorkbook(File1);
XSSFSheet Sheet1=workbook1.getSheetAt(0);  // Here "0" refers First WorkSheet. if "1" means its refer Seconds Sheet

Row row1=Sheet1.createRow(0);   //Here "0" indicates First Row.
searchcell=row1.createCell(0);  //Here "0" indicates first column of the specified row.

searchcell.setCellValue("Selenium");   //insert the "Selenium" text into that cell value
File1.close(); // close the input File Stream

FileOutputStream File2=new FileOutputStream("D:\\Selenium_Testing\\Selenium_Webdriver_Project\\Apache.xls");
workbook1.write(File2);
File2.close();

}
catch(Exception e)
{e.printStackTrace();}

}

}