Saturday, 24 September 2011



QTP Scripts examples

1) Verify Login Boundary 
(Check all the boundary conditions of the Login dialog box. Checks to see if the correct message appears in the error window (Flight Reservation Message)

1) ApplicationDir = Environment("ProductDir")
2) ApplicationPath = "\samples\flight\app\flight4a.exe"
3) If Window("Flight Reservation").Exist(2) Then
4) Window("Flight Reservation").Close
5) SystemUtil.Run ApplicationDir & ApplicationPath
6) Elseif Not Dialog("Login").Exist(1) Then
7) SystemUtil.Run ApplicationDir & ApplicationPath
8) End If
9) Dialog("Login").WinEdit("Agent Name:").Set Datatable.Value ("AgentName",dtGlobalSheet)
10) Dialog("Login").WinEdit("Password:").Set Datatable.Value ("Password",dtGlobalSheet)
11) Dialog("Login").WinButton("OK").Click
12) If Dialog("Login").Dialog("Flight Reservations").Exist(1) and Datatable.Value ("Status",dtGlobalSheet)="Fail" Then
13) Dialog("Login").Dialog("Flight Reservations").Static("Agent name must be at").Check CheckPoint("Agent name must be at least 4 characters long.")
14) Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click
15) Elseif Window("Flight Reservation").Exist(10) and Datatable.Value ("Status",dtGlobalSheet)="Pass" Then
16) Reporter.ReportEvent PASS,"Login: ","Succeeded"
17) Else
18) Reporter.ReportEvent Fail,"Login: ","Combination #" & Datatable.GetCurrentRow & " was not according to Excel file"
19) End If

2) Verify Cancel Operation (in Login Dialog box, if user selects cancel button, before enter any data after enter data dialog box should be disappeared.)

1) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
2) Dialog("Login").Activate
3) Dialog("Login").WinButton("Cancel").Click
4) If Dialog("Login").Exist (2) =True Then
5) Reporter.ReportEvent 1,"sd","Fail"
6) Else
7) Reporter.ReportEvent 0,"sd","Pass"
8) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
9) End If
10) Dialog("Login").Activate
11) Dialog("Login").WinEdit("Agent Name:").Set "asdf"
12) Dialog("Login").WinButton("Cancel").Click
13) If Dialog("Login").Exist (2) =True Then
14) Reporter.ReportEvent 1,"sd","Fail"
15) Else
16) Reporter.ReportEvent 0,"sd","Pass"
17) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
18) End If
19) Dialog("Login").Activate
20) Dialog("Login").WinEdit("Agent Name:").Set "asdf"
21) Dialog("Login").WinEdit("Password:").SetSecure "4a993af45dcbd506c8451b274d2da07b38ff5531"
22) Dialog("Login").WinButton("Cancel").Click
23) If Dialog("Login").Exist (2)=True Then
24) Reporter.ReportEvent 1,"sd","Fail"
25) Else
26) Reporter.ReportEvent 0,"sd","Pass"
27) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
28) End If
29) Dialog("Login").Activate
30) Dialog("Login").WinEdit("Agent Name:").Set "asdf"
31) Dialog("Login").WinEdit("Password:").SetSecure "4a993af45dcbd506c8451b274d2da07b38ff5531"
32) Dialog("Login").WinButton("OK").Click

3) Verify Addition, Subtraction, Multiplication and Division Operations in Calculator Application.

1) Dim aRes,sRes,dRes,mRes
2) VbWindow("VbWindow").Activate
3) VbWindow("VbWindow").VbEdit("VbEdit").Set "10"
4) VbWindow("VbWindow").VbEdit("VbEdit_2").Set "20"
5) v1=VbWindow("VbWindow").VbEdit("VbEdit").GetROProperty ("text")
6) v2=VbWindow("VbWindow").VbEdit("VbEdit_2").GetROProperty ("text")
7) VbWindow("VbWindow").VbButton("ADD").Click
8) aRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText
9) VbWindow("VbWindow").VbButton("SUB").Click
10) sRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText
11) VbWindow("VbWindow").VbButton("MUL").Click
12) mRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText
13) VbWindow("VbWindow").VbButton("DIV").Click
14) dRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText
15) v1=cdbl(v1)
16) v2=cdbl(v2)
17) aRes=cdbl (aRes)
18) sRes=cdbl (sRes)
19) mRes=cdbl (mRes)
20) dRes=cdbl (dRes)
21) If aRes=v1+v2 Then
22) Reporter.ReportEvent 0,"Res","Addition Passed"
23) else
24) Reporter.ReportEvent 1,"Res","Addition Failed"
25) End If
26) If sRes=v1-v2 Then
27) Reporter.ReportEvent 0,"Res","Subtraction Passed"
28) else
29) Reporter.ReportEvent 1,"Res","Subtraction Failed"
30) End If
31) If mRes=v1*v2 Then
32) Reporter.ReportEvent 0,"Res","Multiplecation Passed"
33) else
34) Reporter.ReportEvent 1,"Res","Multiplecation Failed"
35) End If
36) If dRes=v1/v2 Then
37) Reporter.ReportEvent 0,"Res","Division Passed"
38) else
39) Reporter.ReportEvent 1,"Res","Division Failed"
40) End If

4) Verify state of Update Order Button, before open an Order and after open an Order (in Flight Reservation before opening an order Update Order button should be disabled after opening an order enabled.)

1) Option explicit
2) Dim bo,ao
3) If Not window("Flight Reservation").Exist (2) Then
4) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
5) Dialog("Login").Activate
6) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy"
7) Dialog("Login").WinEdit("Password:").SetSecure "4aa8bce9984f1a15ea187a2da5b18c545abb01cf"
8) Dialog("Login").WinButton("OK").Click
9) End If
10) Window("Flight Reservation").Activate
11) bo=Window("Flight Reservation").WinButton("Update Order").GetROProperty ("Enabled")
12) Window("Flight Reservation").WinButton("Button").Click
13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "1"
15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
16) ao=Window("Flight Reservation").WinButton("Update Order").GetROProperty ("Enabled")
17) If bo=False Then
18) Reporter.ReportEvent 0,"Res","Update Order Button Disabled"
19) else
20) Reporter.ReportEvent 1,"Res","Update Order Button Enabled"
21) End If
22) If ao=True Then
23) Reporter.ReportEvent 0,"Res","Update Order Button Enabled"
24) else
25) Reporter.ReportEvent 1,"Res","Update Order Button Disabled"
26) End If

5) Price Consistency, In Flight Reservation (In Flight Reservation, First class price=3*Economy class price and Business class price=2*Economy class price)
1) Option explicit
2) Dim n,f,b,e
3) If Not window("Flight Reservation").Exist (2) Then
4) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
5) Dialog("Login").Activate
6) Dialog("Login").WinEdit("Agent Name:").Set "asdf"
7) Dialog("Login").WinEdit("Password:").SetSecure "4aa8b7b7c5823680cfcb24d30714c9bbf0dff1eb"
8) Dialog("Login").WinButton("OK").Click
9) End If
10) For n= 1 to 10 step 1
11) Window("Flight Reservation").Activate
12) Window("Flight Reservation").WinButton("Button").Click
13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set n
15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
16) Window("Flight Reservation").WinRadioButton("First").Set
17) f=Window("Flight Reservation").WinEdit("Price:").GetVisibleText
18) Window("Flight Reservation").WinRadioButton("Business").Set
19) b=Window("Flight Reservation").WinEdit("Price:").GetVisibleText
20) Window("Flight Reservation").WinRadioButton("Economy").Set
21) e=Window("Flight Reservation").WinEdit("Price:").GetVisibleText
22) f=cdbl(mid(f,2,len (f-1)))
23) b=cdbl(mid(b,2,len (b-1)))
24) e=cdbl(mid(e,2,len (e-1)))
25) If f=3*e and b=2*e Then
26) Reporter.ReportEvent 0,"Res","Pricy Consistancy is there"
27) else
28) Reporter.ReportEvent 1,"Res","Pricy Consistancy is NOT there"
29) End If
30) Window("Flight Reservation").WinButton("Button_2").Click
31) Window("Flight Reservation").Dialog("Flight Reservations").WinButton("No").Click
32) Next

6) Verify Total, In Flight Reservation (In Flight Reservation, Total = Tickets * Price)

1) Option Explicit
2) Dim t,p,tot,n
3) For n= 1 to 10 step 1
4) If Not window("Flight Reservation").Exist (2) Then
5) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open"
6) Dialog("Login").Activate
7) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy"
8) Dialog("Login").WinEdit("Password:").SetSecure "4aa892d62c529f1c23298175ad78c58f43da8e34"
9) Dialog("Login").WinButton("OK").Click
10) End If
11) Window("Flight Reservation").Activate
12) Window("Flight Reservation").WinButton("Button").Click
13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set n
15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
16) t=Window("Flight Reservation").WinEdit("Tickets:").GetVisibleText
17) p=Window("Flight Reservation").WinEdit("Price:").GetVisibleText
18) tot=Window("Flight Reservation").WinEdit("Total:").GetVisibleText
19) t=cdbl (t)
20) p=Cdbl(mid(p,2,len (p-1)))
21) tot=Cdbl(mid(tot,2,len (tot-1)))
22) If tot=t*p Then
23) Reporter.ReportEvent 0,"Res","Calculation Passed"
24) else
25) Reporter.ReportEvent 1,"Res","Calculation Failed"
26) End If
27) Next

7) Verify Flight From & Flight To Combo Boxes (In Flight reservation, select an item from Fly From: combo box and verify weather that item available or not in Fly To: combo box, like this select all items one by one in Fly From and verify weather selected items available or not in Fly To.)

1) Option explicit
2) Dim qtp,flight_app,f,t,i,j,x,y
3) If Not Window("text:=Flight Reservation").Exist (7)= True Then
4) QTP=Environment("ProductDir")
5) Flight_app="\samples\flight\app\flight4a.exe"
6) SystemUtil.Run QTP & Flight_app
7) Dialog("text:=Login").Activate
8) Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set "asdf"
9) Dialog("text:=Login").WinEdit("attached text:=Password:").SetSecure "4aa5ed3daf680e7a759bee1c541939d3a54a5b65"
10) Dialog("text:=Login").WinButton("text:=OK").Click
11) End If
12) Window("text:=Flight Reservation").Activate
13) Window("text:=Flight Reservation").WinButton("window id:=6").Click
14) Window("text:=Flight Reservation").ActiveX("acx_name:=MaskEdBox","window id:=0").Type "090910"
15) f=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").GetItemsCount
16) For i= 0 to f-1 step 1
17) Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").Select (i)
18) x=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").GetROProperty ("text")
19) t=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").GetItemsCount
20) For j= 0 to t-1 step 1
21) Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").Select (j)
22) y=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").GetROProperty ("text")
23) If x <> y Then
24) Reporter.ReportEvent 0,"Res","Test Passed"
25) Else
26) Reporter.ReportEvent 1,"Res","Test Failed"
27) End If
28) Next
29) Next

