Sunday, April 17, 2011

QTP VB Script Practice Examples




Scripttoweblisttofoundtheitem
x= Input Box("enter the state")
x=browser("Register:MercuryTours").Page("Register:Mercury Tours").WebList("country").GetROProperty("Items Count")
For i=1 to x
m=browser("Register:MercuryTours").Page("Register:Mercury Tours").WebList("country").GetItem(i)
If m="INDIA" Then
MsgBox "item is found in the list:"&i+1
exit for
End If
Next
program to retirve the application validation
DataTable.ImportSheet "C:\testing.xls","sheet1","Action1"
n=DataTable.GetSheet("Action1").GetRowCount
For i=1 to n
DataTable.SetCurrentRow(i)
Window("Flight Reservation").WinButton("Button").Click
Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
window("FlightReservation").Dialog("OpenOrder").WinEdit("Edit").SetDataTable("order","ction1")
window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
c=window("Flight Reservation").WinEdit("Name:").GetROProperty("text")
t=window("Flight Reservation").WinEdit("Tickets:").GetROProperty("text")
DataTable("cname","Action1")=c
DataTable("tickets","Action1")=t
Next
DataTable.ExportSheet "e:\data.xls","Action1"
datatable count row
DataTable.ImportSheet "C:\testing.xls","sheet1","Action1"
n=DataTable.GetSheet("Action1").GetRowCount
For i=1 to n
DataTable.SetCurrentRow(i)
Next
MsgBox n
datatable to validate the application
SystemUtil.Run"C:\ProgramFiles\HP\QuickTest Professional\samples\flight\app\flight4a.exe"
dialog("Login").WinEdit("Agent Name:").Set DataTable("uid",1)
dialog("Login").WinEdit("Password:").Set DataTable("pwd",1)
dialog("Login").WinButton("OK").Click
If window("Flight Reservation").Exist(10) Then
window("Flight Reservation").Close
DataTable("result",1)="pass"
else
x=dialog("Login").Dialog("FlightReservations").Static("Passwordmustbeatleast").GetROProperty("text")
dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click
dialog("Login").WinButton("Cancel").Click
DataTable("result",1)="fail"
DataTable("status")=x
End If
notepad data
Dim f,fs
Set fs=CreateObject("scripting.filesystemobject")
Set f=fs.CreateTextFile("C:\testing.txt")
For i=1 to 5
x=inputbox("enter the data from notepad")
f.WriteLine x
Next
f.Close
find the single method to read and write the data from
Dim f,fs,x
Set fs=CreateObject("scripting.filesystemobject")
Set f=fs.CreateTextFile("C:\testing.txt")
For i=1 to 5
x=inputbox("enter the data from notepad")
f.WriteLine x
Next
SystemUtil.Run "C:\testing.txt"
Set fs=CreateObject("scripting.filesystemobject")
Set f=fs.OpenTextFile("C:\testing.txt")
x=f.ReadAll
print x

Vb script examples

1) Write a program for finding out whether the given year is a leap year or not?

Dim xyear
xyear=inputbox ("Enter Year")
If xyear mod 4=0 Then
msgbox "This is a Leap year"
Else
msgbox "This is NOT"
End If

2) Write a program for finding out whether the given number is, Even number or Odd number?

Dim num
num=inputbox ("Enter a number")
If num mod 2=0 Then
msgbox "This is a Even Number"
Else
msgbox "This is a Odd Number"
End If

3) Read two numbers and display the sum?

Dim num1,num2, sum
num1=inputbox ("Enter num1")
num2=inputbox ("Enter num2")
sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion require
msgbox ("Sum is " &sum)

4) Read P,T,R values and Calculate the Simple Interest?

Dim p,t, r, si
p=inputbox ("Enter Principle")
t=inputbox ("Enter Time")
r=inputbox ("Enter Rate of Interest")
si= (p*t*r)/100 ' p= principle amount, t=time in years, r= rate of interest
msgbox ("Simple Interest is " &si)

