Sunday, May 24, 2015

How to extract a number from alphanumeric text string.

str = "Guru1234"

for i = 1 to len(str)
  strValue = mid(str,i,1)
  if isnumeric(strValue) = True Then
      oTemp = oTemp & strValue
  End if
Next

msgbox oTemp

QTP - UFT Interview Questions

1.  What is keyword driven framwork
2.  Process of Automation scenarios
3.  How to retrieve maximum salary from the table
4.  What is JDBC? anwser its a server
5.  What is hybrid driven framework
6.  how to find object in Selenium ? Answer : By ID or Name or Xpath
7.  Criteria to automate manual scenarios?


Note : Post a comment for solution on any questions

Thank you for visiting blog

Saturday, May 23, 2015

Difference btween QTP and Selenium

     sn HP UFT (QTP)                           Selenium Better
1 Licensed Tool (costly) Open Source Tool ( no cost) Selenium
2 Supports for Desktop(windows) based (like java, .net, SAP, Oracle ERP…etc) and Web based applications only for web based applications QTP
3 easy to develop the scripts as it provides built in objects, methods..etc little complex to integrate third party tools and write programming from scratch QTP
4 scripts are developed only in QTP Window scripts are developed in different  IDEs like Visual Studio, Eclipse, Netbeans Selenium
5 Scripts are developed only using VBScript Scripts are developed using JAVA, C#,  Ruby, Perl, Phython,Groovy..etc Selenium
6 provides object repository so that it is easy to add objects and store the properties to recognize objects there is no object repository, all properties are written in the code only QTP
7 Tool can be integrated with HP QC for test management and defect reporting There are no tools to integrate QTP
8 Very good support as we buy the license Has to depend on forums, groups for help QTP
9 very good help documents to learn and explore no good help provided by the tool with examples and should explore from diff sources QTP
10 dedicated system needed to run the scripts, cannot interrup in middle the system used to run the script, we can perform other work and scripts are running in background Selenium
11 supports mainly for IE browser and also supports for firefox and chrome supports for all the browsers IE, FireFox, Chrome, Safari, Opera Selenium
12 supports only on windows OS supports on windows, Linux, Mac OS  

QTP Advanced Inteview Question


1.To create a folder
ResultFolderPath = "C:\Documents and Settings\sbulla\Desktop\SnapMD"
Set Fso = createobject("Scripting.FilesystemObject")
If Not Fso.FolderExists("ResultFolderPath") Then
Fso.CreateFolder ("srikanth")
End If

'##############################################################################

2. To find factorial number


dim f
f=1
n=inputbox("Enter a number")
for i=2 to n
f=f*i
next
msgbox f
'##############################################################################

3.To find the number in the string
str="1234abcd796don"
temp=""
For i=1 to len(str)
If IsNumeric(mid(str,i,1)) Then
temp=temp & mid(str,i,1)
End If
next
msgbox temp
'##############################################################################

4.To print triangle for given number range
s=""
for i=1 to 5
for j= 1 to i
s= s & j
msgbox & vbCrLf &s
Next
Next
'##############################################################################

5.To find only numbers from the given string str="1234abcd796don"
temp=""
For i=1 to len(str)
If IsNumeric(mid(str,i,1)) Then
temp=temp & mid(str,i,1)
End If
next
msgbox temp
'##############################################################################

6. To make rename a file
Set FSO = CreateObject("Scripting.FileSystemObject")
strFile ="C:\Documents and Settings\sbulla\Desktop\Home Address.txt"
strRename = "C:\Documents and Settings\sbulla\Desktop\Srikanth Home Address.txt"
If FSO.FileExists(strFile) Then
FSO.MoveFile strFile, strRename
End If
Set FSO = Nothing
'##############################################################################

7.To find number of repeatable words in the string
txt = "this is srikanthbulla"
cnt = 0
For i = 1 to len(txt)
if mid(txt,i,len("is")) = "is" then
cnt = cnt+1
End If
next
msgbox cnt
8.Another model
txt = "this is sriskanthbulla"
cnt = 0
P=1
while instr (P,txt,"is") >0
cnt = cnt+1
p= instr (P,txt,"is") +len("is")
msgbox cnt
End If
if cnt = 1 then
msgbox i
End If
next
'##############################################################################

9.To find length of given string
txt = "srikanthbulla"
i = 1
do
txt1 = mid(txt,i,1)
if txt1 <> "" then
i = i+1
else
Exit Do
End If
Loop until txt1 = ""
msgbox "length of given string is:"&i-1
'##############################################################################

10.'Add two 2X2 matrices
Dim Arry1(1,1),Arry2(1,1), tArry(1,1)
Arry1(0,0)=8
Arry1(0,1)=9
Arry1(1,0)=5
Arry1(1,1)=-1
Arry2(0,0)=2
Arry2(0,1)=3
Arry2(1,0)=4
Arry2(1,1)=3
for i = 0 to 1
for j = 0 to 1
tArry(0,0)=Arry1(0,0)+ Arry2(0,0)
tArry(0,1)=Arry1(0,1)+Arry2(0,1)
tArry(1,0)=Arry1(1,0)+Arry2(1,0)
tArry(1,1)=Arry1(1,1)+Arry2(1,1)
msgbox tArry(i,j)
next
next
'##############################################################################