8) Verify Order No Entry in Flight Reservation. (In Open Order dialog box, Order No object accepts numeric values only.)

1) If Not window("Flight Reservation").Exist (2) Then
2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
3) Dialog("Login").Activate
4) Dialog("Login").WinEdit("Agent Name:").Set "asdf"
5) Dialog("Login").WinEdit("Password:").SetSecure "4aa9ccae3bb00962b47ff7fb0ce3524c1d88cb43"
6) Dialog("Login").WinButton("OK").Click
7) End If
8) Window("Flight Reservation").Activate
9) Window("Flight Reservation").WinButton("Button").Click
10) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
11) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "a"
12) ord=Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").GetVisibleText
13) If ord= "a" Then
14) Reporter.ReportEvent 1,"Res","Order No Object is taking invalid data"
15) else
16) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "1"
17) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
18) End If

9) Get Test Data from a Flat file and use in Data Driven Testing (through Scripting)

1) Dim fso,myfile
2) Set fso=createobject("scripting.filesystemobject")
3) Set myfile= fso.opentextfile ("F:\gcr.txt",1)
4) myfile.skipline
5) While myfile.atendofline <> True
6) x=myfile.readline
7) s=split (x, ",")
8) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
9) Dialog("Login").Activate
10) Dialog("Login").WinEdit("Agent Name:").Set s(0)
11) Dialog("Login").WinEdit("Password:").SetSecure s(1)
12) Dialog("Login").WinButton("OK").Click
13) Window("Flight Reservation").Close
14) Wend

10) Count, how many Buttons and Edit boxes available in Flight Reservation main window.

1) If Not window("Flight Reservation").Exist (2) Then
2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
3) Dialog("Login").Activate
4) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy"
5) Dialog("Login").WinEdit("Password:").Set "mercury"
6) Dialog("Login").WinButton("OK").Click
7) End If
8) Set oDesc = Description.Create()
9) oDesc("micclass").Value = "WinButton"
10) Set Buttons = Window("text:=Flight Reservation").ChildObjects (oDesc)
11) Num_Buttons = Buttons.Count()
12) Set oDesc1=Description.Create()
13) oDesc1("micclass").Value="WinEdit"
14) Set Editboxes=Window("text:=Flight Reservation").ChildObjects (oDesc1)
15) Num_Editboxes= editboxes.count ()
16) sum= Num_Buttons+Num_Editboxes
17) Reporter.ReportEvent 2, "Res","Total Buttons: "& Num_Buttons &"Total Edit boxes: "& Num_Editboxes

11) Verify search options in Open Order Dialog box

(After selecting open order, 3 search options should be enabled and not checked,
After selecting Order No option, other options should be disabled,
After selecting Customer Name, Flight date option enabled and Order No disabled
After selecting Flight date option, Customer Name enabled and Order No disabled)

1) If Not window("Flight Reservation").Exist (2) Then
2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
3) Dialog("Login").Activate
4) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy"
5) Dialog("Login").WinEdit("Password:").SetSecure "4aa9ed25bc0ebde66ed726ad87d7e991347d8b9c"
6) Dialog("Login").WinButton("OK").Click
7) End If
8) Window("Flight Reservation").Activate
9) Window("Flight Reservation").WinButton("Button").Click
10) Window("Flight Reservation").Dialog("Open Order").Activate
11) oe=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled")
12) ce=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled")
13) fe=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty("Enabled")
14) oc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Checked")
15) cc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Checked")
16) fc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty("Checked")
17) If (oe=true and ce=true and fe=true) and (oc="OFF" and cc="OFF" and fc="OFF") Then
18) Reporter.ReportEvent 0,"Res","Pass"
19) else
20) Reporter.ReportEvent 1,"Res","Fail"
21) End If
22) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
23) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Checked")
24) If ono="ON" Then
25) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Enabled")
26) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled")
27) fd=false
28) ono=false
29) Reporter.ReportEvent 0,"Res","Pass"
30) else
31) Reporter.ReportEvent 1,"Res","Fail"
32) End If
33) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "OFF"
34) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").Set "ON"
35) cn=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Checked")
36) If cn="ON" Then
37) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled")
38) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Enabled")
39) fd=True
40) ono=false
41) Reporter.ReportEvent 0,"Res","Pass"
42) else
43) Reporter.ReportEvent 1,"Res","Fail"
44) End If
45) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").Set "OFF"
46) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").Set "ON"
47) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Checked")
48) If fd="ON" Then
49) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled")
50) cn=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled")
51) cn=True
52) ono=false
53) Reporter.ReportEvent 0,"Res","Pass"
54) else
55) Reporter.ReportEvent 1,"Res","Fail"
56) End If

12) In Login Dialog box, Verify Help message (The message is ‘The password is 'MERCURY')

1) If Not Dialog("Login").Exist (2) Then
2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
3) End If
4) Dialog("Login").Activate
5) Dialog("Login").WinButton("Help").Click
6) message=Dialog("Login").Dialog("Flight Reservations").Static("The password is 'MERCURY'").GetROProperty("text")
7) If message="The password is 'MERCURY'" Then
8) Reporter.ReportEvent 0,"Res","Correct message "&message
9) else
10) Reporter.ReportEvent 1,"Res","Worng message "
11) End If

A Sample QTP Real-time Test Script


 _____________________________________________________________
Dim objNet
Dim strInfo                          
'____________________________________________________________________________________________________________________________________
'Set the initial value of the variables
i = 1
msgnum = 0
strFail = 1
strTestName = "2Step_1orMoreAcres_Attribute_145_100orMoreAcres"                         
'____________________________________________________________________________________________________________________________________
'Function to open a brower and go to a specified URL
Function OpenBrowser (browser, URL)
    systemUtil.Run browser, URL
End Function
'____________________________________________________________________________________________________________________________________
'Get Computer Name
set wshnetwork=createobject("wscript.network")
scomputername=wshnetwork.computername
set wshnetwork=nothing
strServ = scomputername
'msgbox strServ 
'____________________________________________________________________________________________________________________________________
'Turn off the report filter
CurrentMode = Reporter.Filter
Reporter.Filter = rfDisableAll
'____________________________________________________________________________________________________________________________________
'Get username from the local box
Set objNet = CreateObject("WScript.NetWork")
strInfo =  objNet.UserName
'msgbox strInfo
'____________________________________________________________________________________________________________________________________
'Create a unique name for the results file each time the test is executed.
mypath = "\\taz02mon901\Mercury\QTP_Test_Results\2Step_1orMoreAcres_Attribute_145_100orMoreAcres.html"
      Call CreateFiles()
'____________________________________________________________________________________________________________________________________
' Set Excel File to be appenced
strDataSheet = "\\taz02mon901\Mercury\Mercury_QTP_Test\Realtor\2-Step\2STEP_ATTRIBUTES_FAILURE_LOG_QA.xls"
'____________________________________________________________________________________________________________________________________
'Clear the cookies and temp files
'Call  ClearCookies
'____________________________________________________________________________________________________________________________________

'=======================
'                    MAIN   
'=======================

'____________________________________________________________________________________________________________________________________


'Database query
' Connect to the Realtor database
Set dbconn = CreateObject("ADODB.Connection")
Set recordset = CreateObject("ADODB.recordset")
'MS SQL Server DSNless connection
'dbconn.Open("Driver={SQL Server};Server=TAZ02SQL832 ;Database=XProperty ;Uid=admin;Pwd=admin")
dbconn.Open("Driver={SQL Server};Server=TAZ02SQL832;Database=XProperty")
dbconn.commandTimeout = 300
' Specify the query
sql = "select top 1 l.listingid,l.postalcode,l.marketingtypeid,l.listingtypeid,l.bedrooms,l.bathrooms,l.listingsqft,l.price,l.address,l.city,l.state,l.createdate,l.geoapproximation from xproperty.dbo.listing (nolock) l join xproperty.dbo.LISTING_ATTRIBUTE (nolock) la1 on l.listingid = la1.listingid left join xproperty.dbo.LISTING_ATTRIBUTE (nolock) la2 on l.listingid = la2.listingid and la2.attributeid in (144,146,147,150,152,154,159,161,166) where l.status = 'a' and l.agentid is not null and l.postalcode is not null and l.postalcode <> '' and l.country = 'usa' and la1.attributeid = 145 and l.geoapproximation = 1 and l.DataSourceID not in (select datasourceid from xproperty.dbo.DATA_SOURCE_ATTRIBUTE where attributeid in (27,31)) and la2.ListingID is null and l.createdate < getdate() - 2 order by l.createdate desc"
' Set the recordset cursor type
recordset.CursorType = 0
' Execute the query
recordset.Open sql, dbconn
        listingid = recordset.Fields("listingid")&""
        listingid = Trim(listingid)'
        'msgbox listingid
        postalcode = recordset.Fields("postalcode")&""
        'msgbox postalcode
        marketingtypeid = recordset.Fields("marketingtypeid")&""
        'msgbox marketingtypeid
        listingtypeid = recordset.Fields("listingtypeid")&""
        'msgbox listingtypeid
        bedrooms = recordset.Fields("bedrooms")&""
        'msgbox bedrooms
        bathrooms = recordset.Fields("bathrooms")&""
        'msgbox bathrooms
        listingsqft = recordset.Fields("listingsqft")&""
        'msgbox listingsqft
        price = recordset.Fields("price")&""
        'msgbox price
        address = recordset.Fields("address")&""
        'msgbox address
        city = recordset.Fields("city")&""
        'msgbox city
        state = recordset.Fields("state")&""
        'msgbox state
        createdate = recordset.Fields("createdate")&""
        'msgbox createdate
If bedrooms = "" Then
      'Do Nothing
            Else
                  If  bedrooms >5 Then
                        bedrooms = 5
                  End If
End If
bathrooms = fix(bathrooms)
If bathrooms = "" Then
      'Do Nothing
            Else
                  If  bedrooms >5 Then
                        bedrooms = 5
                  End If
End If
If  listingtypeid = 6 Then
      bedrooms = ""
      bathrooms = ""
End If
'_________________________________________________________________________________
' Date and Start Time of the test run
strDate = date
strStartTime = time
'____________________________________________________________________________________________________________________________________
'Open a browser to the google.com homepage 
SystenUtil.run"Iexplote.exe",www.google.co.in


'____________________________________________________________________________________________________________________________________