5) Read Four digit number, calculate & display the sum of the number or display Error message if the number is not a four digit number?

Dim num, sum
num=inputbox ("Enter a Four digit number")
If Len(num) = 4 Then
sum=0
sum=sum+num mod 10
num=num/10
num= left (num, 3)
sum=sum+num mod 10
num=num/10
num= left (num, 2)
sum=sum+num mod 10
num=num/10
num= left (num, 1)
sum=sum+num mod 10
msgbox ("Sum is " &sum)
else
msgbox "Number, you entered is not a 4 digit number"
End If

6) Read any Four-digit number and display the number in reverse order?

Dim num,rev
num= inputbox("Enter a number")
If len(num)=4 Then
rev=rev*10 + num mod 10
num=num/10
num= left(num,3)
rev=rev*10 + num mod 10
num=num/10
num= left(num,2)
rev=rev*10 + num mod 10
num=num/10
num= left(num,1)
rev=rev*10 + num mod 10
msgbox "Reverse Order of the number is "&rev
Else
msgbox "Number, you entered is not a 4 digit number"
End If

7) Read 4 subjects marks; calculate the Total marks and grade?

a) If average marks Greater than or equal to 75, grade is Distinction
b) If average marks Greater than or equal to 60 and less than 75 , then grade is First
c) If average marks Greater than or equal to 50 and less than 60 , then grade is Second
d) If average marks Greater than or equal to 40 and less than 50 , then grade is Third
e) Minimum marks 35 for any subject, otherwise 'no grade fail')

Dim e,m,p,c, tot
e=inputbox ("Enter english Marks")
m=inputbox ("Enter maths Marks")
p=inputbox ("Enter physics Marks")
c=inputbox ("Enter chemistry Marks")
tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c)
msgbox tot
If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=300 Then
msgbox "Grade is Distinction"
else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=240 and tot<300 Then msgbox "Grade is First" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=200 and tot<240 Then msgbox "Grade is Second" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=160 and tot<200 Then
msgbox "Grade is Third"
else
msgbox "No Grade, Fail"
End If
End If
End If
End If

8) Display Odd numbers up to n?

Dim num,n
n=Inputbox ("Enter a Vaule")
For num= 1 to n step 2
msgbox num
Next

9) Display Even numbers up to n?

Dim num,n
n=Inputbox ("Enter a Vaule")
For num= 2 to n step 2
msgbox num
Next

10) display natural numbers up to n and write in a text file?

Dim num, n, fso, myfile
n= inputbox ("Enter any Value")
num=1
For num= 1 to n step 1
Set fso= createobject ("scripting.filesystemobject")
set myfile=fso.opentextfile ("d:\sureshbabu.txt", 8, true)
myfile.writeline num
myfile.close
Next

11) Display Natural numbers in reverse order up to n?

Dim num,n
n=Inputbox ("Enter a Vaule")
For num=n to 1 step -1
msgbox num
Next

12) Display Natural numbers sum up to n? (Using For...Next Loop)

Dim num, n, sum
n= inputbox ("Enter a Value")
sum=0
For num= 1 to n step 1
sum= sum+num
Next
msgbox sum

13) Display Natural numbers sum up to n? (using While...Wend Loop)

Dim num, n, sum
n= inputbox ("Enter a Value")
While num <=cdbl (n)
sum= sum+num
num=num+1
Wend
msgbox sum

14) Display Natural numbers sum up to n? (Using Do...Until...Loop)

Dim num, n, sum
n= inputbox ("Enter a Value")
sum=0
num=1
Do
sum= sum+num
num=num+1
Loop Until num =cdbl (n+1)
msgbox sum

15) Write a Function for Natural Numbers sum up to n?

Function NNumCou (n)
Dim num, sum
sum=0
For num= 1 to n step 1
sum= sum+num
Next
msgbox sum
End Function

