This knowledge base will be updated on a regular basis so please return or follow us on Twitter to be informed of regular code postings.
Function ExportRunTime (ResName)
'export run time table
DataTable.Export "c:\TestData.xls"
'connect to the resources module
Set oTDC = QCUtil.QCConnection.QCResourceFactory
'Get a collection of all resources in module
Set oRoot = oTDC.NewList("")
'ensure we start with no resources
Set oSub = Nothing
'count the number of resources in the module
iTotalItems = oRoot.Count
'loop through until we find the one that's passed into this function
For ItemCtr = 1 To iTotalItems
CurItem = oRoot.Item(ItemCtr).Name
If UCase(CurItem) = UCase(ResName) Then
Set oSub = oRoot.Item(ItemCtr)
End If
Next
Set oRoot = Nothing
Set oTDC = Nothing
If Not oSub is nothing Then
oSub.filename = "TestData.xls"
oSub.ResourceType = "Data table"
oSub.post
oSub.UploadResource "c:\", True
End If
End Function
Sub ExportDT (DirectoryPath)
Dim arrDate, varDate, arrTime, varTime
arrDate = Split(Date,"/")
For each element in arrDate
varDate = varDate & element
Next
arrTime = Split(time,":")
For each element in arrTime
varTime = varTime & element
Next
DataTable.Export DirectoryPath & Environment.value("TestName") & "_" & varDate & "_" & varTime & ".xls"
End Sub
Window("Microsoft Internet Explorer").Maximize
You can also use the Browser FullScreen method:' Make browser fullscreen
Browser("Browser").FullScreen
The FullScreen method displays the browser in full-screen mode. This method is applicable when running a test using Internet Explorer only. It is not supported when using Netscape.
Set x = Browser("Welcome: Edgewords Training").Object.Document.all.tags("FONT")
msgbox x.length
For each obj in x
myVal = obj.getattribute("color")
If myVal = "#ff0000" Then
msgbox "found red"
msgbox obj.getattribute("innerText")
End If
Next
Window("Microsoft Internet Explorer").Click 35,5
'Starting a web browser:
'Set the variable to "NS" for Netscape or "IE" for Internet Explorer.
Browser1 = "IE"
StartURL = "www.yahoo.com"
IF Browser1 = "IE" THEN
set IE = CreateObject("InternetExplorer.Application")
IE.Visible = true
IE.Navigate StartURL
END IF
IF Browser1 = "NS" THEN
SystemUtil.Run "netscp6.exe", StartURL,"C:\Program Files\Netscape\Netscape 6\", ""
END IF
'Kill Browser Process
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where Name='iexplore.exe'")
For Each objProcess in colProcess
objProcess.Terminate()
Next
On Error Goto 0
if Window("Flight Reservation").Exist(60) then
reporter.ReportEvent micPass, "Login", "Flight Window Displayed Successfully"
else
reporter.ReportEvent micFail, "Login", "Flight Window Failed to Display"
ExitGlobalIteration
end if
Dim qtApp
Set qtApp = CreateObject("QuickTest.Application")
qtApp.WindowState = "Minimized" ' Minimize QTP
wait 2
qtApp.WindowState = "Normal" ' Restore QTP
wait 2
qtApp.WindowState = "Maximized" ' Maximize QTP
Set qtApp = Nothing
' This code executes the CTRL+F key combination (search) on a browser.
' Activate browser window
Set WshShell = CreateObject("WScript.Shell") WshShell.AppActivate "Put the label of the browser"
wait(3)
WshShell.SendKeys "^f" ' The caret (^) represents the CTRL key.
wait(2)
object.SendKeys(string)
The SendKeys method will send keystroke(s) to the active window. To send a single character (for example, x), use "x" as the string argument. To send multiple characters (for example, abc), use "abc" as the string argument. You can also send special characters such as SHIFT, CTRL, and ALT, which are represented by the plus sign (+), the caret (^), and the percent sign (%), respectively.
For more information on the SendKeys method and other special keys, such as the backspace or a function key, please refer to the MSDN SendKeys Method page.
on error resume next
val=DataTable("ParamName",dtGlobalSheet)
if err.number<> 0 then
'Parameter does not exist
else
'Parameter exists
end if
On error Goto 0
Call KillProcess ("'Excel.exe'")
Public Sub KillProcess (strProcess)
strComputer = "."
Set objWMIService=GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcess=objWMIService.ExecQuery ("Select * from Win32_Process Where Name=" & strProcess)
For Each objProcess in colProcess
objProcess.Terminate()
Next
End Sub
' If you're in QTP and looking for Windows or anything at the top level of your machine.
' First create a description object for the window or object you are looking for:
Dim oDesc, oColl
Set oDesc = Description.Create()
oDesc("<property>").Value = "<value>"
' Get collection of all childObjects that match desciption
Set oColl = Desktop.ChildObjects(oDesc)
' Now you can access the object and use your standard QTP methods etc.
oColl(0).Activate
Sub SendMailOutlook(aTo, Subject, TextBody, aFrom)
'Create an Outlook object
Dim Outlook 'As New Outlook.Application
Set Outlook = CreateObject("Outlook.Application")
'Create a new message
Dim Message 'As Outlook.MailItem
Set Message = Outlook.CreateItem(olMailItem)
With Message
'You can display the message To debug And see state
'.Display
.Subject = Subject
.Body = TextBody
'Set destination email address
.Recipients.Add (aTo)
'Set sender address If specified.
Const olOriginator = 0
If Len(aFrom) > 0 Then .Recipients.Add(aFrom).Type = olOriginator
'Send the message
.Send
End With
End Sub
CompareFiles (FilePath1, FilePath2)
FilePath1 The path to the first file to compare
FilePath2 The path to the second file to compare
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(1000)
Str2 = File2.Read(1000)
CompareFiles = StrComp(Str1, Str2, 0)
If CompareFiles <> 0 Then
CompareFiles = True
Exit Do
End If
Loop
File1.Close()
File2.Close()
End Function
Return value:
' The function returns 0 or False if the two files are identical, otherwise True.
Example:
File1 = "C:\countries\apple1.jpg"
File2 = "C:\countries\apple3.jpg"
If CompareFiles(File1, File2) = False Then
MsgBox "Files are identical."
Else
MsgBox "Files are different."
End If
' Instead of using Services.StartTransaction and Services.EndTransaction...
' You can capture timings like this:
StartTime = Timer
perform actions to be timed here...
EndTime = Timer
Reporter.ReportEvent micDone, "Time", EndTime-StartTime
' Round <myValue> to <decimialPlaces>
' QTP round() function rounds down if previous digit is even and up if it's odd:
' Round(2.15) and Round(2.25) both return 2.2
Function trueRound(byval myValue, byval decimalPlaces)
Dim oMath, oMode
set oMath = DotNetFactory.CreateInstance("System.Math", "System")
set oMode = DotNetFactory.CreateInstance("System.MidpointRounding", "System")
trueRound=oMath.Round(myValue, decimalPlaces, oMode.AwayFromZero)
set oMath = nothing
set oMode = nothing
End Function
' This example connects to the demo flight app Access Database that comes with QTP.
' The ODBC DSN entry is already set-up when the flight app is installed
' Connect to the Flight32 database
Set dbexample = CreateObject("ADODB.Connection")
dbexample.Open("DSN=Flight32")
' Perform a querySet
recordset = dbexample.Execute("SELECT * from Orders")
' Get the values from the Customer_Name column
while (NOT recordset.EOF)
MsgBox recordset.Fields("Customer_Name")
' Move to the next value in the record set
recordset.MoveNext
wend
' Close the database connection.
dbexample.Close
Set dbexample = Nothing
' Changing format to U.S. and adding 10 days:
' Add 10 days
mydat = DateAdd ("d", 10, Date())
' Split the date on the slash
myarr = split (mydat,"/")
' re-arrange into MM/DD/YY US format
mydat = myarr(1) & "/" & myarr(0) & "/" & right(myarr(2), 2)
msgbox mydat
' This function reads a Windows list object, then returns an array of the items in the list
Public Function createListArray(ByRef oList)
Dim listArr(), i, itemCount
createListArray = micFail
itemCount = oList.GetItemsCount
ReDim listArr(itemCount-1)
For i=0 To UBound(listArr)
listArr(i)=oList.GetItem(i)
Next
createListArray = listArr
End Function
' Just enter this code snippet at the start of your script:
Set qtApp = CreateObject("QuickTest.Application")
qtApp.WindowState = "Maximized"
Set qtApp = Nothing
Set objBug = QCUtil.QCConnection.BugFactory.AddItem(Null)
objBug.Summary = "404 on View Balance"
objBug.Status = "New"
objBug.Priority = "3-High"
objBug.Field("BG_SEVERITY") = "3-High"
objBug.DetectedBy = "admin"
objBug.Field("BG_DETECTION_DATE") = Date
objBug.Field("BG_DESCRIPTION") = "Got a 404 not found when viewing balance"
objBug.Post
' Pass in the number of minutes to be added e.g. MsgBox TimeAdd (20)
Function TimeAdd (mins)
Dim varMyTime
varMyTime = TimeValue (DateAdd ("n", mins, Now()))
TimeAdd = Left (varMyTime, 5)
End Function
Function Close_All_Browsers ()
Dim obj, TotalBrowsers, CreationTime, BrowserName, i
Set obj = Description.Create()
obj("micclass").value = "Browser"
TotalBrowsers = Desktop.ChildObjects(obj).count
CreationTime = "0"
For i = 1 to TotalBrowsers
BrowserName = Browser("CreationTime:=" & CreationTime).GetROProperty("name")
If Instr (1,BrowserName,"Quality Center",1) > 0 Then
CreationTime=CreationTime+1
else
Browser("CreationTime:=" & CreationTime).Close
End If
wait 1
Next
wait 3
End Function
strText = "Edgewords"
varTextVal = Asc (strText)
if varTextVal >= 65 AND varTextVal <= 90 Then
msgbox "The first character is uppercase"
elseIf varTextVal >= 97 And varTextVal <= 122 Then
msgbox "The first character is lowercase"
else
msgbox "The first character is non alphabetical"
end if
Public Function SelfClosingMsgbox (title, content)
Dim WSObj,myPopup
Set WSObj = CreateObject("WScript.Shell")
myPopup = WSobj.popup(content, 3, title, 0) 'note that the '3' here determines length of time in seconds
Set WSObj = Nothing
Set myPopup = Nothing
End Function
'You can use the 'Print' statement in QTP to output information to
'QTPs Print Log at Run-Time
'This may be more useful than using the 'MsgBox' function as it does not
'stop the test run and the log is still displayed after playback
'Example:
For i = 1 to 5
Print i * 2
Next
' Capture the source code:
SourceCode = Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").Object.documentElement.outerHtml
' You can then use the File System Object to write the captured HTML to a local file:
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oTextFile = oFSO.CreateTextFile("C:\SourceCode.html", True, -1)
oTextFile.Write(SourceCode)
Set oFSO = nothing
Set oTextFile = nothing
numberOfFlights = Window("Flight Reservation").Dialog("Flights Table").WinList("From").GetItemsCount
myRandomNumber = RandomNumber(0, numberOfFlights - 1)
reporter.ReportEvent micDone, "Select Flight", "Random Number Selected is " & cStr(myRandomNumber)
Window("Flight Reservation").Dialog("Flights Table").WinList("From").Select myRandomNumber
' If you are using the Global Worksheet as below, remember to set the Data Table iterations
' to run one iteration only in the Test Settings
datatable.ImportSheet "c:\FlightData.xls", "Sheet1", "Global"
varRows = datatable.GetRowCount
For i = 1 to varRows
DataTable.SetCurrentRow i
Window("Flight Reservation").Activate
Window("Flight Reservation").WinButton("New Order").Click
Window("Flight Reservation").ActiveX("Date of flight").Type "121212"
Window("Flight Reservation").WinComboBox("Fly From:").Select DataTable.Value ("flyfrom", dtGlobalSheet)
Window("Flight Reservation").WinComboBox("Fly To:").Select DataTable.Value ("flyto", dtGlobalSheet)
Window("Flight Reservation").WinButton("FLIGHT").Click
Window("Flight Reservation").Dialog("Flights Table").WinButton("OK").Click
Window("Flight Reservation").WinEdit("Name:").Set DataTable.Value ("firstname", dtGlobalSheet)
Window("Flight Reservation").WinRadioButton("Business").Set
Window("Flight Reservation").WinEdit("Tickets:").Set "2"
Window("Flight Reservation").WinButton("Insert Order").Click
Window("Flight Reservation").ActiveX("Threed Panel Control").WaitProperty "text", "Insert Done...", 10000
Next