'Check for the text office on the LDP
'Browser("Real Estate Listings,_5").Page("2275 Youngman Ave Unit:").WebElement("Property Information for").Check CheckPoint("Property Information for 2275 Youngman Ave Unit: 108W Save Listing Property FeaturesCondo/Townhome/Row Home/Co-OpStatus: Active Area: SP-Highland Area County: RAMSEYYear Built: 1980 1 total bedroom(s) 2 total bath(s) Approximately 1130 sq. ft.Style: High Rise (4+ Levels) Office 1 car garage School District: St. Paul Exterior FeaturesHeated garage Listing InformationRefreshed at 9:35 AM PT (19 days ago)Added on Jun 29, 2004 (1940 days ago) To access this page directly, usehttp://qap.www.realtor.com/realestateandhomes-detail/2275-Youngman-Ave-Unit-108W_St-Paul_MN_55116_1038274619 This listing is brokered byEdina Realty, Inc.Office: (651)698-2434")
strPropInfo = Browser("Real Estate Listings,_5").Page("2275 Youngman Ave Unit:").WebElement("Property Information for").GetROProperty("innertext")
'msgbox strPropInfo
strGarageCheck = Instr(strPropInfo, "Lot size is 100 or more acres")
'msgbox strGarageCheck
If  strGarageCheck <> 0 Then
      'msgbox "Pass"
            Else
                  'msgbox "Fail"
            strEndTime = time
                  Call AppendXL
                  msgnum = msgnum+1
                        Browser("Real Estate Listings,_5").Page("2275 Youngman Ave Unit:").Sync
                        Browser("Real Estate Listings,_5").Close
                        Call SendMail
            ExitTest
End If
'


'Close the browser


Browser("Real Estate Listings,_5").Page("2275 Youngman Ave Unit:").Sync
Browser("Real Estate Listings,_5").Close
'_________________________________________________________________________________


'Open a browser to the google.com homepage
OpenBrowser "iexplore.exe", "http://.www.google.com/"
wait (3)
'___________________________________________________________________________________________________________________________________
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebEdit("srchHomeLocation").Set postalcode
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebRadioGroup("ctl00$cphC$MainSearch$ccBuyRen").Select marketingtypeid
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebElement("More Search Options").FireEvent "onmouseover"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebElement("More Search Options").Click
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebEdit("tbMinPrice").Set price
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebEdit("tbMaxPrice").Set price
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebList("ctl00$cphC$AdvancedSearchPage$_2").Select bedrooms&"+"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebList("ctl00$cphC$AdvancedSearchPage$_3").Select bathrooms&"+"
If  marketingtypeid = 2 Then
'Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebElement("WebElement").FireEvent "onmouseover"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebRadioGroup("ctl00$cphC$AdvancedSearchPage$").FireEvent "onmouseover"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebRadioGroup("ctl00$cphC$AdvancedSearchPage$").Select "2"
wait (3)
End If
If listingtypeid = 1 Then
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$").Set "ON"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_2").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_4").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_5").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_6").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_7").Set "OFF"
ElseIf listingtypeid = 2 Then
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_2").Set "ON"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_4").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_5").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_6").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_7").Set "OFF"
ElseIf listingtypeid = 4 Then
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_2").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_4").Set "ON"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_5").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_6").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_7").Set "OFF"
ElseIf listingtypeid = 3 Then
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_2").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_4").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_5").Set "ON"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_6").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_7").Set "OFF"
ElseIf listingtypeid = 5 Then
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_2").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_4").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_5").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_6").Set "ON"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_7").Set "OFF"
ElseIf listingtypeid = 6 Then
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_2").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_4").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_5").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_6").Set "OFF"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebCheckBox("ctl00$cphC$AdvancedSearchPage$_7").Set "ON"
End If
Browser("Real Estate Listings,").Page("Real Estate Listings,_3").Link("Lot & Community").FireEvent "onmouseover"
Browser("Real Estate Listings,").Page("Real Estate Listings,_3").Link("Lot & Community").Click
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebList("ctl00$cphC$AdvancedSearchPage$_5").FireEvent "onmouseover"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebList("ctl00$cphC$AdvancedSearchPage$_5").Click
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebList("ctl00$cphC$AdvancedSearchPage$_5").Select "1 or More Acres"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").Link("Search").Click
Browser("Real Estate Listings,_5").Sync
'___________________________________________________________________________________________________________________________________
'Select Listview
Browser("Real Estate Listings,_5").Page("55116 real estate & 55116").WebElement("WebElement_2").Click
strView = "List"
Set odesc=description.Create()
odesc("micclass").value="WebElement"
odesc("html tag").value="DIV"
odesc("class").value="listingData"
Set childObjs= Browser("Real Estate Listings,").Page("55116 real estate & 55116").ChildObjects(odesc)
strResults = childObjs.count
'msgbox strResults
If  strResults <> 0 Then
      Call Listcheck
            Else
                  strFail = 1
End If
If strFail= 0 Then
      'Do Nothing
            Else
            strEndTime = time
                  Call AppendXL
                  msgnum = msgnum+1
End If
'___________________________________________________________________________________________________________________________________
'Select Galleryview
Browser("Real Estate Listings,_5").Page("55116 real estate & 55116").WebElement("WebElement_4").Click
strView = "Gallery"
Set odesc=description.Create()
odesc("micclass").value="WebElement"
odesc("html tag").value="DIV"
odesc("class").value="listingData"
Set childObjs= Browser("Real Estate Listings,").Page("55116 real estate & 55116").ChildObjects(odesc)
strResults = childObjs.count
'msgbox strResults
If  strResults <> 0 Then
      Call Gallerycheck
            Else
                  strFail = 1
End If
If strFail= 0 Then
      'Do Nothing
            Else
            strEndTime = time
                  Call AppendXL
                  msgnum = msgnum+1
End If
'___________________________________________________________________________________________________________________________________
'Select Mapview
Browser("Real Estate Listings,").Page("55116 real estate & 55116").Image("REALTOR.com® - Official").Click
Browser("Real Estate Listings,").Sync
Browser("Real Estate Listings,").Page("Real Estate Listings,_3").WebElement("More Search Options").Click
If  marketingtypeid = 2 Then
'Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebElement("WebElement").FireEvent "onmouseover"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebRadioGroup("ctl00$cphC$AdvancedSearchPage$").FireEvent "onmouseover"
Browser("Real Estate Listings,_5").Page("Real Estate Listings,").WebRadioGroup("ctl00$cphC$AdvancedSearchPage$").Select "2"
wait (3)
End If
Browser("Real Estate Listings,").Page("Real Estate Listings,_3").Link("Display Options").Click
Browser("Real Estate Listings,").Page("Real Estate Listings,_3").WebRadioGroup("ccViewResults").Select "map"
Browser("Real Estate Listings,").Page("Real Estate Listings,_3").Link("Search").Click
Browser("Real Estate Listings,").Sync
wait (10)
strView = "Map"
'Browser("Real Estate Listings,").Page("55116 real estate & 55116").WebElement("WebElement_3").Check CheckPoint("WebElement_2")
Set odesc=description.Create()
odesc("micclass").value="WebElement"
odesc("html tag").value="DIV"
odesc("class").value="listingData"
Set childObjs= Browser("Real Estate Listings,").Page("55116 real estate & 55116").ChildObjects(odesc)
strResults = childObjs.count
'msgbox strResults
If  strResults <> 0 Then
      Call Mapcheck
            Else
                  strFail = 1
End If
If strFail= 0 Then
      'Do Nothing
            Else
            strEndTime = time
                  Call AppendXL
                  msgnum = msgnum+1
End If
'____________________________________________________________________________________________________________________________________
'Close the browser
Browser("Real Estate Listings,_5").Page("2275 Youngman Ave Unit:").Sync
Browser("Real Estate Listings,_5").Close
'____________________________________________________________________________________________________________________________________
               If msgnum = 0 Then
                         intRunStatusID = 1
                               else
                                    intRunStatusID = 0
                  End If
'____________________________________________________________________________________________________________________________________
'Test Run End Time
strEndTime = time
'____________________________________________________________________________________________________________________________________ 
'Call UpdateRun
'____________________________________________________________________________________________________________________________________
'Determine which email sub to use based on Pass or Fail
 
If intRunStatusID = 1 Then
      Call SendMail
            else
                  Call SendMail
End If
************************************************

Web Scripts

 

1) Count all opened Browsers on desktop and close them all?
Set oDesc = Description.Create()
oDesc("micclass").Value = "Browser"
Set Browsers =Desktop.ChildObjects (oDesc)
NumberofBrowsers = Browsers.Count()
Reporter.ReportEvent 2,"Res","Number of Browsers are: "&NumberOfBrowsers
For Counter=0 to NumberofBrowsers-1
Browsers(Counter).Close
Next
2) Count, how many links available in Mercury Tours Home Page.
Set oDesc = Description.Create()
oDesc("micclass").Value = "Link"
Set Lists = Browser("Welcome: Mercury").Page("Welcome: Mercury").ChildObjects (oDesc)
NumberOfLinks = Lists.Count()
Reporter.ReportEvent 2,"Res","Number of Links are: "&NumberOfLinks
3) Verify  whether the 'Gmail'  link available or not on Google Homepage

Option explicit
Dim oLink, Links, TotLinks, i, myLink
Set oLink = description.Create
oLink("micclass").value = "Link"
SystemUtil.Run "D:\Program Files\Internet Explorer\IEXPLORE.EXE"
set Links = Browser("name:=Google").page("title:=Google").ChildObjects(oLink)
TotLinks = Links.count
For i =0 to TotLinks-1 
myLink = Links(i).getroproperty("innertext")
If mylink = "Gmail" Then
     reporter.ReportEvent 0,"res","Link Gmail available"
End If
Next

4) Count number of Links, Edit Boxes available on Google Homepage?

Dim oLink
Set oLink=description.Create
Set oEdit=description.Create
oLink("micclass").value="Link"
oEdit("micclass").value="WebEdit"
Set Links=browser("name:=Google").page("title:=Google").ChildObjects(oLink)
Set EditBoxes=browser("name:=Google").page("title:=Google").ChildObjects(oEdit)
TotLinks= Links.count
TotEditBoxes=EditBoxes.count
msgbox TotLinks
msgbox TotEditBoxes
Reporter.ReportEvent 0,"Result","Total Links are: "&TotLinks&"Total edit Boxes are: "&TotEditBoxes

5) Count how many links available in a Web Page(any web page, using Regular Expressions)

Dim oLink,Links, TotLinks
Set oLink=Description.Create
oLink("micclass").value="Link"
Set Links=Browser("title:=.*").page("title:=.*").ChildObjects(oLink)
TotLinks=Links.count
msgbox TotLinks
Reporter.ReportEvent 2,"Res","Total Links are: "&TotLinks