Function Library Example


'Global Variables Function Library
Public StrUrl,StrUName,StrPword

StrUrl="http://localhost:8080/mtours"
StrUName="User1003"
StrPword="test"
Function Library
Function LaunchApp(Url)
Systemutil.Run Url
If Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").Exist(10) Then
Reporter.ReportEvent micPass ,"Launch App Check","Application Launched Successfully"
LaunchApp="Pass"
Else
Reporter.ReportEvent micFail ,"Launch App Check","Application not launched successfully for valid Url"
LaunchApp="Fail"
End If
End Function
Function NewUserReg(UName,Pword)
Dim ActMsg,ExpMsg
ExpMsg=UName
Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").Image("Register").Click
If Browser("Welcome: Mercury Tours").Page("Register: Mercury Tours").Exist(10) Then
Reporter.ReportEvent micPass ,"Register Link Check","Application displyaed New User Registration Page"
Browser("Welcome: Mercury Tours").Page("Register: Mercury Tours").WebEdit("userName").Set UName
Browser("Welcome: Mercury Tours").Page("Register: Mercury Tours").WebEdit("password").Set Pword
Browser("Welcome: Mercury Tours").Page("Register: Mercury Tours").WebEdit("confirmPassword").Set Pword
Browser("Welcome: Mercury Tours").Page("Register: Mercury Tours").Image("register").Click
ActMsg=Browser("Welcome: Mercury Tours").Page("Register: Mercury Tours_2").WebElement("Note: Your user name is").GetROProperty("innertext")
ActMsg=mid(ActMsg,25,Len(UName))
If ExpMsg=ActMsg Then
Reporter.ReportEvent micPass ,"New User Registration Check","New User Registered Successfully"
NewUserReg="Pass"
Else
Reporter.ReportEvent micFail ,"New User Registration Check","New User Registration failed"
NewUserReg="Fail"
End If
Else
Reporter.ReportEvent micFail ,"Register Link Check","Application not displayed New User Registration Page"
End If
End Function
Function Login(Uname,Pword)
Browser("Welcome: Mercury Tours").Page("Register: Mercury Tours_2").Link("sign-in").Click
Browser("Welcome: Mercury Tours").Page("Sign-on: Mercury Tours").WebEdit("userName").Set UName
Browser("Welcome: Mercury Tours").Page("Sign-on: Mercury Tours").WebEdit("password").Set Pword
Browser("Welcome: Mercury Tours").Page("Sign-on: Mercury Tours").Image("Login").Click
If Browser("Welcome: Mercury Tours").Page("Find a Flight: Mercury").Exist(10) Then
Reporter.ReportEvent micPass ,"New User Login Check","New User Login is successful"
Login="Pass"
Else
Reporter.ReportEvent micFail ,"New User Login Check","New User Login Failed"
Login="Fail"
End If
End Function
Function Logout()
Browser("Welcome: Mercury Tours").Page("Find a Flight: Mercury").Image("sign-off").Click
If browser("Welcome: Mercury Tours").Page("Sign-on: Mercury Tours").Exist Then
Reporter.ReportEvent micPass ,"LogOut Check","System redirected to Login Page"
Logout="Pass"
Else
Reporter.ReportEvent micFail ,"Logout Check","System not displayed Login Page"
Logout="Fail"
End If
End Function
Function CloseBrowser()
Browser("Welcome: Mercury Tours").Close
If Browser("Welcome: Mercury Tours").Exist(1) Then
Reporter.ReportEvent micFail ,"Close App Check","Application not Closed Successfully"
CloseBrowser="Fail"
Else
Reporter.ReportEvent micPass ,"Close App Check","Application Closed Successfully"
CloseBrowser="Pass"
End If
End Function
'New User Registration Test
'Project Name : Mercury Tours
'Module Name : Customer
'Script Desc : This script validates new user registration & Login
'Author : xxxxxxxxxxxxxxxxxxxxx
'Created Date : xx/xx/xxxx
Option Explicit
Call LaunchApp(StrUrl)
Call NewUserReg(StrUName,StrPword)
Call Login(StrUName,StrPword)
Call Logout()
Call CloseBrowser()