11.'Find how many alpha characters present in a string?
Str=" Qua2li1ty 1234 Tho1ugh2t "
cnt=0
For i=1 to len(Str)
If not isnumeric (mid(Str,i,1)) then
cnt=cnt+1
End if
Next
Msgbox cnt
'##############################################################################

12.'Write a program to Convert an expression to a date
Dim StrDate,actualDate,StrTime,actualTime
StrDate = "October 19, 1962" ' Define date.
actualDate = CDate(StrDate) ' Convert to Date data type.
Msgbox actualDate
StrTime = "4:35:47 PM" ' Define time.
actualTime = CDate(StrTime) ' Convert to Date data type.
Msgbox actualTime
'##############################################################################

13.'Print all values line by line from an Array
Arry = array(1,2,3,4,"qtp","Testing")
For i= 0 to ubound(Arry)
temp=temp&vbnewline&Arry(i)
Next
msgbox temp
'##############################################################################

14.'Sort Array elements
Arry=Array(8,3,4,2,7,1,6,9,5,0)
For i = 0 to ubound(Arry)
For j = i+1 to ubound(Arry)
If Arry(i)>Arry(j) Then
tmp=Arry(i)
Arry(i)=Arry(j)
Arry(j)=tmp
End If
Next
Next
For k = 0 to ubound(Arry)
msgbox Arry(k)
Next
15.'Format Number to specified decimal places
'Num = 3.14159
'DecimaPlacestobeFormat=2
'Msgbox Round(Num , DecimaPlacestobeFormat)
Dim oNum
oNum=3.123
oDecNum=oNum- int(oNum)
msgbox oDecNum
'##############################################################################

16.To print fibbonacci number from given range
x=0
y=1
msgbox x
msgbox y
for i=1 to 100
z=x+y
x=y
y=z
msgbox z
next

'##############################################################################

16.'Write a program to insert 100values and to delete 50 values from an array
Dim Arry()
ReDim Arry(100)
For i = 0 to ubound(Arry)
'Message the total 100 Values
temp = temp&newline&Arry(i)
Next
Msgbox temp
ReDim preserve Arry(50)
For i = 0 to ubound(Arry)
temp = temp&newline&Arry(i)
'Message the Values after deleting 50 values
Next
Msgbox temp
'##############################################################################

17.'Join elements of an array as a string
Dim Str,Counter
Str="Quick Test Professional"
temp = split(Str," ")
for i = 0 to ubound(temp)
Msgbox temp(i) next Msgbox join(temp," ")
'##############################################################################

18.'Find whether current month is a long month
Dim CurrentMonth,currentYear,DaysinMonths
CurrentMonth = Month(date)
currentYear = Year(date)
DaysinMonths=Day(DateSerial(currentYear, CurrentMonth + 1, 0))
msgbox DaysinMonths&" Days in Current Month" If DaysinMonths=31 Then
Msgbox "Current Month is a long month"
else
Msgbox "Current Month is not a long month"
end if
'##############################################################################

19.'Finding whether a variable is an Array
Dim Arry()
if isarray(Arry) then
Msgbox "the given variable is an array"
Else
Msgbox "the given variable is not an array"
End if
'##############################################################################

20.'Find occurrences of a specific character in a string
Dim Str,Array,chr
Str="Quality Thaought"
chr="a"
Array=split(Str,chr)
msgbox ubound(Array)
'##############################################################################

21.To print a table of given range
n=inputbox("enter the number ")
For i=1 to n
For j=1 to 10
product=i*j
x= i&"*"&j&"="&product
table=table&vbnewline&x
Next
Next
msgbox table
'##############################################################################

22.'How Can we store array variable in dictionary in QTP?
TestStartTime = Now()
Dim a
a = array(2,3,4,5)
for i= 0 to ubound(a)
Set d = createobject("Scripting.Dictionary")
d.Add "mykey", a
msgbox d("mykey")(i)
TestEndTime=Now()
Next
durationoftestExecution=datediff("M",teststarttime,testendtime)
MSGBOX durationoftestExecution
'##############################################################################

23. To find week day
dob1 = #22-Aug-2013#
msgbox weekdayname(weekday(dob1))
msgbox Weekday("22-Aug-2013") '- returns the numeric representation of weekday.
'##############################################################################

24.'Display the Unique values and delete the duplicate values in an array using Vb Scripting
Dim arr, res(8), temp, count1
count1=0
temp=" "
arr=array(0,12,47,58,21,12,0,47,69)
For i= 0 to ubound(arr)
For j=i+1 to ubound(arr)

If arr(i)=arr(j) Then
temp=temp & arr(i)
msgbox temp
End If
Next
Next
'##############################################################################

25.'Length of a string without using InBuilt Functions using Vb Script
Dim arr()
On error resume next
str="My name is Srikanth bulla"
Set regex=new RegExp
regex.IgnoreCase=true
regex.Global=true
regex.pattern ="."
Set obj=regex.execute(str)
ReDim arr(obj.count-1)
i=0
For each temp in obj
arr(i)=temp.value
i=i+1
Next msgbox i
'##############################################################################