6) Verify Cost in jjperfumes.com 
'Test Flow
'i) Launch jjperfumes.com
'ii) Select a product and enter some quantity
'iii) select Add to Cart, capture Unit price, Quantity and Cost
'iV) Remove $ symbols and compare
'---------------------------------- 
-----

SystemUtil.Run "C:\Program Files\Internet Explorer\iexplore.exe","","C:\Documents and Settings\gcr.GCRC-9A12FBD3D9","open"
Browser("Google").Page("Google").Sync
Browser("Google").Navigate "http://www.jjperfumes.com/"

Browser("Google").Page("JJ Perfumes-Discount perfume").Image("thumb_1845_WLINP50PSW").Click
Browser("Google").Page("JJ Perfumes-Discount perfume_2").WebEdit("quantity").Set "4"
Browser("Google").Page("JJ Perfumes-Discount perfume_2").WebButton("Add To Cart").Click

Unit_Price = Browser("Google").Page("JJ Perfumes-Discount perfume_3").WebElement("[Remove]").GetROProperty("innertext")
Qty = Browser("Google").Page("JJ Perfumes-Discount perfume_3").WebEdit("quantity[]").GetROProperty("value")
Cost = Browser("Google").Page("JJ Perfumes-Discount perfume_3").WebElement("[Remove]_2").GetROProperty("innertext")

Qty=Cint(Qty)
Unit_Price=Cdbl (Mid (Unit_Price,3))
Cost=Cdbl (Mid (Cost, 3))
'Msgbox Unit_Price: Msgbox Qty: Msgbox Cost

If Cost=Qty * Unit_Price Then
    Reporter.ReportEvent micPass,"Res","Cost is Correct"
    Else
    Reporter.ReportEvent micFail,"Res","Cost is InCorrect"
End If 


Function To Create HTML Report
Dim StartTime,stTime, enTime
Dim fso, ts,intCnt, intPass,intFail
intPass=0
intFail=0
Const ForWriting = 2
Function OpenFile (strFileName)
StartTime = Timer
stTime = Time
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(strFileName,2)
'OpenFile = strFileURL
CreateHeader
End Function
*****************************
Function To Close File
Dim objIE,strFileURL
Function CloseFile ( strFileURL,strEnv )
Footer(strEnv)
ts.close()
Set objIE = CreateObject("InternetExplorer.Application")
objIE.visible = True
objIE.Navigate strFileURL
wait(5)
Set objIE=nothing
End Function
***********************
Function to Clear Cookies()
Function ClearCookies()
SystemUtil.Run "iexplore.exe"
WebUtil.DeleteCookies
Set objBrowser=Description.Create
objBrowser("micclass").value="Browser"
Set objBCount = Desktop.ChildObjects(objBrowser)
intBrowserCount = objBCount.Count
strHwnd=Browser("creationtime:=" & intBrowserCount).GetROProperty("hwnd")
SystemUtil.CloseProcessByHwnd(strHwnd)
End Function
***********************
Function to send Email
Function SendMail()
If k=0 Then
'Nothing
Else
msgsub = " Geo_PostalCode pattern searchTest Results:" &vbcrLf &"One or more of the Test Cases Failed." &vbcrLf &"See attachment for details."
End If
Set objConf = CreateObject("CDO.Configuration")
cdoSendUsingPort=2
sMailServerName="smtp.phx.move.com"
cdoAnonymous=cdoNONE
objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoSendUsingPort
objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = sMailServerName
objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoAnonymous 'cdoBasic
objConf.fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False
objConf.fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
'objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "corp\ NRaoJ "
'objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "123K!r45"
objConf.fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
objConf.fields.Update
Set objMsg = CreateObject("CDO.Message")
objMsg.Configuration = objConf

objMsg.to = "gcreddy@gmail.com"
objMsg.From = "gcreddy@gmail.com"
objMsg.Subject = "~Geo_PostalCode pattern search"
objMsg.TextBody =msgsub
doc=strFilepath
objMsg.AddAttachment(doc)
objMsg.Send
Set objMsg = Nothing
NewMail = True
End Function

***********************
Function to create append excel

Function LogFile
Set objExcel=CreateObject("Excel.Application")
objExcel.visible=False
objExcel.workbooks.open(strFilePath)
r=1
Do Until len(objExcel.cells(r,1))=0
r=r+1
Loop
objExcel.cells(r,1).value="Step Name"
objExcel.cells(r,2).value="Step Description"
objExcel.cells(r,3).value="Test Results"
objExcel.DisplayAlerts = False
objExcel.Save
objExcel.Quit
Set objExcel = Nothing
End Function

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

Function to get the Application Environment on which the script is running
Function GetEnv()
Set fso=Createobject("Scripting.FileSystemObject")
sFile="C:\WINDOWS\system32\drivers\etc\hosts"
Set MyFile=fso.OpenTextFile(sFile,1, True)
Do
sEnv=MyFile.ReadLine
If instr(sEnv,"PRODUCTION")>0 Then
GetEnv="Production"
Exit do
Elseif instr(sEnv,"Staging")>0 Then
GetEnv="Staging"
Exit do
Elseif instr(sEnv,"QA MAINTENANCE")>0 Then
GetEnv="QAM"
Exit do
Elseif instr(sEnv,"qap.")>0 Then
GetEnv="qap"
Exit do
End If
Loop While MyFile.AtEndOfStream=False
End Function

***********************
Function To Create HTML Report
Dim StartTime,stTime, enTime
Dim fso, ts,intCnt, intPass,intFail
intPass=0
intFail=0
Const ForWriting = 2
Function OpenFile (strFileName)
StartTime = Timer
stTime = Time
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(strFileName,2)
'OpenFile = strFileURL
CreateHeader
End Function

***********************
Web Scripts-II

1) Script to get the list of links in Google and do spell check
=====================================
Dim d
set mw=CreateObject("Word.Application")
set d=Description.Create
d("micclass").value="Link"
set a=Browser("Google").page("Google").childobjects(d)
for i=0 to a.count-1 
mw.WordBasic.filenew 
s=a(i).getROProperty("innertext")
mw.WordBasic.insert s 
if mw.ActiveDocument.Spellingerrors.count>0 then 
Reporter.ReportEvent 1,"Spelling","spelling error :"&s 
end if
mw.ActiveDocument.Close(False)
next
mw.quit
set mw=nothing

2) Script to check ON the checkboxes in yahoo mail inbox
========================================

Dim d
Set d=Description.Create
d("micclass").value="WebCheckBox"
Set c=Browser("Inbox (17) - Yahoo! Mail").Page("Inbox (17) - Yahoo! Mail").ChildObjects(d)
For i=1 to 10
c(i).set "ON"
Next

3) script to select a mail having subject 'hi' or 'HI'
=================================
n=Browser("yahoo").Page("yahoo").WebTable("Inbox").RowCount
For i=2 to n
s=Browser("yahoo").Page("yahoo").WebTable("Inbox").GetCellData(i,7)
If lcase(trim(s))="hi" Then
Browser("yahoo").Page("yahoo").WebCheckBox("index:="&i-1).set "ON"
End If
Next
4) Function to send a mail
====================
Function SendMail(SendTo, Subject, Body, Attachment) 
Set otl=CreateObject("Outlook.Application")
Set m=otl.CreateItem(0) 
m.to=SendTo 
m.Subject=Subject 
m.Body=Body 
If (Attachment <> "") Then 
Mail.Attachments.Add(Attachment)
End If
m.Send 
otl.Quit 
Set m = Nothing 
Set otl = Nothing
End Function
Call SendMail("nagesh.rao46@gmail.com","hi","This is test mail for tsting","")
Adv VBScripts

5) Open Internet Explorer and navigate to yahoo mail
===================================
Dim ie
Set ie=CreateObject("InternetExplorer.Application")
ie.Visible=True
ie.Navigate "www.yahoomail.com"
x=Browser("CreationTime:=0").GetROProperty("title")
msgbox x

6) Function for Counting Objects from any opened web page

Function Objects_Count(myObject)
   Dim Objects
   Set Objects=Description.Create
 Objects("micclass").value=myObject
 Set Object=Browser("title:=.*").Page("title:=.*").ChildObjects(Objects)
 TotObjects=Object.Count
 Msgbox TotObjects
End Function
Call Objects_Count("WebButton")


1)    Database Scripts-I
2)    
1) Get Test Data From a Database and use in Data Driven Testing (through Scripting)
3)      
4)     Dim objCon, objRs
5)     'Creating an automation object in database connection class, it is used for connecting to databases.
6)     Set objCon=CreateObject("Adodb.Connection")
7)     'Creating an automation object in database record set class, it is used for performing operations on database tables(records).
8)     Set objRs= CreateObject("Adodb.Recordset")
9)     'Establishing connection string for Ms-Access database.
10)  objCon.Provider=("Microsoft.Jet.oledb.4.0")
objCon.Open "C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\Flights.mdb"
objRs.Open "Select * from Login", objCon
Do Until objRs.EOF=True
SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set objRs.Fields("Agent")
Dialog("Login").WinEdit("Password:").Set objRs.Fields("Pwd")
Dialog("Login").WinButton("OK").Click
Window("Flight Reservation").Close
objRs.MoveNext
Loop
objRs.Close
objCon.Close
Set objCon=Nothing
Set objRs=Nothing
11)   
12)  2) Exporting Data from a Database to an Excel Sheet
13)   
14)  1) Dim con,rs
15)  2) Set con=createobject("adodb.connection")
16)  3) Set rs=createobject("adodb.recordset")
17)  4) con.provider="microsoft.jet.oledb.4.0"
18)  5) con.open"C:\Documents and Settings\admin\My Documents\Gcreddy.mdb"
19)  6) rs.open"select*from Login",con
20)  7) Set ex=createobject("Excel.Application")
21)  8) Set a=ex.workbooks.open("C:\Documents and Settings\admin\My Documents\Gcreddy.xls")
22)  9) Set b=a.worksheets("sheet1")
23)  10) i=1
24)  11) Do While Not rs.EOF
25)  12) b.cells (i,1).value=rs.fields("agent")
26)  13) b.cells(i,2).value=rs.fields("password")
27)  14) rs.movenext
  15) i=i+1
   16) Loop
  17) a.save
  18) a.close
  
33) 3) Exporting Data from a Database to a Text file
 