script close all browsers

 'Suppose there are 10 browser ;;; write script to close all the browsers  ''The below script will close all the open browser

dim d
set d=Description.Create
d("micclass").value="Browser"
set a=Desktop.ChildObjects(d)
for i=0 to a.count-1
   a(i).close
Next


There are 10 browsers and in that 1 browser is mercury tours website.... except mercury tours browser all the other browsers should be closed Get all the browsers and for each browser get the title in the title if "mercury" word is not there then close

dim d
set d=Description.Create
d("micclass").value="Browser"
set a=Desktop.ChildObjects(d)
for i=0 to a.count-1
   s=a(i).getROProperty("title")
   if instr(1,s,"Mercury")=0 Then
     a(i).close
   End if
Next

some examples filesystemobject

Option explicit
Dim mseo,wbo,wso,x,y,z,r,i
Set mseo= createobject("excel.application")
mseo.Visible=true
Set wbo=mseo.Workbooks.Open("c:\mydata.xls",2,true)
Set wso=wbo.Worksheets("sheet1")
r=wso.usedrange.rows.count
For i=1 to r step 1
x=wso.cells(i,1)
y=wso.cells(i,2)
z=eval(x)
If y=z Then
    wso.cells(i,3)="passed"
    else
    wso.cells(i,3)="failed"
    End If
    Next
    wbo.Save
    mseo.Quit
=================================================================
fsdfsOption explicit
Dim fso,fo,f,fc,sf
Set fso=createobject("scripting.filesystemobject")
Set fo=fso.GetFolder("c:\program files")
print "files are"
print "------"
Set fc=fo.files
For each f in fc
    print f.name
    Next
    print"sub folders are:"
    print"----"
    Set sf=fo.subfolders
    For each f in sf
        print f.name
    Next
=================================================================
Option explicit
Dim fso,f,x
Set fso=createobject("scripting.filesystemobject")
Set f=fso.OpenTextFile("c:\textfile.txt",2,true)
f.Write"hello world"
f.Close
Set f=fso.OpenTextFile("\textfile.txt",1)
x=f.ReadLine
msgbox x
f.Close
Set fso= nothing
Set f=nothing
====================================================================
Option explicit
Dim xmlo,root,childs,x,y,i
Set xmlo=xmlutil.CreateXMLFromFile("c:/temp4.xml")
Set root=xmlo.GetRootElement
Set childs=root.ChildElementsByPath("ctemp/temp1")
For i=1 to childs.Count step 1
     x=childs.Item(i).Value
     y=childs.Item(i).Attributes.Item(1).Value
     print x&"in"&y
Next
Set childs=nothing
Set root=nothing
Set xmlo=nothing
==================================================================

Option explicit
Dim xmlo,root,childs,x,i,y
Set xmlo=xmlutil.CreateXMLFromFile("c:/emp.xml")
Set root=xmlo.GetRootElement
Set childs=root.ChildElementsByPath("employee")
For i=1 to childs.Count step 1
     x=childs.Item(i).ChildElementsByPath("name").Item(1).Value
     y=childs.Item(i).ChildElementsByPath("did").Item(1).Value
    print x&"indept no"&y
Next
Set childs=nothing
Set root=nothing
Set xmlo=nothing
=========================================================
Option explicit
Dim xmlo,root,childs,x,i
Set xmlo=xmlutil.CreateXMLFromFile("c:/emp.xml")
Set root=xmlo.GetRootElement
Set childs=root.ChildElementsByPath("employee/name")
For i=1 to childs.Count step 1
     x=childs.Item(i).Value
     print x