26.This function will Check or Uncheck the CheckBox in web page.
Obj: object name. Such as: Obj = Browser(xxx).Page(xxx)
Function SelectCheckBox(Obj,SelectCheckBox,On,Off)
Set oDesc = Description.Create()
oDesc("micclass").Value = "WebCheckBox"
Set Lists = oObj.ChildObjects(oDesc)
NumberOfLists = Lists.Count()
if SelectCheckBox = "All" then
For i = 0 To NumberOfLists - 1
Lists(i).Set On
Next
else
Lists(sSelectCheckBox).Set Off
End if
End Function
'##############################################################################

Other model:
Function SelectCheckBox(rootObj,chkNum)
On Error Resume Next
Dim chkNumb
chkNumb=Cint(chkNum)
Set cDescCheckBox1= Description.Create
cDescCheckBox1("type").value = "checkbox"
cDescCheckBox1("html tag").value = "INPUT"
'Set rootObject=Browser("Optus Online Store").Page("Optus Online Store").Frame("mainFrame")
Set objCheck = rootObj.ChildObjects(cDescCheckBox1)
If objCheck.count >0 Then
EnabledStatus=objCheck(chkNumb).getroproperty("Enabled")
Else Reporter.ReportEvent micFail,"Unable to retrieve check box items in the page","Extra
features are not populated"
End If
If EnabledStatus=0 Then
objCheck(chkNumb).set "ON"
On Error GoTo 0
If Err.Number<> 0 Then
Reprter.reporter 1,"Unable to select checkbox","Either incorrect check box or check box is disabled"
Err.Clear
End If Wait(3)
End If
End Function
'##############################################################################

27.reverse each and evry string from mail string.
txt = "this is srikanthbulla"
cnt = 0
For i = 1 to len(txt)
if mid(txt,i,1)) = "" then
temp=mid(txt,1,i)
msgbox strrev(temp)
txt=replace(txt,temp,"")
End If
next
28.Other model
temp=split(txt," ")
for i=1 to ubound(temp)
msgbox strrev(temp(i))
'##############################################################################

28. Find numaric value in text file.
Set fso=Createobject("scripting.filesystemobject")
Set File =fso.opentextfile("Path")
while File.atendofline<>true
str=File.readline
For i=1 to len(str)
If IsNumeric(mid(str,i,1)) Then
temp=temp & mid(str,i,1)
End If
next
msgbox temp
'##############################################################################

29.'To clear temporary Internet files
Set WshShell = CreateObject("WScript.Shell")
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8"
'To clear browsing cookies WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProces 2"
'To Clear Browsing History
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1"
'##############################################################################