34)  Dim objCon,objRs,ObjFso,myFile,myData,rc,r
35)  Set objCon=createobject("Adodb.connection")
36)  Set objRs=createobject("Adodb.Recordset")
37)  set objFso=createobject("Scripting.Filesystemobject")
38)  Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr\My Documents\gcreddy.txt",8)
39)  objcon.provider=("Microsoft.jet.oledb.4.0")
40)  objcon.open"C:\Documents and Settings\gcr\My Documents\gcreddy.mdb"
41)  objrs.open "select * from login",objCon
42)  r=1
43)  Do until objRs.EOF
44)  a=objRs.Fields ("Agent")
45)  b=objRs.Fields ("Pwd")
46)  myFile.Writeline a &","& b
47)  r=r+1
48)  objRs.MoveNext
49)  Loop
50)  myFile.Close
51)  objCon.Close
52) 
4) Connecting to a SQL Sever database
53)   
54)  Const adOpenStatic = 3
55)  Const adLockOptimistic = 3
56)   
57)  Set objConnection = CreateObject("ADODB.Connection")
58)  Set objRecordSet = CreateObject("ADODB.Recordset")
59)   
60)  objConnection.Open _
61)  "Provider=SQLOLEDB;Data Source=atl-sql-01;" & _
62)  "Trusted_Connection=Yes;Initial Catalog=Northwind;" & _
63)  "User ID=fabrikam\kenmyer;Password=34DE6t4G!;"
64)   
65)  objRecordSet.Open "SELECT * FROM Customers", _
66)  objConnection, adOpenStatic, adLockOptimistic
67)   
68)  objRecordSet.MoveFirst
69)   
70)  Wscript.Echo objRecordSet.RecordCount
71)   
72)  5) Open a Database Using a DSN
73)   
74)  Const adOpenStatic = 3
75)  Const adLockOptimistic = 3
76)   
77)  Set objConnection = CreateObject("ADODB.Connection")
78)  Set objRecordSet = CreateObject("ADODB.Recordset")
79)   
80)  objConnection.Open _
81)  "Northwind;fabrikam\kenmyer;34ghfn&!j"
82)   
83)  objRecordSet.Open "SELECT * FROM Customers", _
84)  objConnection, adOpenStatic, adLockOptimistic
85)   
86)  objRecordSet.MoveFirst
87)   
88)  Wscript.Echo objRecordSet.RecordCount
89)   
90)   
91)  6) Open Two Recordsets
92)   
93)   
94)  Const adOpenStatic = 3
95)  Const adLockOptimistic = 3
96)   
97)  Set objConnection = CreateObject("ADODB.Connection")
98)  Set objRecordSet = CreateObject("ADODB.Recordset")
99)  Set objRecordSet2 = CreateObject("ADODB.Recordset")
100)      
101)     objConnection.Open _
102)     "Provider= Microsoft.Jet.OLEDB.4.0; " & _
103)     "Data Source=inventory.mdb"
104)      
105)     objRecordSet.Open "SELECT * FROM GeneralProperties Where ComputerName = 'Computer1'", _
106)     objConnection, adOpenStatic, adLockOptimistic
107)      
108)     objRecordSet.MoveFirst
109)      
110)      
111)     objRecordSet2.Open "SELECT * FROM Storage Where ComputerName = 'Computer1'", _
112)     objConnection, adOpenStatic, adLockOptimistic
113)      
114)     objRecordSet2.MoveFirst
115)      
116)     Do Until objRecordset.EOF
117)     Wscript.Echo objRecordset.Fields.Item("ComputerName")
118)     Wscript.Echo objRecordset.Fields.Item("OSName")
119)     objRecordSet.MoveNext
120)     Loop
121)      
122)     Do Until objRecordset2.EOF
123)     Wscript.Echo objRecordset2.Fields.Item("DriveName"), _
124)     objRecordset2.Fields.Item("DriveDescription")
125)     objRecordSet2.MoveNext
126)     Loop
127)      
128)     objRecordSet.Close
129)     objRecordSet2.Close
130)     objConnection.Close
131)      
132)      
133)     7) Searching a Database Using String Criteria
134)      
135)     Const adOpenStatic = 3
136)     Const adLockOptimistic = 3
137)      
138)     Set objConnection = CreateObject("ADODB.Connection")
139)     Set objRecordSet = CreateObject("ADODB.Recordset")
140)      
141)     objConnection.Open _
142)     "Provider = Microsoft.Jet.OLEDB.4.0; " & _
143)     "Data Source = eventlogs.mdb"
144)      
145)     objRecordSet.Open "SELECT * FROM EventTable " & _
146)     "WHERE Type = 'Error'", objConnection, adOpenStatic, _
147)     adLockOptimistic
148)      
149)     objRecordSet.MoveFirst
150)      
151)     Wscript.Echo "Number of records: " & objRecordset.RecordCount
152)      
153)     objRecordSet.Close
154)     objConnection.Close
155)      
156)                Database Scripts-II
157)      
158)     1) Insert Data into a database table using Database Command Object

Dim objCon,objCom
Set objCon=Createobject("ADODB.connection")

objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\gcreddy.mdb;"

Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon

objCom.CommandText="insert into Emp values('G C Reddy',88233,30000)"
objCom.Execute

objCon.Close
Set objCom=Nothing
Set objCon=Nothing

2) Insert multiple sets of Data (using Excel sheet)  into a database table using Database Command Object

Dim objCon,objCom,strEmpName,intEmpNo,intEmpSal,intRowcount,i
Set objCon=Createobject("ADODB.connection")

objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\gcreddy.mdb;"

Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon

Datatable.AddSheet("input")
Datatable.ImportSheet "C:\gcreddy.xls",1,"input"
intRowcount=Datatable.GetSheet("input").GetRowCount
Msgbox intRowcount
For i=1 to intRowcount step 1
    DataTable.SetCurrentRow(i)
    strEmpName=    DataTable.Value(1,"input")
    intEmpNo=    DataTable.Value(2,"input")
    intEmpSal=    DataTable.Value(3,"input")
objCom.CommandText="insert into Emp values( '"&strEmpName&" ',"&intEmpNo&","&intEmpSal&")"
objCom.Execute

Next

objCon.Close
Set objCom=Nothing
Set objCon=Nothing

3) Fetch data from a database, and compare with expected data in Excel file.
----------

Dim objCon, objRs, objExcel, myFile, mysheet
Set objCon=CreateObject("Adodb.Connection")
Set objRs= CreateObject("Adodb.Recordset")
Set objExcel=CreateObject("Excel.Application")
Set myFile=objExcel.Workbooks.Open ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\TestData2.xls")
Set mySheet=myFile.Worksheets("Sheet1")
Rc=mySheet.usedrange.rows.count
'Msgbox Rc
objCon.Provider=("Microsoft.Jet.oledb.4.0")
objCon.Open "C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\Comp.mdb"
objRs.Open "Select EMPName from Employee", objCon



Do Until objRs.EOF=True
x=objRs.Fields("EMPName")
    For j= 2 to Rc
y=mySheet.cells(j,"A")

If x=y  Then
    Reporter.ReportEvent micPass,"Res","Name: "& y &"  Available"
'    Else
'Reporter.ReportEvent micFail,"Res","Name: "& y &"  Not Available"

End If
    Next
   
objRs.MoveNext
Loop
objExcel.Quit
Set objExcel=Nothing
objRs.Close
objCon.Close
Set objRs=Nothing
Set objCom=Nothing
------------------------------------




1)     Create a Folder

Option Explicit
Dim objFSO, objFolder, strDirectory
strDirectory = "D:\Gcreddy"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.CreateFolder(strDirectory)

2) Delete a Folder

Set oFSO = CreateObject("Scripting.FileSystemObject")
oFSO.DeleteFolder("E:\Gcreddy")

3) Copying Folders

Set oFSO=createobject("Scripting.Filesystemobject")
oFSO.CopyFolder "E:\gcr", "C:\jvr", True

4) Checking weather the folder available or not, if not creating the folder

Option Explicit
Dim objFSO, objFolder, strDirectory
strDirectory = "D:\Gcreddy"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
msgbox strDirectory & " already created "
else
Set objFolder = objFSO.CreateFolder(strDirectory)
end if

5) Returning a collection of Disk Drives

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set colDrives = oFSO.Drives
For Each oDrive in colDrives
MsgBox "Drive letter: " & oDrive.DriveLetter
Next


6) Getting available space on a Disk Drive

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oDrive = oFSO.GetDrive("C:")
MsgBox "Available space: " & oDrive.AvailableSpace


 Computer File System
It is a feature of the Operating System, used to Create/Modify/view/delete Drives, Folders and Files

    OS Distribution
Operating System and Other Utilities
   
FileSystemObject

VBScript has Provided FileSystemObject to perform file system operations through scripting

Dim objFso
'Creating an Automation Object in File System class, that can be used to perform Operations on Computer File System
Set objFso=CreateObject("scripting.FileSystemObject")

1) Creating a File

Dim objFso
Set objFso=CreateObject("scripting.FileSystemObject")
objFso.CreateTextFile ("E:\Gcreddy.txt")
objFso.CreateTextFile ("E:\Gcreddy.doc")
objFso.CreateTextFile ("E:\Gcreddy.xls")
objFso.CreateTextFile ("E:\Gcreddy.pdf")

Note: We can Create other files also, but they act as Text/Flat Files
Set objFile = objFSO.CreateTextFile("E:\Gcreddy.txt")

2) Checking weather the File is available or not, if not creating the File

strDirectory="E:\"
strFile="Gcreddy.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile("E:\Gcreddy.txt")
End if

3) Reading Data character by character from a Flat File

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("E:\Gcreddy.txt", 1)
Do Until objFile.AtEndOfStream
strCharacters = objFile.Read(1)
msgbox strCharacters
Loop


4) Reading Data line by line from a Flat File

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("E:\Gcreddy.txt", 1)
Do Until objFile.AtEndOfStream
strCharacters = objFile.Readline
msgbox strCharacters
Loop

5) Data Driven Testing by fetching Test data directly from a Text file.

**************************************************
'Test Requirement: Data Driven Testing by Fetching Test data directly from a Text file.

'Author:
G C Reddy

'Date of Creation: 13-08-2010

'Pre-requisites:

'gcr.txt (Test Data)

'Test Flow:
'Creating an Automation Object in FileSystem class
'Opening the External Test Data file using the Object
'Read the Data & Split the Data
'Generating the Login Operation
'Pass Parameters
'*************************************************

Dim objFso, myFile, myLine, myField
Set objFso=CreateObject("Scripting.FileSystemObject")
Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\vindod.txt",1) '1 for Read, 2-Write & 8-Append
myFile.SkipLine