Next
Set childs=nothing
Set root=nothing
Set xmlo=nothing
============================================================
Option explicit
Dim x,n,i
print "hai testers"
n=datatable.getsheet(1).GetRowCount
For i=1 to n step 1
    datatable.GetSheet(1).setCurrentRow(i)
    x=datatable.Value("name",1)
    print x
Next
============================================================
Option explicit
Dim exo,wbo,wso,i
Set exo=createobject("Excel.Application")
exo.Visible=true
Set wbo=exo.Workbooks.Add
Set wso=wbo.Worksheets("sheet1")
For i=1 to 56 step 1
    wso.cells(i,1).font.colorindex=i
        wso.cells(i,1)=i
Next
wbo.Saveas("c:\colors1.xls")
exo.Quit
Set wso=nothing
Set wbo=nothing
Set exo=nothing
=============================================================

Option explicit
Dim con,rs,x,y
Set con=createobject("ADODB.connection")
con.Open "testing"
Set rs=createobject("ADODB.RecordSet")
rs.Open "select AT_ID,AT_USER from td.ALERT",con
While rs.EOF<>True
    x=rs.Fields("AT_ID").Value
    y=rs.Fields("AT_USER").Value
print y&" have "&x&"as id"
rs.MoveNext
Wend

con.Close
==============================================================
Option explicit
Dim odesc,list,i
Set odesc= description.Create
odesc("micclass").value="image"
invokeapplication "C:\Program Files\Internet Explorer\iexplore.exe"
browser("title:=about:blank").Navigate "http://localhost:8080/mtours/servlet/com.mercurytours.servlet.WelcomeServlet"
set list=browser("title:=Welcome: Mercury Tours").page("title:=Welcome: Mercury Tours").ChildObjects(odesc)
For i=0 to list.count-1 step 1
    If list(i).object.complete= true Then
       reporter.ReportEvent micPass,"image test","image completely loaded"
       else
           reporter.ReportEvent micFail,"image test","image not completely loaded"

    End If
Next
browser("title:=.*").Close
Set list=nothing
Set odesc=nothing
========================================================
Option explicit
Dim x,y
x=" admin"
y="admin"
invokeapplication "c:\programflies\internetExplorer\iexplore.exe"
browser("title:=about:blank").Navigate"http://newtours.demoaut.com/"
With browser("title:=welcome:mercuryTours")
with.page(" title:=welcome:mercuryTours")
.webedit("name:=user Name").setx
.webedit("name:=password").sety
.image("name:=login").click
End with
End with
If browser("title:=Find a Flight:Mercury tours:").Exist Then
    reporter.ReportEvent Micpass,"logintest","in-correctlogin"
End If
browser("title:=.*").close
===============================================================
Option explicit
Dim odesc,list,i,x,y
Set odesc= description.Create
odesc("micclass").value="image"
invokeapplication "C:\Program Files\Internet Explorer\iexplore.exe"
browser("title:=about:blank").Navigate "http://localhost:8080/mtours/servlet/com.mercurytours.servlet.WelcomeServlet"
set list=browser("title:=Welcome: Mercury Tours").page("title:=Welcome: Mercury Tours").ChildObjects(odesc)
For i=0 to list.count -1 step 1
   x=list(i).getroproperty("name")
   y=list(i).getroproperty("src")
   print x & " image src is " &y
Next
browser("title:=.*").Close
Set list=nothing
Set odesc=nothing
===============================================================
Option explicit
Dim bros,n
Set bros=description.Create
bros("micclass").value="browser"
Set n=desktop.ChildObjects(bros)
msgbox n.count
=============================================================
invokeapplication "C:\Program Files\Internet Explorer\iexplore.exe"
browser("title:=about:blank").Navigate "http://localhost:8080/mtours/servlet/com.mercurytours.servlet.WelcomeServlet"
If browser("title:=Welcome: Mercury Tours").Exist Then
    reporter.ReportEvent micPass,"home page open test","correctly opened"
    browser("title:=.*").Close
    else
    reporter.ReportEvent micFail,"home page open test","incorrectly opened"