30.to select last 10 check boxs in web table in g mail
Row= Browser("Title:Google").Page("Title:Gmail").webtable("Title:Inbox").rowcount for i= 1 to row
Col= Browser("Title:Google").Page("Title:Gmail").webtable("Title:Inbox").columncount(i)
for j= 1 to Col
CboxCount = Browser("Title:Google").Page("Title:Gmail").webtable("Title:Inbox").childitem
count(i,j,"webcheckbox")
for k= CboxCount TO 10 STEP-1
Set Cboxcheck =Browser("Title:Google").Page("Title:Gmail").webtable("Title:Inbox").childitem (i,j,"webcheckbox",K)
IF Cboxcheck.visible = true then
Cboxcheck.set"on"
30.How to handle the dynamically changed objects in google search result set
Browser("Title:Google").Page("Title:Google").webedit("Title:Google").set"123"
Browser("Title:Google").Page("Title:Google").webbutton("Title:Google").click
Browser("Title:Google").Page("Title:Google").sync
set obj=description.create
obj("micclass).value="Link"
obj("Attached text).value=".*"
Set child=Browser("Title:Google").Page("Title:Google").childobjects(obj)
for i= 1 to child.count-1
child(i).click
'##############################################################################

Filesystemobject:
Filesystemobject is an object model which is used to handle the drives, folders, and files of a system or server.
'Create a filesystemObject
Set fso=createobject("Scripting.FileSystemObject")
'Create a non existing file "qtptest.txt " with overwrite option as True
Set qfile1=fso.CreateTextFile("C:\qtptest.txt")
'Output --> New File "qtptest.txt " is created
'Close the files
qfile1.Close
'Release the allocated objects
Set qfile1=nothing 
'##############################################################################

Set fso=createobject("Scripting.FileSystemObject")
'File to be copied Sourcefile="C:\copy.txt"'Dest folder where the file has to be copied
Destination="D:\final1\"
'If the destination doesnot exist then create the destination folder
If fso.FolderExists(Destination) = false Then
fso.CreateFolder (Destination)
End If
'Copy the file
fso.CopyFile Sourcefile,Destination,True
Set fso=nothing
'Delete the file
Set fso=createobject("Scripting.FileSystemObject")
'File to be deleted. Sourcefile="C:\copy.txt" 'Delete the file
fso.DeleteFile Sourcefile
Set fso=nothing
'CreateFolder
Set fso=createobject("Scripting.FileSystemObject")
'Folder to be created Foldername="D:\Folder_create"
'If the folder doenot exst then create the folder
If fso.FolderExists(Foldername) = false Then
fso.CreateFolder (Foldername)
End If
Set fso=nothing
'##############################################################################

'Copy Folder
Set fso=createobject("Scripting.FileSystemObject")
'Folder to be created SourcePath="D:\Folder_create" DestinationPath="D:\Destination\"
'If the folder doesnot exst then create the folder
If fso.FolderExists(DestinationPath) = false Then
fso.CreateFolder (DestinationPath)
End If
fso.CopyFolder SourcePath,DestinationPath,True
Set fso=nothing
'##############################################################################

Set fso=createobject("Scripting.FileSystemObject")
'Folder to be created SourcePath="D:\Folder_move" DestinationPath="D:\Destination\"
'If the folder doesnot exst then create the folder
If fso.FolderExists(DestinationPath) = false Then
fso.CreateFolder (DestinationPath)
End If
fso.MoveFolder SourcePath,DestinationPath
Set fso=nothing
'Delete Folder
Set fso=createobject("Scripting.FileSystemObject")
'Folder to be deleted. FolderDel="D:\final1" 'Delete the folder
fso.DeleteFolder(FolderDel)
'##############################################################################

'Drive existance
Set fso=createobject("Scripting.FileSystemObject")
'The drive to check the existence drivepath="D:\"
If fso.DriveExists(drivepath) then
msgbox "Drive Exists" Else Msgbox "Drive doesnot Exist"
End If
Set fso=nothing
'##############################################################################
'File existance Set fso=createobject("Scripting.FileSystemObject") 'The file to check the existence filepath="D:\qtptest.txt" If fso.FileExists(filepath) then msgbox "File Exists" Else Msgbox "File doesnot Exist" End If
'##############################################################################

'Folder existance
Set fso=createobject("Scripting.FileSystemObject")
'The Folder to check the existence
folderpath="D:\qtp"
If fso.FolderExists(folderpath) then
msgbox "Folder Exists"
Else
Msgbox "Folder doesnot Exist"
End If
Set fso=nothing
'##############################################################################

'Get drive:
Set fso=createobject("Scripting.FileSystemObject")
'Drive for getting details Sourcefile="C:\"
Set get_drv=fso.GetDrive(Sourcefile)
'Some of the following details can be retrieved from a drive
msgbox get_drv.AvailableSpace
Msgbox get_drv.DriveLetter
msgbox get_drv.DriveType
msgbox get_drv.FileSystem
msgbox get_drv.FreeSpace
msgbox get_drv.Path
Msgbox get_drv.RootFolder
Msgbox get_drv.SerialNumber
Msgbox get_drv.TotalSize
Set fso=nothing
'##############################################################################

'Get Folder:
Set fso=createobject("Scripting.FileSystemObject")
'Folder for getting details
Sourcefolder="D:\QTP"
Set get_folder=fso.GetFolder(Sourcefolder)
'get the subfolders count in a folder
Set get_subfolder=get_folder.SubFolders
For each sfile in get_subfolder
'Get the name of each folder
Msgbox sfile.name
Next
'##############################################################################
'Get File: Set fso=createobject("Scripting.FileSystemObject") 'File for getting details Sourcefile="D:\qtptest.txt" Set get_file=fso.GetFile(Sourcefile) 'Some of the following details can be retrieved from a file msgbox get_file.DateCreated msgbox get_file.DateLastAccessed msgbox get_file.DateLastModified msgbox get_file.ParentFolder msgbox get_file.Path
'##############################################################################
Set fso=nothing 'Read method: Set fso=createobject("Scripting.FileSystemObject") 'Open the file "qtptest.txt" in writing mode. Set qfile=fso.OpenTextFile("C:\qtptest.txt",2,True) 'write contents to the file into two newlines qfile.Writeline "Welcome to the World of QTP" qfile.Writeline "the file name is qtptest.txt" 'Open the file "qtptest.txt" in reading mode. Set qfile=fso.OpenTextFile("C:\qtptest.txt",1,True) 'Read characters from the file Msgbox qfile.Read(10) 'Output --> "Welcome to" will be read 'Close the files qfile.Close 'Release the allocated objects Set qfile=nothing Set fso=nothing
'##############################################################################
'Readall method: Set fso=createobject("Scripting.FileSystemObject") 'Open the file "qtptest.txt" in writing mode. Set qfile=fso.OpenTextFile("C:\qtptest.txt",2,True) 'write contents to the file into two newlines qfile.Writeline "Welcome to the World of QTP" qfile.Writeline "the file name is qtptest.txt" 'Open the file "qtptest.txt" in reading mode. Set qfile=fso.OpenTextFile("C:\qtptest.txt",1,True) 'Read the entire contents of priously written file Msgbox qfile.ReadAll 'Output --> Displays the entire file. 'Close the files qfile.Close Set fso=createobject("Scripting.FileSystemObject") 'Open the file "qtptest.txt" in writing mode. Set qfile=fso.OpenTextFile("C:\qtptest.txt",2,True) 'write contents to the file into two newlines qfile.Writeline "Welcome to the World of QTP" qfile.Writeline "the file name is qtptest.txt" 'Open the file "qtptest.txt" in reading mode. Set qfile=fso.OpenTextFile("C:\qtptest.txt",1,True) 'Read the entire contents of priously written file Do while qfile.AtEndOfStream <> true Msgbox qfile.ReadLine 'Output --> The file will be read line line by line. Loop 'Write method: Set fso=createobject("Scripting.FileSystemObject") 'Open the file "qtptest.txt" in writing mode. Set qfile=fso.OpenTextFile("C:\qtptest.txt",2,True) 'write contents to the file into a single line qfile.Write "Welcome to the World of QTP" qfile.Write "the file name is qtptest.txt" 'Open the file "qtptest.txt" in reading mode. Set qfile=fso.OpenTextFile("C:\qtptest.txt",1,True) 'Read the entire contents of priously written file Do while qfile.AtEndOfStream <> true 'Output --> The file will contain the above written content in single line. Msgbox qfile.ReadLine Loop
'##############################################################################
' Writeline method: Set fso=createobject("Scripting.FileSystemObject") 'Open the file "qtptest.txt" in writing mode. Set qfile=fso.OpenTextFile("C:\qtptest.txt",2,True) 'write contents to the file into two newlines qfile.Writeline "Welcome to the World of QTP" qfile.Writeline "the file name is qtptest.txt" 'Open the file "qtptest.txt" in reading mode. Set qfile=fso.OpenTextFile("C:\qtptest.txt",1,True) 'Read the entire contents of priously written file Do while qfile.AtEndOfStream <> true 'Output --> The file will contain the above written content line by line. Msgbox qfile.ReadLine Loop ' WriteBlankLines method: Set fso=createobject("Scripting.FileSystemObject") 'Open the file "qtptest.txt" in writing mode. Set qfile=fso.OpenTextFile("C:\qtptest.txt",2,True) 'write contents to the file into two newlines qfile.Writeline "Welcome to the World of QTP" 'will insert 4 new blank lines qfile.WriteBlankLines(4) qfile.Writeline "the file name is qtptest.txt" 'Open the file "qtptest.txt" in reading mode. Set qfile=fso.OpenTextFile("C:\qtptest.txt",1,True) 'Read the entire contents of priously written file Do while qfile.AtEndOfStream <> true 'Output --> The file will be read file line by line. ' AtEndOfLine method:
'##############################################################################
Excel object Create an Excel File: 'Create a new Microsoft Excel object Set myxl = createobject("excel.application") 'To make Excel visible myxl.Application.Visible = true myxl.Workbooks.Add wait 2 'Save the Excel file as qtp.xls myxl.ActiveWorkbook.SaveAs "D:\qtp.xls" 'close Excel myxl.Application.Quit Set myxl=nothing
'##############################################################################
Create an Excel File , Enter some data , Save the Excel and close the Excel: Set myxl = createobject("excel.application") myxl.Workbooks.Open "D:\qtp.xls" myxl.Application.Visible = true 'this is the name of Sheet in Excel file "qtp.xls" where data needs to be entered set mysheet = myxl.ActiveWorkbook.Worksheets("Sheet1") mysheet.cells(1,1).value ="Name" mysheet.cells(1,2).value ="Age" mysheet.cells(2,1).value ="Ram"
'##############################################################################
Read the data from Excel File: Set myxl = createobject("excel.application") myxl.Workbooks.Open "D:\qtp.xls" myxl.Application.Visible = true
'##############################################################################
'this is the name of Sheet in Excel file "qtp.xls" where data needs to be entered set mysheet = myxl.ActiveWorkbook.Worksheets("Sheet1") 'Get the max row occupied in the excel file Row=mysheet.UsedRange.Rows.Count 'Get the max column occupied in the excel file Col=mysheet.UsedRange.columns.count 'To read the data from the entire Excel file For i= 1 to Row For j=1 to Col Msgbox mysheet.cells(i,j).value Next Next
'##############################################################################
Compare Two Excel sheets Cell by cell: temp=0 Set myxl = createobject("excel.application") 'To make Excel visible myxl.Visible = True 'Open a workbook "qtp1.xls" Set Workbook1= myxl.Workbooks.Open("C:\qtp1.xls") 'Open a workbook "qtp2.xls" Set Workbook2= myxl.Workbooks.Open("C:\qtp2.xls") Set mysheet1=Workbook1.Worksheets("Sheet1") Set mysheet2=Workbook2.Worksheets("Sheet1") 'Compare two sheets cell by cell For Each cell In mysheet1.UsedRange 'Highlights the cell if cell values not match If cell.Value <>mysheet2.Range(cell.Address).Value Then 'Highlights the cell if cell values not match cell.Interior.ColorIndex = 3 temp=1 End If Next If temp=0 Then Msgbox "No Mismach exists" End If
'##############################################################################
⇒Search for Particular value in Excel: Set myxl = createobject("excel.application") myxl.Workbooks.Open "D:\qtp.xls" myxl.Application.Visible = true 'This is the name of Sheet in Excel file "qtp.xls" where data needs to be entered set mysheet = myxl.ActiveWorkbook.Worksheets("Sheet1") With mysheet.UsedRange For each cell in mysheet.UsedRange ' compare with the expected data If cell="Ram" then 'make the cell with color if it finds the data cell.Interior.ColorIndex = 40 End If next End With 'Save the Workbook myxl.ActiveWorkbook.Save
'##############################################################################
Copy an Excel sheet to another Excel sheet: Set myxl = createobject("excel.application") 'To make Excel visible myxl.Visible = True 'Open a workbook "qtp1.xls" Set Workbook1= myxl.Workbooks.Open("C:\qtp1.xls") 'Open a workbook "qtp2.xls" Set Workbook2= myxl.Workbooks.Open("C:\qtp2.xls") 'Copy the used range of workbook "qtp1.xls" Workbook1.Worksheets("Sheet1").UsedRange.Copy 'Paste the copied values in above step in the A1 cell of workbook "qtp2.xls" Workbook2.Worksheets("Sheet1").Range("A1").PasteSpecial Paste =xlValues
'##############################################################################
Addsheet Method: Description: Adds the specified sheet to the run-time Data Table and returns the sheet so that you can directly set properties of the new sheet in the same statement. Syntax: DataTable.AddSheet(SheetName) Example: 'Create a datatable sheet during Run time.This sheet will be available during run time only. 'We can view this sheet in Result Summaryunder section "Run Time data Table". datatable.AddSheet("Qtpworld") 'To add column name and a default value under them. datatable.GetSheet("Qtpworld").AddParameter "name","Ram" datatable.GetSheet("Qtpworld").AddParameter "age","18"
'##############################################################################
DeleteSheet Method: Description: Deletes the specified sheet from the run-time Data Table. Syntax: DataTable.DeleteSheet SheetID Example: 'Create a datatable sheet during Run time.This sheet will be available during run time only. 'We can view this sheet in Result Summary under section "Run Time data Table" . datatable.AddSheet("Qtpworld") 'To delete datatable sheet datatable.DeleteSheet("Qtpworld") datatable.DeleteSheet("Global") wait 3
'##############################################################################
Data table Methods: ⇒Import Method: Description: Imports the specified Microsoft Excel file to the run-time Data Table. Syntax: DataTable.Import(FileName) ⇒Export Method: Description: Saves a copy of the run-time Data Table in the specified location. Syntax: DataTable.Export(FileName) datatable. Export "C:\qtptest.xls" 'To get the total count of QTP datatable sheets msgbox datatable.GetSheetCount ImportSheet Method: Description: Imports a sheet of a specified file to a specified sheet in the run-time Data Table. The data in the imported sheet replaces the data in the destination sheet (see SheetDest argument). Syntax: DataTable.ImportSheet(FileName, SheetSource, SheetDest) ExportSheet Method: Description: Exports a specified sheet of the run-time Data Table to the specified file. Syntax: DataTable.ExportSheet(FileName, DTSheet) 'Create a sheet "Sheet1" in qtp datatable.AddSheet "Sheet1" datatable.ImportSheet "C:\qtpsheet.xls","Sheet1","Sheet1" 'Add a column "Result" for displaying result in qtp sheet datatable.GetSheet("Sheet1").AddParameter "Result","" wait 2 'Apply the logic: if age is less than 18 then the guy is " Minor" else "Major" row =datatable.GetSheet("Sheet1").GetRowCount For i = 1 to row datatable.GetSheet("Sheet1").SetCurrentRow(i) If datatable.Value("Age","Sheet1") > 18 Then datatable.Value("Result","Sheet1") = "Major" Else datatable.Value("Result","Sheet1") = "Minor" End If Next 'Export the qtp sheet "Sheet1" bak to external excel Datatable.ExportSheet "C:\qtpsheet.xls","Sheet1" ' After exporting you can see that the excel file now has been updated with result
'##############################################################################
⇒GetSheet Method: Description: Returns the specified sheet from the run-time Data Table. Syntax: DataTable.GetSheet(SheetID) Example given below '############################################################################## ⇒GetSheetCount Method: Description: Returns the total number of sheets in the run-time Data Table. Syntax: DataTable.GetSheetCount Example given below
'##############################################################################
⇒GetCurrentRow Method: Description: Returns the current (active) row in the first sheet in the run-time Data Table (global sheet). Syntax: DataTable.GetCurrentRow Example given below
'##############################################################################
⇒GetRowCount Method: Description: Returns the total number of rows in the longest column in the first sheet in the run-time Data Table (global sheet). Syntax: DataTable.GetRowCount Example given below
'##############################################################################
⇒SetCurrentRow Method: Description: Sets the specified row as the current (active) row in the run-time Data Table. Syntax: DataTable.SetCurrentRow(RowNumber) Example datatable.AddSheet("Qtpworld") 'To add column name and a default value under them. datatable.GetSheet("Qtpworld").AddParameter "name","Ram" datatable.GetSheet("Qtpworld").AddParameter "age","18" 'Enter data into second row of datatsheet "Qtpworld" datatable.GetSheet("Qtpworld").SetCurrentRow(2) datatable.Value("name","Qtpworld")="Ramu" datatable.Value("age","Qtpworld")="23" 'total number of datasheets in the run-time Data Table Msgbox datatable.GetSheetCount 'Get the max used range of the datasheet row=datatable.GetSheet("Qtpworld").GetRowCount 'Loop to read all the data in the datasheet "Qtpworld" For Drow= 1 to row datatable.GetSheet("Qtpworld").SetCurrentRow(Drow) Msgbox datatable.Value("name","Qtpworld") Msgbox datatable.Value("age","Qtpworld") Msgbox "Current Row is: " & datatable.GetSheet("Qtpworld").GetCurrentRow Next
'##############################################################################
Database Connections ADO(ActiveX Data Objects) Connection object: The ADO(ActiveX Data Objects) Connection object is used to create a connection to a data source. Through this connection, you can access and manipulate a database. ADO Recordset object ? The ADO Recordset object is used to hold a set of records from a database table.To be able to read database data, the data should be loaded into a recordset.
'##############################################################################
⇒QTP Scripts for connecting to MS Access: Option Explicit Dim con,rs Set con=createobject("adodb.connection") Set rs=createobject("adodb.recordset") con.open "Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\mydatabase.mdb;Uid=Admin;Pwd=;" rs.open "select * from emp",con Do while not rs.eof VbWindow("Form1").VbEdit("val1").Set rs.fields("v1") VbWindow("Form1").VbEdit("val2").Set rs.fields("v2") VbWindow("Form1").VbButton("ADD").Click rs.movenext Loop
'##############################################################################
⇒QTP Script for connecting to sqlserver: Option Explicit Dim con,rs Set con=createobject("adodb.connection") Set rs=createobject("adodb.recordset") con.open"Driver={SQL Server};server=MySqlServer;uid=MyUserName;pwd=MyPassword;database=pubs" rs.open "select * from emp",con Do while not rs.eof VbWindow("Form1").VbEdit("val1").Set rs.fields("v1") VbWindow("Form1").VbEdit("val2").Set rs.fields("v2") VbWindow("Form1").VbButton("ADD").Click rs.movenext Loop
'##############################################################################
⇒QTP Script for connecting to oracle: Option Explicit Dim con,rs Set con=createobject("adodb.connection") Set rs=createobject("adodb.recordset") con.open "Driver={Microsoft ODBC for Oracle};Server=QTPWorld; Uid=your_username;Pwd=your_password;" rs.open "select * from emp",con Do while not rs.eof VbWindow("Form1").VbEdit("val1").Set rs.fields("v1") VbWindow("Form1").VbEdit("val2").Set rs.fields("v2") VbWindow("Form1").VbButton("ADD").Click rs.movenext Loop
'##############################################################################
⇒QTP Script for connecting to Excel: Option Explicit Dim con,rs Set con=createobject("adodb.connection") Set rs=createobject("adodb.recordset") con.open "DRIVER={Microsoft Excel Driver (*.xls)};DBQ=C:\TestStatus.xls;Readonly=True" rs.open "SELECT count(*) FROM [Status$] where Status = 'Failed' ",con Msgbox rs(0) 'Release objects Set rs= nothing Set con= nothing The difference between QTP 10 and 11.: 1. Identify objects Using CSS and Xpath 2. Results viewer with pie charts, statics for both current and previous test runs, summary page. 3. Normal object identification method has been updated with "Visual Relation Identifier" in addition to "ordinal identifier" features in which object identification which will depend on relation to neighboring objects and will be helpful to overcome weakness of ordinal identification feature only in QTP10. 4. "LoadFunctionLibrary" - load function library at any step of runs instead of starting of run execute file. 5. Regular expression creation will be very easy 6. Web 2.0 toolkit applications support. 7. Support for recording using Firefox 8. New Sliverlight Add-in is supported to test objects in sliverlight 2 9. Regular Expression evaluator In QTP 10 you will not find these features . This is the difference between QTP 10 and 11. You may also like -
'##############################################################################
Working with WebTable in QTP: A Table containing a number of rows and columns. A Table containing any kind of information in cells in combinations of rows and columns. Keywords for Web Table are given below. Rows Columns Cell Cell Data RowCount ColumnCount GetCellData GetRowWithCellText CellText TextCellExist ' To get data in a particular cell in the data table strData= Browser("Google").Page("title:=.*").WebTable(“name:=TTable").GetCellData(r,c) MsgBox strData Next
'##############################################################################
'Using childObject method to find objects of a particular type within a webtable Public Function func_findObjectinaWebTable(strObjType) Set objDesc=Description.Create objDesc("micclass").value=strobjType set objChild=Browser("Google").Page("title:=.*").WebTable(“name:=TTa").ChildObjects(objDesc) func_findObjectinaWebTable = objChild.count MsgBox func_findObjectinaWebTable End Function
'##############################################################################
'Using HTML DOM to get count of objects in a webtable Public Function func_findObjectinaWebTable(strTagName) set objChild= Browser("Google").Page("title:=.*").WebTable(“name:=TestTable").object.getElementsbyTagName(strTagName) func_findObjectinaWebTable = objChild.length End Function
'##############################################################################
'Using ChildItemCount and childItem in webtable to extract information Public Function func_findObjectinaWebTable(strObjType,introw,intCol) ob0jChildCnt=Browser("Google").Page("title:=.*").WebTable(“name:=TestTable,"index:=0").ChildItemCount(introw,intcol,strobjType) If objChildCnt >0 Childitem will return object oftype defined in arguments for childitem Set ChldItm = Browser("Google").Page("title:=.*").WebTable(“name:=TestTable,"index:=0").ChildItem(introw,intcol,strobjType,0) If (strobjType = "Link" or strobjType ="WebEdit") Then ChldItm.Click ElseIf(stobjType = "WebCheckBox") Then ChldItm.Set "ON" End If End Function CellText method works as same as GetCellData method. Eg.:Msgbox Browser("name:=qtp").WebTable("index:=0").CellText(1,1)
'##############################################################################
'Get Row no# with CellText Ex:In my table , there are rows of data where my name could be seen. So wanted to get the number of a table where my name exists. And thus this code works there. RowNumber = Browser("").Page("").WebTable("").GetRowWithCellText("Jackiechen")
'##############################################################################
TextCellExist method checks whether a text exists in a cell or not. It returns true, if the input text exists in the cell, else it returns false. Rather than using GetCellData method and then comparing the result with the input text, we can achieve it using this simple method. Msgbox Browser("name:=qtp").WebTable("index:=0").TextCellExist(1,1,"jackie")
'##############################################################################
' To Find number of rows and columns in a web table intRowCnt=Browser("Google").Page("title:=.*").WebTable(“name:= Ttable").RowCount For r=1 to intRowCnt intColCnt=Browser("Google").Page("title:=.*").WebTable(“name:=TTable").ColumnCount(r) For c=1 to intColCnt
'##############################################################################
'To get the Column headers of a table so as to write these headers as Column Names to a excel sheet DataTable.AddSheet "MySheet" Set oTable=Browser("Gmail: Email from Google").Page("Gmail - Inbox").WebTable(“t") RC=oTable.RowCount CC=oTable.ColumnCount(1) Print "RC " & RC Print "CC " & CC For i=1 to CC ColName=oTable.GetCellData(1,i) Print "ColName"& ColName DataTable.GetSheet("MySheet").AddParameter ColName,""
'##############################################################################
'To the required cell data from a web table and write these values to an excel sheet For i=1 to RC Datatable.GetSheet("MySheet").SetCurrentRow(i) CC=oTable.ColumnCount(i) For j=1 to CC CData=oTable.GetCellData(i,j) DataTable.GetSheet("MySheet").GetParameter(j).value=CData Print "CData" & CData Next Next
'##############################################################################
'Reading an excel sheet and passing cell data as a link PCMySheet=DataTable.GetSheet("MySheet").GetParameterCount RCMySheet=DataTable.GetSheet("MySheet").GetRowCount For j=1 to RCMySheet For i=1 to PCMySheet CValue=DataTable.GetSheet("MySheet").GetParameter(i).ValueByRow(j) 'RCValue=DataTable.GetSheet("MySheet").GetParameter(3).ValueByRow(j) Print "CValue"& CValue Next Next For j=1 to RCMySheet For i=1 to PCMySheet CValue=DataTable.GetSheet("MySheet").GetParameter(i).ValueByRow(j) RCValue=DataTable.GetSheet("MySheet").GetParameter(3).ValueByRow(j) Print "RCValue"& RCValue 'Next Next
'##############################################################################
'To get the no# of web tables existing on page To the get all web tables names, text, rowcount, columncount Set ObjTable=Description.Create ObjTable("html tag").value="TABLE" ObjTable("text").value=".*" Set TotObjTable=Browser("Gmail: Email from Google").Page("Gmail - Inbox").ChildObjects(ObjTable) NoOfTables=TotObjTable.count Print "NoOfTables" & NoOfTables For i=0 to NoOfTables-1 TabName=TotObjTable(i).GetROProperty("name") TabCols=TotObjTable(i).GetROProperty("cols") TabRows=TotObjTable(i).GetROProperty("rows") TabText=TotObjTable(i).GetROProperty("text") Print "TabName"& TabName Print "TabCols"& TabCols Print "TabRows"& TabRows Print "TabText"& TabText Next
'##############################################################################
'Descriptive program with respect to a Web Table Set ObjTable=Description.Create ObjTable("html tag").value="TABLE" ObjTable("text").value=".*" Set TotObjTable=Browser("Gmail: Email from Google").Page("GmailInbox").ChildObjects(ObjTable) NoOfTables=TotObjTable.count Print "NoOfTables" & NoOfTables For i=0 to NoOfTables-1 TabName=TotObjTable(i).GetROProperty("name") TabCols=TotObjTable(i).GetROProperty("cols") TabRows=TotObjTable(i).GetROProperty("rows") TabText=TotObjTable(i).GetROProperty("text") Print "TabName"& TabName Print "TabCols"& TabCols Print "TabRows"& TabRows Print "TabText"& TabText Next
'##############################################################################
1. How to find third or nth maximum salary from salary table? SELECT * FROM Employee Emp1 WHERE (N-1) = (SELECT COUNT(DISTINCT(Emp2.Salary)) FROM Employee Emp2 WHERE Emp2.Salary > Emp1.Salary) 2.SELECT TOP 1 salary FROM (SELECT TOP 3 salary FROM employees ORDER BY salary DESC) AS emp ORDER BY salary ASC 3.how to delete duplicate rows in sql server DELETE FROM emp WHERE empid IN ( SELECT empid FROM emp GROUP BY empid HAVING ( COUNT(empid) > 1 )