Do Until myFile.AtEndOfStream
myLine=myFile.ReadLine
myField=Split(myLine,",")
SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"
Dialog("text:=Login").Activate
Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set myField(0)
Dialog("text:=Login").WinEdit("attached text:=Password:").Set myField(1)
wait 2
Dialog("text:=Login").WinButton("text:=OK").Click
Window("text:=Flight Reservation").Close
Loop
myFile.Close
Set objFso=Nothing
6) Writing data to a text file

Dim Stuff, myFSO, WriteStuff, dateStamp
dateStamp = Date()
Stuff = "I am Preparing this script: " &dateStamp
Set myFSO = CreateObject("Scripting.FileSystemObject")
Set WriteStuff = myFSO.OpenTextFile("e:\Gcreddy.txt", 8, True)
WriteStuff.WriteLine(Stuff)
WriteStuff.Close
SET WriteStuff = NOTHING
SET myFSO = NOTHING

7) Delete a text file

Set objFSO=createobject("Scripting.filesystemobject")
Set txtFilepath = objFSO.GetFile("E:\gcr.txt")
txtFilepath.Delete()

8) Checking weather the File is available or not, if available delete the File

strDirectory="E:\"
strFile="gcr.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strDirectory & strFile) Then
Set objFile = objFSO.Getfile(strDirectory & strFile)
objFile.delete ()
End if

9) Comparing two text files

Dim f1, f2
f1="e:\Gcreddy1.txt"
f2="e:\Gcreddy2.txt"
Public Function CompareFiles (FilePath1, FilePath2)
Dim FS, File1, File2
Set FS = CreateObject("Scripting.FileSystemObject")
If FS.GetFile(FilePath1).Size <> FS.GetFile(FilePath2).Size Then
CompareFiles = True
Exit Function
End If
Set File1 = FS.GetFile(FilePath1).OpenAsTextStream(1, 0)
Set File2 = FS.GetFile(FilePath2).OpenAsTextStream(1, 0)
CompareFiles = False
Do While File1.AtEndOfStream = False
Str1 = File1.Read
Str2 = File2.Read
CompareFiles = StrComp(Str1, Str2, 0)
If CompareFiles <> 0 Then
CompareFiles = True
Exit Do
End If
Loop
File1.Close()
File2.Close()
End Function
Call Comparefiles(f1,f2)
If CompareFiles(f1, f2) = False Then
MsgBox "Files are identical."
Else
MsgBox "Files are different."
End If

10) Counting the number of times a word appears in a file

sFileName="E:\gcr.txt"
sString="gcreddy"
Const FOR_READING = 1
Dim oFso, oTxtFile, sReadTxt, oRegEx, oMatches
Set oFso = CreateObject("Scripting.FileSystemObject")
Set oTxtFile = oFso.OpenTextFile(sFileName, FOR_READING)
sReadTxt = oTxtFile.ReadAll
Set oRegEx = New RegExp
oRegEx.Pattern = sString
oRegEx.IgnoreCase = bIgnoreCase
oRegEx.Global = True
Set oMatches = oRegEx.Execute(sReadTxt)
MatchesFound = oMatches.Count
Set oTxtFile = Nothing : Set oFso = Nothing : Set oRegEx = Nothing
msgbox MatchesFound

11) Read a CSV File Using Database Techniques

On Error Resume Next

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

strPathtoTextFile = "C:\Databases\"

objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=" & strPathtoTextFile & ";" & _
          "Extended Properties=""text;HDR=YES;FMT=Delimited"""

objRecordset.Open "SELECT * FROM PhoneList.csv", _
          objConnection, adOpenStatic, adLockOptimistic, adCmdText

Do Until objRecordset.EOF
    Wscript.Echo "Name: " & objRecordset.Fields.Item("Name")
    Wscript.Echo "Department: " & _
        objRecordset.Fields.Item("Department")
    Wscript.Echo "Extension: " & objRecordset.Fields.Item("Extension")  
    objRecordset.MoveNext
Loop


12) Read a Text File into an Array

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
    ("e:\gcreddy.txt", ForReading)

Do Until objTextFile.AtEndOfStream
    strNextLine = objTextFile.Readline
    arrServiceList = Split(strNextLine , ",")
    Wscript.Echo "Server name: " & arrServiceList(0)
    For i = 1 to Ubound(arrServiceList)
        Wscript.Echo "Service: " & arrServiceList(i)
    Next
Loop

13)  'Calculate size of a Text file

Dim objFso, File1,File2
File1="C:\Documents and Settings\1 RIGHATWAY\Desktop\xyz.txt"
Set objFso=CreateObject("
Scripting.FileSystemObject")
x= objFso.GetFile(File1).Size
Msgbox x& "  Bytes"

14) 'Test Requirement: Open 1 to 10 orders in Flight Reservation , Capture Customer names and Export into a Text file

'Test Flow:
'Login Operation
'Open Order Operation and form the Loop to open 1 to 10 Orders
'Capture Cusomer names using GetROProperty Method
'Create File system Object and Open the Text file using  the Object and Export Cusomer names
'----------------------------------------------------------------------------
Option Explicit
Dim Order_Number, Customer_Name, objFso, myFile
Set objFso=CreateObject("Scripting.FileSystemObject")
Set myFile= objFso.CreateTextFile ("C:\Documents and Settings\1 RIGHATWAY\Desktop\abcNew.txt",2)
myFile.WriteLine "Cusomer Names"
myFile.WriteLine "--------------------"
If Not Window("Flight Reservation").Exist(3)  Then
SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set "asdf"
Dialog("Login").WinEdit("Password:").SetSecure "4c48590870466b8dc050bbd24e816890c747ccf8"
Dialog("Login").WinButton("OK").Click
End If
For Order_Number= 1 to 10 step 1
Window("Flight Reservation").Activate
Window("Flight Reservation").WinButton("Button").Click
Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set Order_Number
Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
Customer_Name = Window("Flight Reservation").WinEdit("Name:").GetROProperty("text")
wait (2)
myFile.WriteLine Customer_Name
Next
myFile.Close
Set objFso=Nothing

15)
'******************************************************
'Test Requirement: Capturing all Buttons Names from the Login Dialog box and exporting to a Text file


'Pre-requasites:
'gcr.txt

'Test Flow:
'Creating an Automation Object in FileSystem class
'Opening the External Test Data file using the Object
'Creating Collection object and Capturing Button Names using the Object
'Writing Button Names to an External Text file
'********************************************************

Dim objFso, myFile, oButton, Buttons, TotButtons
Set objFso=CreateObject("Scripting.FileSystemObject")
Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\vindod.txt",2) '1 for Read, 2-Write & 8-Append
myFile.WriteLine "Button Names"
myFile.WriteLine "----------"
Set oButton=Description.Create
oButton("micclass").value="WinButton"
SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"
Set Buttons=Dialog("text:=Login").ChildObjects(oButton)
TotButtons=Buttons.Count

For i= 0 to TotButtons-1
    myButton=Buttons(i).GetRoProperty("text")
myFile.WriteLine myButton
Next

myFile.Close
Set objFso=Nothing 
MS Word Scripts

1) create a word document and write some data
====================
dim mw
set mw=CreateObject("Word.Application")
mw.Documents.Add
mw.selection.typetext "hello"
mw.ActiveDocument.SaveAs "e:\gcreddy.doc"
mw.quit
set mw=nothing

2) Create word, Create table and write all the services names
========================================
Set mw = CreateObject("Word.Application")
mw.Visible = True
Set dc = mw.Documents.Add()
Set objRange = dc.Range()
dc.Tables.Add
objRange,1,3
Set objTable = dc.Tables(1)
x=1
strComputer = "."
Set wms=GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = wms.ExecQuery("Select * from Win32_Service")
For Each s in colItems
If x > 1 Then
objTable.Rows.Add()
End If
objTable.Cell(x, 1).Range.Font.Bold = True
objTable.Cell(x, 1).Range.Text = s.Name
objTable.Cell(x, 2).Range.text = s.DisplayName
objTable.Cell(x, 3).Range.text = s.State
x = x + 1
Next


3) script to display all the doc files in all the drives in the system
=========================================
Dim mw
Set mw=CreateObject("Word.Application")
Set fs=createobject("Scripting.FileSystemObject")
Set d=fs.Drives
mw.FileSearch.FileName="*.doc"
For each dr in d
msgbox dr
mw.FileSearch.LookIn=dr
mw.FileSearch.SearchSubFolders=True
mw.FileSearch.Execute
For each i in mw.FileSearch.FoundFiles
print i
Set f=fs.GetFile(i)
print f.Name&" "&f.Size&" "&f.DateCreated
print "-------------------------------------------------------------------"
Next
Next
mw.Quit 


4) Counting the number of times a word appears in a word document
=========================================

Set objWord=CreateObject("Word.Application")
Set myfile=objWord.Documents.Open ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\xyz.doc")
strText="gcreddy"
strRead=myfile.Content
Set RegExp=new regexp
regexp.ignorecase=True
regexp.global=True
regexp.pattern=strText
Set matches=regexp.execute(strRead)
matchesFound=matches.count
msgbox matchesfound
myfile.close
set objFso=Nothing


1) Create an Excel file, enter some data and save the file through VB script?

1) Dim objexcel
2) Set objExcel = createobject("Excel.application")
3) objexcel.Visible = True
4) objexcel.Workbooks.add
5) objexcel.Cells(1, 1).Value = "Testing"
6) objexcel.ActiveWorkbook.SaveAs("f:\exceltest.xls")
7) objexcel.Quit

2) Check if the Excel file exists or not, if exists open the file and enter some data , If not Exists create the file and enter some data and save the file through VB script?

Dim objExcel, FilePath
FilePath="C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\gcr.xls"
Set objExcel=CreateObject("Excel.Application")
set objFso=CreateObject("Scripting.FileSystemObject")
objExcel.Visible=True

If Not objFso.FileExists(FilePath)  Then
objExcel.Workbooks.Add
objExcel.Cells(1,1).value="QTP"
objExcel.ActiveWorkbook.SaveAs (FilePath)

Else
set myFile= objExcel.Workbooks.Open (FilePath)
Set mySheet=myFile.Worksheets("Sheet1")
mySheet.cells(1,1).value="QTP"
objExcel.ActiveWorkbook.Save
End If
objExcel.Quit
Set objExcel=Nothing 

3) Data Driven Testing through an External Excel Sheet


1) Set myExcel=Createobject("Excel.Application")
2) Set myFile=myExcel.workbooks.open ("C:\Documents and Settings\admin\My Documents\gcreddy.xls")
3) Set mySheet=myFile.worksheets("Sheet1")
4) Rows_Count=mySheet.usedrange.rows.count
5) For i= 1 to Rows_Count
6) Agent=mySheet.cells(i,"A")
7) pwd=mySheet.Cells(i,"B")
8) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open"
9) Dialog("Login").Activate
10) Dialog("Login").WinEdit("Agent Name:").Set Agent
11) Dialog("Login").WinEdit("Password:").SetSecure pwd
12) Dialog("Login").WinEdit("Password:").Type micReturn
13) Window("Flight Reservation").Close
14) Next