End If
===============================================================
Option explicit
Dim con,rs,x,y
Set con=createobject("ADODB.connection")
con.Open "provider=SQLOLEDB;Server=MINDQ10;Database=QualityCenter_Demo_db;Trusted_Connection=yes"
Set rs=createobject("ADODB.RecordSet")
rs.Open "select AT_ID,AT_USER from td.ALERT",con
While rs.EOF<>True
    x=rs.Fields("AT_ID").Value
    y=rs.Fields("AT_USER").Value
print y&" have "&x&"as id"
rs.MoveNext
Wend

con.Close
==========================================================
Option explicit
Dim con
Set con=createobject("ADODB.connection")
con.Open "DSN=QT_Flight32"
con.Execute("update orders set Tickets_Ordered=10 where order_number=5")
con.Close
===========================================================
Dim str
str="suman is a good girl"
msgbox instr(3,str,"is")
=======================================================
Option explicit
Dim exo,wbo,wso,x,y,z,n,i
Set exo=createobject("excel.appliocation")
exo.visible=true
Set wbo=exo.workbooks.open("d:\colm.xls")
Set wso=wbo.worksheets("sheet1")
n=wso.usedrange.rows.count
For i=2 to n step 1
    x=wso.cells(i,1)
    y=wso.cells(i,2)
    z=x+y
    wso.cells(i,3)=z
Next
wbo.save
exo.quit
Set wso=nothing
Set wbo=nothing
Set exo=nothing
====================================================================
Option explicit
dim fso,fo,x
Set fso=createobject("scripting.filesystemobject")
Set fo=fso.OpenTextFile("c:/aaa.txt",1,false) ''''12+12------
While fo.AtEndOfStream<>true
    x=fo.ReadLine
    If eval(x) Then
        print x&"true"
        else
        print x&"fale"
    End If
Wend
fo.Close
Set fo=nothing
Set fso=nothing
===================================================

Option explicit
Dim fso,foo,fs,x,y,i
Set fso=createobject("scripting.filesystemobject")
Set foo=fso.getfolder("C:\flight reservation")
Set fs=foo.files
print "vbs files"
print "*************************"
For each i in fs
    x=i.name
    y=right(x,3)
    If y="vbs" Then
print x
    End If
Next
========================================================
Dim dbcon
Set dbcon=CreateObject("Adodb.Command")
dbcon.provider="microsoft.jet.oledb.4.0"
dbcon.Open"C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"
Set rs=CreateObject("Adodb.RecordSet")
Set cmd=CreateObject("Adodb.Command")
cmd.ActiveConnection=dbcon
cmd.CommandText="select order_number,customer_name from orders where order_no<=5"
rs.Open=cmd.Execute
Do until rs.EOF
    msgbox rs.Fields("order_number")
    msgbox rs.Fields("customer_name")
    rs.MoveNext
Loop
rs.Close
dbcon.close
Set rs=nothing
Set dbcon=nothing
==================================================================
   
dialog("Login").Activate
dialog("Login").WinEdit("Agent Name:").Set datatable("agname","Global")
dialog("Login").WinEdit("Password:").Set datatable("pword","Global")
dialog("Login").WinButton("OK").Click
If dialog("Login").Dialog("Flight Reservations").Exist then
dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click
dialog("Login").WinButton("Cancel").Click
End If
If window("Flight Reservation").Exist then
    datatable("results","Global")="pass"
    window("Flight Reservation").Close
    else
    datatable("results","Global")="fail"
    end if
=====================================================================
Option explicit
Dim x,y,z
x=datatable.Value("input1",1)
y=datatable.Value("input2",2)
z=cint(x)+cint(y)
datatable.Value("result",1)=z