4) Compare two excel files


Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook1= objExcel.Workbooks.Open("E:\gcreddy1.xls")
Set objWorkbook2= objExcel.Workbooks.Open("E:\gcreddy2.xls")
Set objWorksheet1= objWorkbook1.Worksheets(1)
Set objWorksheet2= objWorkbook2.Worksheets(1)
For Each cell In objWorksheet1.UsedRange
If cell.Value <> objWorksheet2.Range(cell.Address).Value Then
msgbox "value is different"
Else
msgbox "value is same"
End If
Next
objWorkbook1.close
objWorkbook2.close
objExcel.quit
set objExcel=nothing

5) Data Driven Testing using Data Table methods

Datatable.AddSheet "gcreddy"
Datatable.ImportSheet "C:\Documents and Settings\Administrator\Desktop\gcreddy.xls",1,3
n=datatable.GetSheet (3).GetRowCount
For i= 1 to n
Datatable.SetCurrentRow(i)
Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set datatable("agent",3)
Dialog("Login").WinEdit("Password:").Set datatable("pwd",3)
Dialog("Login").WinButton("OK").Click
Window("Flight Reservation").Close
Next

Example 2):

Datatable.AddSheet "gcreddy"
Datatable.ImportSheet "C:\Documents and Settings\Administrator\Desktop\gcreddy.xls",1,3
n=datatable.GetSheet (3).GetRowCount
For i= 1 to n
Datatable.SetCurrentRow(i)
VbWindow("Form1").Activate
VbWindow("Form1").VbEdit("val1").Set datatable("V1",3)
VbWindow("Form1").VbEdit("val2").Set datatable("V2",3)
VbWindow("Form1").VbButton("ADD").Click
eres= Datatable.Value ("res",3)
ares=VbWindow("Form1").VbEdit("res").GetROProperty ("text")
If eres=ares Then
datatable("res",3)=pass
else
datatable("res",3)=fail
End If
Next

6) Open an Excel Spreadsheet


Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Scripts\gcreddy.xls")

7) Read an Excel Spreadsheet


Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open _
("C:\Scripts\New_users.xls")

intRow = 2

Do Until objExcel.Cells(intRow,1).Value = ""
Wscript.Echo "CN: " & objExcel.Cells(intRow, 1).Value
Wscript.Echo "sAMAccountName: " & objExcel.Cells(intRow, 2).Value
Wscript.Echo "GivenName: " & objExcel.Cells(intRow, 3).Value
Wscript.Echo "LastName: " & objExcel.Cells(intRow, 4).Value
intRow = intRow + 1
Loop

objExcel.Quit

8) Add Formatted Data to a Spreadsheet


Set objExcel = CreateObject("Excel.Application")

objExcel.Visible = True
objExcel.Workbooks.Add
objExcel.Cells(1, 1).Value = "Test value"
objExcel.Cells(1, 1).Font.Bold = TRUE
objExcel.Cells(1, 1).Font.Size = 24
objExcel.Cells(1, 1).Font.ColorIndex = 3

9) Sort an Excel Spreadsheet on Three Different Columns


Const xlAscending = 1
Const xlDescending = 2
Const xlYes = 1

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = _
objExcel.Workbooks.Open("C:\Scripts\Sort_test.xls")

Set objWorksheet = objWorkbook.Worksheets(1)
Set objRange = objWorksheet.UsedRange

Set objRange2 = objExcel.Range("A1")
Set objRange3 = objExcel.Range("B1")
Set objRange4 = objExcel.Range("C1")

objRange.Sort objRange2,xlAscending,objRange3,,xlDescending, _
objRange4,xlDescending,xlYes
10) Short an excel sheet column

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add
Set objWorksheet = objWorkbook.Worksheets(1)

objExcel.Cells(1, 1).Value = "5"
objExcel.Cells(2, 1).Value = "1"
objExcel.Cells(3, 1).Value = "0"
objExcel.Cells(4, 1).Value = "3"


Set objRange=objworksheet.usedrange
objrange.sort(objrange)
11) Add New Sheet to Excel File

Dim objExcel
Set objExcel = createobject("Excel.Application")
objExcel.Visible=True
objExcel.Workbooks.Add
objexcel.ActiveWorkbook.SaveAs ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\gcreddy.xls")

objExcel.Worksheets.Add
objExcel.ActiveWorkbook.Save
objExcel.Quit
Set objExcel=Nothing
12) Rename Sheets in an Excel File (WorkBook)

Dim objExcel
Set objExcel = createobject("Excel.Application")
objExcel.Visible=True
objExcel.Workbooks.Add
objexcel.ActiveWorkbook.SaveAs ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\gcreddy.xls")

objExcel.Worksheets("Sheet1").Name="gcr"
objExcel.Worksheets("Sheet2").Name="qtp"
objExcel.Worksheets("Sheet3").Name="training"

objExcel.ActiveWorkbook.Save
objExcel.Quit
Set objExcel=Nothing

13) Add a Sheet to an Excel File (WorkBook) and change the Position
Dim objExcel
Set objExcel = createobject("Excel.Application")
objExcel.Visible=True
Set myFile= objExcel.Workbooks.Add
objexcel.ActiveWorkbook.SaveAs ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\gcreddy.xls")

objExcel.Worksheets.Add
myFile.Sheets("Sheet4").Move, myFile.Sheets(4)

objExcel.ActiveWorkbook.Save
objExcel.Quit
Set objExcel=Nothing
System Administration

1) Getting Local Computer Information


Set objComputer = CreateObject("Shell.LocalMachine")

Wscript.Echo "Computer name: " & objComputer.MachineName
Wscript.Echo "Shutdown allowed: " & objComputer.IsShutdownAllowed
Wscript.Echo "Friendly UI enabled: " & objComputer.IsFriendlyUIEnabled
Wscript.Echo "Guest access mode: " & objComputer.IsGuestAccessMode
Wscript.Echo "Guest account enabled: " & _
    objComputer.IsGuestEnabled(0)
Wscript.Echo "Multiple users enabled: " & _
    objComputer.IsMultipleUsersEnabled
Wscript.Echo "Offline files enabled: " & _
    objComputer.IsOfflineFilesEnabled
Wscript.Echo "Remote connections enabled: " & _
    objComputer.IsRemoteConnectionsEnabled
Wscript.Echo "Undock enabled: " & objComputer.IsUndockEnabled


2) Restart a Computer

strComputer = "atl-dc-01"
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate,(Shutdown)}!\\" & _
        strComputer & "\root\cimv2")

Set colOperatingSystems = objWMIService.ExecQuery _
    ("Select * from Win32_OperatingSystem")

For Each objOperatingSystem in colOperatingSystems
    objOperatingSystem.Reboot()
Next

3) Shut Down a Computer

strComputer = "."
Set objWMIService = GetObject_
    ("winmgmts:{impersonationLevel=impersonate,(Shutdown)}\\" & _
        strComputer & "\root\cimv2")

Set colOperatingSystems = objWMIService.ExecQuery _
    ("Select * from Win32_OperatingSystem")

For Each objOperatingSystem in colOperatingSystems
    objOperatingSystem.Win32Shutdown(1)
Next
 
4) Modify System Startup Delay

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colStartupCommands = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")

For Each objStartupCommand in colStartupCommands
    objStartupCommand.SystemStartupDelay = 10
    objStartupCommand.Put_
Next

QTP Other Topics

New Features of QTP 10.0

QuickTest 10.00 now offers the following new features

• Centrally Manage and Share Testing Assets, Dependencies, and Versions in Quality Center 10.00
• Perform Single-User Local System Monitoring While Running Your Tests
• Improve Portability by Saving Copies of Tests Together with Their Resource Files
• Call Actions Dynamically During the Test Run
• Develop Your Own Bitmap Checkpoint Comparison Algorithm
• Centrally Manage Your Work Items and ToDo Tasks in the To Do Pane
• Improve Test Results Analysis with New Reporting Functionality
• Test Standard and Custom Delphi Objects Using the Delphi Add-in and Delphi Add-in Extensibility

1. Centrally Manage and Share Testing Assets, Dependencies, and Versions in Quality Center 10.00 

QuickTest Professional 10.00 has a powerful set of new Quality Center 10.00 integration capabilities for QuickTest assets.*
These integration capabilities include:
• New resources and dependencies model for storing and managing shared assets
• Support for asset versioning and baselines
• Asset Comparison Tool for comparing versions of individual QuickTest assets and Asset Viewer for viewing an earlier version of a QuickTest asset
• A special tool for Quality Center administrators that upgrades all QuickTest assets to use these new features.
* QuickTest assets include tests, components, application areas, and the resources associated with them, such as shared object repositories, function libraries, recovery scenarios, and external data tables.

2. Perform Single-User Local System Monitoring While Running Your Tests 

The new local system monitoring feature (File > Settings > Local System Monitor) enables you to monitor the local (client-side) computer resources used by the application instance you are testing during a run session.
You can monitor a number of different system counters to view the effects your application has on the system. You can also define upper limits for the counters. If any of the specified counters exceed these limits, the test run will fail.
Additionally, you can export the data from the System Monitor tab to a variety of file types.
The results generated for the counters you monitor are displayed as a line chart in a special System Monitor tab in the Test Results window.


The System Monitor tab in the Test Results window 

The points in the chart are synchronized with the steps in the Run Results tree. When you select a step in the tree, the (red) Current Step line jumps to the corresponding location in the chart.
You can also export the data from the chart so it can be further analyzed in other programs.

Migrating QTP 9.5 version to QTP 10.00 Version
 

1. If the scripts are in QC we can follow below method

A. If all scripts are in Quality Center then you can simply use the "Asset Upgrade Tool for QC". There is a folder with that name on the QuickTest installation DVD.

2. If the upgrade tool doesn't work on any version earlier than v10.
There is another way to upgrade those scripts from QTP 9.5 to QTP 10?

A. you have to open the script in QTP 10 and save the same which is the suggested process of HP. request HP to provide a tool for this.


--------------------------------------------------------------------------------
From QTP help ("Convert a Set of Tests from an Older QuickTest Version to the Current Version" example in Open Method of Application object):

'***********************************
'Description:
'
'This example specifies a folder in which tests from an older QuickTest version are
'stored and then loops through each test in the folder (and its subfolders) to open
'each one and save it in the current version format.
'
'*********************************************

Dim qtApp 'As QuickTest.Application ' Declare the Application object variable
Dim filesys
Dim maindir
Dim testCol
Dim checkfolder

' Create the QuickTest Professional object
Set qtApp = CreateObject("QuickTest.Application")
qtApp.Launch
qtApp.Visible = True

' Get the collection of test scripts
Set filesys = CreateObject("Scripting.FileSystemObject")

' TO DO: Sepecify the test script directory....
Set maindir = filesys.GetFolder("C:\temp")
Set testCol = maindir.SubFolders

' Loop through each test in the collection
For Each fl In testCol

' Verify the folder is a QTP test
checkfolder = fl.Path & "\Action0"
If (filesys.FolderExists(checkfolder)) Then ' The folder is a QTP test folder

' Convert test
qtApp.Open fl.Path, False, False

' wscript.sleep 1000

' Save converted test
qtApp.Test.Save

End If
Next

qtApp.Quit

' Release the File System Objects
Set testCol = Nothing
Set maindir = Nothing
Set filesys = Nothing

' Release the QuickTest Professional application object
Set qtApp = Nothing

Supposedly, this should do it if you run it on a machine with QTP 10 installed - though you would have to tweak it a bit for tests stored in QC. The idea is to open each test in edit mode, then save it.


7 Steps to Improve Skills in QTP

I) QTP Testing Process

In order to use QTP IDE properly, you should have good command on QTP Testing process.
a) Planning
a) Analyzing the AUT
b) Implementing Automation Framework
c) Creating/Selecting Test cases
d) Collecting Test Data
e) Automation Infrastrucure development
f) Tool settings Configuration & Globalization

b) Generating the basic Test

1) Keyword driven methodology/Shared object repository method/Preparing the script manually
2) Descriptive programming/Programmatic Descriptions
i) Entering Programmatic Descriptions Directly into Statements
ii) Using Description Objects for Programmatic Descriptions
iii) Retrieving Child Objects
iv) Using the Index Property in Programmatic Descriptions

c) Enhancing the Test

a) Adding Comments
b) Creating Checkpoints Programmatically
c) Synchronization
d) Parameterization
e) Inserting Programmatic statements
f) Enhancing Tests with the windows API
g) Calling Functions and/or Actions

d) Debugging the Test

e) Running the Test

f) Analyzing the Test Results

g) Reporting Defects

a. Manual Defect Reporting
b. Tool based Defect Reporting
c. Integration with Quality Center

II) VB Script


VbScript is the QTP Tool Default Scripting Language for applaying Progamming Logic, so learn Vbscript indepth.

Below fundamentals & Features are Important:

a) VBScript Fundamentals

1)Introduction
a) Scripting Languages vs. Programming Languages
b) Basic Features of VBScript
c) Hosting Environments & Script Engines
d) Crating & running a Script

2) Variables and Constants
a) VBScript data types
b) Declaring Variables and Option Explicit Statement
c) Assigning Values to Variables
d) Scalar Variables and Array Variables
e) Dynamic Arrays, Dimensional Arrays
f) Constants
g) Variables Vs. Constants

3) VBScript Operators
a) Operator Precedence
b) Arithmetic Operators
c) Comparison Operators
d) Concatenation Operators
e) Logical Operators

4) Flow Control (I. Conditional Statements)
a) VBScript Conditional Statements
b) Running a state if condition is true (Single line Syntax)
c) Running a block of Statements if Condition is true
d) Running Certain Statements if a Condition is True and Running Others if a Condition is False
e) Deciding Among Several Alternatives (IF..Else If…)
f) Executing a certain block of statements when two / more conditions are True (Nested If...)
g) Deciding Among Several Alternatives (Selct case Statement)

5) Flow Control (II. Looping through the code)
a) Do...Loop (Loops while or until a condition is True.)
b) While...Wend (Loops while a condition is True.)
c) For...Next: Uses a counter to run statements a specified number of times.
d) For Each...Next (Repeats a group of statements for each item in a collection or each element of an array.)
e) Nested Loops

6) VBScript Procedures
a) Sub Procedures
b) Function Procedures
c) Creating & Calling Procedures

7) Coding Conventions
a) Constant Naming Conventions
b) Variable Naming Conventions
c) Variable Scope Prefixes
d) Object Naming Conventions
e) Code Commenting Conventions

b) Advanced VBScript

1) VBScript Intrinsic (Pre-Defined) Functions
a) Conversions
b) Dates/Times
c) Formatting Strings
d) Input/Output
e) Math
f) Miscellaneous
g) Rounding
h) Strings
i) Variants

2) Regular Expressions
a) Uses for Regular Expressions
b) Regular Expression Syntax
c) Build a Regular Expression
d) Order of Precedence
e) Ordinary Characters
f) Character Matching
g) Anchors
h) Alternation and Grouping
i) Backreferences
j) Regular Expression (RegExp) Object

3) File System Operations

a) Computer File System
b) Working with Drives and Folders
c) Working with Flat Files
d) Working with Word Docs
e) Working with Excel Sheets

4) Database Operations

a) ActiveX Data Objects
b) ADODB Connection Object & Recordset Object
c) Test Database Creation & Collecting Test Data
d) Databases Connections (Ms-Access, SQL Server and Oracle)
e) Data Driven Testing by fetching Data from a Database
f) Data Comparisons

5) Methods, Objects and Classes

a) VBScript Global Methods
b) QTP Methods
c) FileSystemObject
d) Dictionary Object
e) Classes

6) Error Handling

a) Error Handling Guidelines
b) Error Handling in QuickTest Professional
c) Error Preventing
d) Synchronization
e) QTP Exit Statements
f) VBScript error handling vs. Recovery Scenarios
g) On Error Statement
h) Err Object

III) Automation Framework

Automation Framework is a Systamatic Approach for Automating, Software Testing Process.
In order to Create & Run Tests as well oraganizing & Managing Automation Resources, a well defined Framework required.

Framework may vary from one company to another.

Below concepts are important to learn:
o Test Automation Framework
o Types of Framework
o Keyword Driven Framework
o Framework Structure
o Developing a Robust Automation Framework
o Implementing & Managing Automation Resources

IV) COM/DCOM Technologies

When working with QTP, It is important to know, Microsoft Applications like:

o MS Excel,
o Ms Word,
o Outlook Express and
o Internet Explorer

V) XML

XML is an extremely popular and useful format. It can be used in several areas in QTP.
Ex:
o Exporting objects,
o Environment Variables,
o Data driven Testing
o Data transporting etc.

VI) SQL

SQL Knowledge is highly recomendable in order to perform Database Testing using QTP
Below concepts are important:
o Database Fundamentals
o Data Creation & Exporting
o Database Connections
o Select Statements

VII) HTML, DOM
In order to work with Web based Applications, It is important to femiliar with web technologies like:
o HTML, DHTML
o Flash
o HTTP like Protocols
o DOM (Documentation Object Model

Jan 20, 2010

Error Handling in QTP


Error Handling in QTP

Error Handling:
Error handling refers to the anticipation, detection, and resolution of programming, application, and communications errors.

Within every Script we have to think about possible exceptions and how to handle them. Especially in the uppermost layers of the script, it is important to handle all exceptions.

Error Handling in QuickTest Professional:
QTP and VBScript give the Test Engineer some tools to handle errors and Exceptions.

Error Preventing:

A good method for using error handling is to try to prevent them.

When an error occurred, Report it in detail. When working with GUI objects, use the Window.Exist property. Every If…Then..End If statement has the Else part, the same for
Select Case. Use Case Else.

Error Handling Methods in QTP and VB Script:

a)    Synchronization
b)    Exist Property
c)    Recover Scenarios

d)    On Error Statement

Without an On Error statement, any run-time error that occurs is fatal: an error message is displayed, and execution stops.

Whenever possible, you use structured exception handling in your code, rather than resorting to unstructured exception handling and the On Error statement.

Parts:

GoToline

    Enables the error-handling routine that starts at the line specified in the required line argument. The line argument is any line label or line number. If a run-time error occurs, control branches to the specified line, making the error handler active. The specified line must be in the same procedure as the On Error statement, or a compile-time error will occur.

GoTo 0

    Disables enabled error handler in the current procedure and resets it to Nothing.

GoTo -1

    Disables enabled exception in the current procedure and resets it to Nothing.

Resume Next

    Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred, and execution continues from that point. Use this form rather than On Error GoTo when accessing objects.

on Error Resume Next 

Example1:
Dim a
a = 1
b-2
MsgBox a + b ' displays result without showing error

Example2:

Function Sum(Num1, Num2)
If IsNumeric(Num1) = False Or IsNumeric(Num2) = False Then
On Error Resume Next
Err.Raise vbObjectError + 100, "Sum Function", _
"One or more parameters are invalid."
Exit Function
End If
Sum = Num1 +Num2

End Function
 
Call Sum("gcreddy","QTP") 'Comes out without showing error
Call Sum(100,200) ' returns sum of 100,200 as 300
e)    Error Object

The Err object is an intrinsic object with global scope — there is no need to create an instance of it in your code. 

The properties of the Err object are set by the generator of an error — Visual Basic, an Automation object, or the VBScript programmer.
 
The default property of the Err object is Number.

 Err.Number contains an integer and can be used by an Automation object to return an SCODE.

When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a run-time error in your code, use the Raise method.
The Err object's properties are reset to zero or zero-length strings ("") after an On Error Resume Next statement. The Clear method can be used to explicitly reset Err.
 
Example:

On Error Resume Next
Err.Raise 6   ' Raise an overflow error.
MsgBox ("Error # " & CStr(Err.Number) & " " & Err.Description)
Err.Clear      ' Clear the error.

Err Object Properties and Methods

Properties

Description Property
 
HelpContext Property
 
HelpFile Property
 
Number Property
 
Source Property

Methods

Clear Method

Raise Method

f)    Exit Statement

Open 30 to 40 Orders in Flight Reservation Window, if some records not available handle the situation

Option Explicit
Dim Order_Number
If Not Window("Flight Reservation").Exist(3) Then
SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set "gcreddy"
Dialog("Login").WinEdit("Password:").SetSecure "4c2e1e65bf29943393b6940f116d35231ce5fb7e"
Dialog("Login").WinButton("OK").Click
End If

For Order_Number= 30 to 40 step 1
Window("Flight Reservation").Activate
Window("Flight Reservation").WinButton("Button").Click
Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set Order_Number
Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click

If Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").Exist(3) Then
Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click
Window("Flight Reservation").Dialog("Open Order").WinButton("Cancel").Click
Reporter.ReportEvent micWarning,"Res", "Up to "& Order_Number-1 &" Order only available"
Exit For
End If
Next
  



Note:-This Programs are the best and reffed to so many websites

0 comments:

Post a Comment

Bookmark Us

Delicious Digg Facebook Favorites More Stumbleupon Twitter