You are on page 1of 167

How to call Class inside 1 more Class and use it in Automation script

Class 1

On Error Resume Next


ExecuteFile "C:\Arun\testing.class"
if Err.Number <> 0 then
Reporter.ReportEvent micFail,"AccountAllocation.class", Err.Description
end if
Err.Clear

Class Main

private objTesting

private sub Class_Initialize()


objTesting=null
End Sub

public function getTestingReference


Set objTesting = New Testing
set getTestingReference= objTesting
end function

'Set objTesting = New Testing

'Call objTesting.add1

End Class

Class 2
Class Testing

Private a

Private Sub Class_Initialize()


a=null
end Sub

Public function Add1()


msgbox "inside"
End function

End Class
Script

'On Error Resume Next


ExecuteFile "C:\Arun\main.class"
if Err.Number <> 0 then
Reporter.ReportEvent micFail,"AccountAllocation.class", Err.Description
end if
Err.Clear

'private objTesting

' set getTestingReference = objTesting

Set objMain = New Main

'Call objTesting.add1
Set objTesting=objMain.getTestingReference

objTesting.add1
Posted by Arun Justin Kulandairaj at 1:53 PM 1 comments

Problems with QTP


Problems with QTP

1)
QTP has some issues in identifying object in Descriptive programming..

mainly for "Class Name" we should use micclass


like wise some more properties are available

2)

While debugging QTP scripts from QC, some time QTP will get hangged.., it is a
known issue and even mercury knows about it.
it happends even in 9.1 also

3)Check points...
Checkpoints are hidden inside OR file and we dont have option of exporting /
importing from 1 place to other.. if we change approach it will land in problem

4)
Problem in identifying objects in case of very think client. some time identifying
objects will be problem .. specialy for list objects..in Java env

5)
QTP doesn't support drag and drop objects on web

6)

QTP doen't record any objects from pdf file

7)

QTP result generation is not user friendly


Posted by Arun Justin Kulandairaj at 1:51 PM 0 comments

spell check
Function CheckSpellErrors(Var)
Set obj = CreateObject("Word.Application")
obj.WordBasic.FileNew
obj.WordBasic.Insert Var
Set SpellErrCollection = obj.ActiveDocument.SpellingErrors
For each element in SpellErrCollection
CreateObject("wscript.shell").popup element,1,"Spell Error"
Next
NoofErrors = obj.ActiveDocument.SpellingErrors.Count
obj.Documents.Close (False)
obj.Quit
Set SpellErrCollection = Nothing
Set obj = Nothing
CheckSpellErrors = NoofErrors
End Function

Msgbox "Spell Error Count = "&CheckSpellErrors("Checki spelling Usingg


Automated Testingz")
Posted by Arun Justin Kulandairaj at 1:51 PM 1 comments

Friday, July 6, 2007

User defined Result file


'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
' About : Delcaration of Constans and Variables
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
Public g_sFileName 'Report Log File Name.
Public g_iCapture_Count 'Number of Images captured
Public g_iImage_Capture 'Flag for Image Capture in Result File
Public g_iPass_Count 'Pass Count
Public g_iFail_Count 'Fail Count
Public g_tStart_Time 'Start Time
Public g_tEnd_Time 'End Time

'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
' About : Procedure to Open a HTML File for Report Log
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~

Public Sub rep_Open_File(sFileName, iImageCapture)


Dim g_objReport 'File Object
Dim g_objFS 'File System Object

g_iPass_Count = 0
g_iFail_Count = 0
g_sFileName = sFileName
g_iImage_Capture = iImageCapture
Set g_objFS = CreateObject("Scripting.FileSystemObject")
Set g_objReport = g_objFS.OpenTextFile(g_sFileName, 2, True)
g_objReport.Write "<$$HTML><$$BODY><$$TABLE BORDER=0
CELLPADDING=3 CELLSPACING=1 WIDTH=100%>"
g_objReport.Write "<$$TR COLS=2><$$TD BGCOLOR=WHITE WIDTH=6%><$
$IMG
SRC='https://webaccess.kdc.capitalone.com/GetAccess/images/logo_sso.gif'><$
/$TD><$$TD WIDTH=94% BGCOLOR=WHITE><$FONT FACE=VERDANA
COLOR=NAVY SIZE=2><$$B> Helix ProphIT Automation - " & Date & " - " &
Time & " on Machine " & Environment.Value("LocalHostName") &
"<$$/B><$$/FONT><$$/TD><$$/TR><$$/TABLE>"
g_objReport.Write "<$$TABLE BORDER=0 BGCOLOR=BLACK
CELLPADDING=3 CELLSPACING=1 WIDTH=100%>"
g_objReport.Close
Set g_objFS = Nothing
Set g_objReport = Nothing
g_tStart_Time = Now()
End Sub

'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
' About : Procedure to Insert a Section to Report Log
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~

Public Sub rep_Insert_Section(sSection)


Dim g_objReport 'File Object
Dim g_objFS 'File System Object
Set g_objFS = CreateObject("Scripting.FileSystemObject")
Set g_objReport = g_objFS.OpenTextFile(g_sFileName, 8, True)
g_objReport.Write "<$$TR><$$TD COLSPAN=6 BGCOLOR=#66699><$$FONT
FACE=VERDANA COLOR=WHITE SIZE=2><$$B>" & sSection &
"<$$/B><$$/FONT><$$/TD><$$/TR>"
g_objReport.Write "<$$TR COLS=6><$$TD BGCOLOR=#FFCC99
WIDTH=25%><$$FONT FACE=VERDANA COLOR=BLACK SIZE=2><$
$B>Description<$$/B><$$/FONT><$$/TD><$$TD BGCOLOR=#FFCC99
WIDTH=25%><$$FONT FACE=VERDANA COLOR=BLACK SIZE=2><$
$B>Expected Result<$$/B><$$/FONT><$$/TD><$$TD BGCOLOR=#FFCC99
WIDTH=25%><$$FONT FACE=VERDANA COLOR=BLACK SIZE=2><$
$B>Actual Result<$$/B><$$/FONT><$$/TD><$$TD BGCOLOR=#FFCC99
WIDTH=25%><$$FONT FACE=VERDANA COLOR=BLACK SIZE=2><$
$B>Result<$$/B><$$/FONT><$$/TD><$$TD BGCOLOR=#FFCC99
WIDTH=7%><$$FONT FACE=VERDANA COLOR=BLACK SIZE=2><$$B>Test
Type<$$/B><$$/FONT><$$/TD><$$/TR>"
g_objReport.Close
Set g_objFS = Nothing
Set g_objReport = Nothing
End Sub

'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
' About : Procedure to Insert a Step to Report Log
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~

Public Sub rep_Insert_Step(sDesc)


Dim g_objReport 'File Object
Dim g_objFS 'File System Object
Set g_objFS = CreateObject("Scripting.FileSystemObject")
Set g_objReport = g_objFS.OpenTextFile(g_sFileName, 8, True)
g_objReport.Write "<$$TR><$$TD BGCOLOR=#EEEEEE COLSPAN=5><$
$FONT FACE=VERDANA SIZE=2><$$B>" & sDesc &
"<$$/B><$$/FONT><$$/TD><$$/TR>"
g_objReport.Close
Set g_objFS = Nothing
Set g_objReport = Nothing
End Sub

'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
' About : Procedure to Insert a Result to Report Log
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~

Public Sub rep_Insert_Result(sDesc, sExpected, sActual, sResult, sTestType)


Dim g_objReport 'File Object
Dim g_objFS 'File System Object
Dim l_sFile 'Bitmap File Name

Set g_objFS = CreateObject("Scripting.FileSystemObject")


Set g_objReport = g_objFS.OpenTextFile(g_sFileName, 8, True)

If sResult="PASS" Then
g_iPass_Count = g_iPass_Count + 1
If g_iImage_Capture=2 Then
l_sFile = Environment("ResultDir") & "\Screen" & g_iCapture_Count & ".png"
Desktop.CaptureBitmap l_sFile
g_iCapture_Count = g_iCapture_Count + 1
g_objReport.Write "<$$TR COLS=5><$TD BGCOLOR=#EEEEEE
WIDTH=25%><$$FONT FACE=VERDANA SIZE=2>" & sDesc & "<$$/FONT><$
$/TD><$$TD BGCOLOR=#EEEEEE WIDTH=25%><$$FONT FACE=VERDANA
SIZE=2>" & sExpected & "<$$/FONT><$$/TD><$$TD BGCOLOR=#EEEEEE
WIDTH=25%><$FONT FACE=WINGDINGS SIZE=4>2<$/FONT><$FONT
FACE=VERDANA SIZE=2><$A HREF='" & l_sFile & "'>" & sActual &
"<$/A><$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=7%><$FONT
FACE='WINGDINGS 2' SIZE=5 COLOR=GREEN>P<$/FONT><$FONT
FACE=VERDANA SIZE=2 COLOR=GREEN><$B>" & sResult &
"<$/B><$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=18%><$FONT
FACE=VERDANA SIZE=2>" & sTestType & "<$/FONT><$/TD><$/TR>"
Reporter.ReportEvent micPass,sDesc,sActual
Else
g_objReport.Write "<$TR COLS=5><$TD BGCOLOR=#EEEEEE
WIDTH=25%><$FONT FACE=VERDANA SIZE=2>" & sDesc &
"<$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=25%><$FONT
FACE=VERDANA SIZE=2>" & sExpected & "<$/FONT><$/TD><$TD
BGCOLOR=#EEEEEE WIDTH=25%><$FONT FACE=VERDANA SIZE=2>" &
sActual & "<$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=7%><$FONT
FACE='WINGDINGS 2' SIZE=5 COLOR=GREEN>P<$/FONT><$FONT
FACE=VERDANA SIZE=2 COLOR=GREEN><$B>" & sResult &
"<$/B><$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=18%><$FONT
FACE=VERDANA SIZE=2>" & sTestType & "<$/FONT><$/TD><$/TR>"
Reporter.ReportEvent micPass,sDesc,sActual
End If
ElseIf sResult="FAIL" Then
g_iFail_Count = g_iFail_Count + 1
If g_iImage_Capture=1 Or g_iImage_Capture=2 Then
l_sFile = Environment("ResultDir") & "\Screen" & g_iCapture_Count & ".png"
Desktop.CaptureBitmap l_sFile
g_iCapture_Count = g_iCapture_Count + 1
g_objReport.Write "<$TR COLS=5><$TD BGCOLOR=#EEEEEE
WIDTH=25%><$FONT FACE=VERDANA SIZE=2>" & sDesc &
"<$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=25%><$FONT
FACE=VERDANA SIZE=2>" & sExpected & "<$/FONT><$/TD><$TD
BGCOLOR=#EEEEEE WIDTH=25%><$FONT FACE=WINGDINGS
SIZE=4>2<$/FONT><$FONT FACE=VERDANA SIZE=2><$A HREF='" & l_sFile
& "'>" & sActual & "<$/A><$/FONT><$/TD><$TD BGCOLOR=#EEEEEE
WIDTH=7%><$FONT FACE='WINGDINGS 2' SIZE=5
COLOR=RED>O<$/FONT><$FONT FACE=VERDANA SIZE=2
COLOR=RED><$B>" & sResult & "<$/B><$/FONT><$/TD><$TD
BGCOLOR=#EEEEEE WIDTH=18%><$FONT FACE=VERDANA SIZE=2>" &
sTestType & "<$/FONT><$/TD><$/TR>"
Reporter.ReportEvent micFail,sDesc,sActual
Else
g_objReport.Write "<$TR COLS=5><$TD BGCOLOR=#EEEEEE
WIDTH=25%><$FONT FACE=VERDANA SIZE=2>" & sDesc &
"<$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=25%><$FONT
FACE=VERDANA SIZE=2>" & sExpected & "<$/FONT><$/TD><$TD
BGCOLOR=#EEEEEE WIDTH=25%><$FONT FACE=VERDANA SIZE=2>" &
sActual & "<$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=7%><$FONT
FACE='WINGDINGS 2' SIZE=5 COLOR=RED>O<$/FONT><$FONT
FACE=VERDANA SIZE=2 COLOR=RED><$B>" & sResult &
"<$/B><$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=18%><$FONT
FACE=VERDANA SIZE=2>" & sTestType & "<$/FONT><$/TD><$/TR>"
Reporter.ReportEvent micFail,sDesc,sActual
End If
Else
g_objReport.Write "<$TR COLS=5><$TD BGCOLOR=#EEEEEE
WIDTH=25%><$FONT FACE=VERDANA SIZE=2>" & sDesc &
"<$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=25%><$FONT
FACE=VERDANA SIZE=2>" & sExpected & "<$/FONT><$/TD><$TD
BGCOLOR=#EEEEEE WIDTH=25%><$FONT FACE=VERDANA SIZE=2>" &
sActual & "<$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=7%><$FONT
FACE='WINGDINGS 2' SIZE=5 COLOR=RED>O<$/FONT><$FONT
FACE=VERDANA SIZE=2 COLOR=BLACK><$B>" & sResult &
"<$/B><$/FONT><$/TD><$TD BGCOLOR=#EEEEEE WIDTH=18%><$FONT
FACE=VERDANA SIZE=2>" & sTestType & "<$/FONT><$/TD><$/TR>"
Reporter.ReportEvent micGeneral,sDesc,sActual
End If

g_objReport.Close
Set g_objFS = Nothing
Set g_objReport = Nothing
End Sub

'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
' About : Procedure to Close Report Log
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~

Public Sub rep_Close


Dim g_objReport 'File Object
Dim g_objFS 'File System Object
Set g_objFS = CreateObject("Scripting.FileSystemObject")
Set g_objReport = g_objFS.OpenTextFile(g_sFileName, 8, True)
g_tEnd_Time = Now()
g_objReport.Write "<$TR COLS=5><$TD BGCOLOR=BLACK
WIDTH=25%><$FONT FACE=VERDANA COLOR=WHITE SIZE=2><$B>Pass
Count : " & g_iPass_Count & "<$/B><$/FONT><$/TD><$TD BGCOLOR=BLACK
WIDTH=25%><$FONT FACE=VERDANA COLOR=WHITE SIZE=2><$B>Fail
Count : " & g_iFail_Count & "<$/B><$/FONT><$/TD><$TD BGCOLOR=BLACK
WIDTH=25%><$FONT FACE=VERDANA COLOR=WHITE SIZE=2><$B>Time
Taken : " & DateDiff("n",g_tStart_Time,g_tEnd_Time) & "
Minutes<$/B><$/FONT><$/TD><$TD BGCOLOR=BLACK WIDTH=7%><$FONT
FACE=VERDANA COLOR=WHITE SIZE=2><$B><$/B><$/FONT><$/TD><$TD
BGCOLOR=BLACK WIDTH=18%><$FONT FACE=VERDANA COLOR=WHITE
SIZE=2><$B><$/B><$/FONT><$/TD><$/TR>"
g_objReport.Write "<$/TABLE><$/BODY><$/HTML>"
g_objReport.Close
Set g_objFS = Nothing
Set g_objReport = Nothing
End Sub

'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
' About : Procedure to Show Report Log in Browser Window
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~

Public Sub rep_Show_Result


rep_Close
Set objIE = CreateObject("InternetExplorer.Application") ' Creating a new object
for IE
objIE.Visible = True 'Setting the visible property to true
'msgbox g_sFileName & "#Summary"
objIE.Navigate g_sFileName & "#Summary"
End Sub
Posted by Arun Justin Kulandairaj at 3:35 PM 0 comments

Synchronise Objects function


//Synchronise Objects function - another

Public Function
fnSynchroniseObjects(objPage,objObjectToSynchronise,intWaitValue)

Dim blnResult

blnWaitProprtyValue=CBool(blnWaitProprtyValue)
intWaitValue=(Int(intWaitValue)*1000)
objPage.Sync

objObjectToSynchronise.WaitProperty "visible", True , intWaitValue

objObjectToSynchronise.WaitProperty "attribute/readyState", "complete",


intWaitValue

End Function
Posted by Arun Justin Kulandairaj at 3:20 PM 0 comments

verify the Heading text in a Frame


'' Name : fnVerifyHeadingText(objFrame, strHeading)
'' Description: This function is used to verify the Heading text in a Frame
'' Arguments :
'' objFrame: Frame object in which the heading is present
'' strHeading: Heading String
'' Return: True/False
'' Pre-Condition:The frame containing the heading should be displayed
'' Post-condition:
''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Public Function fnVerifyHeadingText(objFrame, strHeading)

Dim objDescWebElem, objWEHeading

fnVerifyHeadingText = True
'''''''''' Creating a web element object for Heading'''''''''''''
Set objDescWebElem = Description.Create()
objDescWebElem("micclass").Value = "WebElement"
objDescWebElem("innertext").Value = Trim(strHeading)
objDescWebElem("outertext").Value = Trim(strHeading)
objDescWebElem("html tag").Value="SPAN"

''''''''''Verify Heading''''''''''''''''''''''''''''''''
If objFrame.Exist(4) Then
Set objWEHeading = objFrame.ChildObjects(objDescWebElem)
If (objWEHeading.Count <= 0) Then
fnVerifyHeadingText = False
End If
Else
fnVerifyHeadingText = False
End If

End Function
Posted by Arun Justin Kulandairaj at 3:20 PM 0 comments
Older Posts

Descriptive Programming
Introduction to Descriptive Programming.
How to write Descriptive Programming?
When and Where to use Descriptive programming?
Some points to note with Descriptive Programming.

Introduction to Descriptive Programming:


Descriptive programming is used when we want to perform an operation on an
object that is not present in the object repository. There can be various valid
reason to do so. We will discuss them later in this article.

How to write Descriptive Programming?

There are two ways in which descriptive programming can be used


1. By giving the description in form of the string arguments.
2. By creating properties collection object for the description.

1. By giving the description in form of the string arguments.

This is a more commonly used method for Descriptive Programming.


You can describe an object directly in a statement by specifying
property:=value pairs describing the object instead of specifying an object’s
name. The general syntax is:

TestObject("PropertyName1:=PropertyValue1", "..." ,
"PropertyNameX:=PropertyValueX")

TestObject—the test object class could be WebEdit, WebRadioGroup etc….

PropertyName:=PropertyValue—the test object property and its value. Each


property:=value pair should be separated by commas and quotation
marks. Note that you can enter a variable name as the property value if you
want to find an object based on property values you retrieve during a run
session.

Consider the HTML Code given below:

<--!input type="”textbox”" name="”txt_Name”"-->


<--!input type="”radio”" name="”txt_Name”"-->

Now to refer to the textbox the statement would be as given below

Browser(“Browser”).Page(“Page”).WebEdit(“Name:=txt_Name”,”html
tag:=INPUT”).set “Test”

And to refer to the radio button the statement would be as given below

Browser(“Browser”).Page(“Page”).WebRadioGroup(“Name:=txt_Name”,”html
tag:=INPUT”).set “Test”

If we refer to them as a web element then we will have to distinguish between


the 2 using the index property

Browser(“Browser”).Page(“Page”).WebElement(“Name:=txt_Name”,”html
tag:=INPUT”,”Index:=0”).set “Test” ‘ Refers to the textbox
Browser(“Browser”).Page(“Page”).WebElement(“Name:=txt_Name”,”html
tag:=INPUT”,”Index:=1”).set “Test” ‘ Refers to the radio button

To determine which property and value pairs to use, you can use the Object
Spy:
1. Go to Tools -> Object Spy.
2. Select the "Test Object Properties" radio button.
3. Spy on the desired object.
4. In the Properties list, find and write down the properties and values that can
be used to identify the object.

2. By creating properties collection object for the description.

Properties collection also does the same thing as string arguments. The only
difference is that it "collects" all the properties of a particular object in an
instance of that object. Now that object can be referenced easily by using the
instance, instead of writing "string arguments" again and again. It is my
observation that people find "string arguments" [1] method much easier and
intuitive to work with.

To use this method you need first to create an empty description


Dim obj_Desc ‘Not necessary to declare
Set obj_Desc = Description.Create

Now we have a blank description in “obj_Desc”. Each description has 3


properties “Name”, “Value” and “Regular Expression”.

obj_Desc(“html tag”).value= “INPUT”

When you use a property name for the first time the property is added to the
collection and when you use it again the property is modified. By default each
property that is defined is a regular expression. Suppose if we have the
following description

obj_Desc(“html tag”).value= “INPUT”


obj_Desc(“name”).value= “txt.*”

This would mean an object with html tag as INPUT and name starting with txt.
Now actually that “.*” was considered as regular expression. So, if you want
the property “name” not to be recognized as a regular expression then you
need to set the “regularexpression” property as FALSE

obj_Desc(“html tag”).value= “INPUT”


obj_Desc(“name”).value= “txt.*”
obj_Desc(“name”).regularexpression= “txt.*”

This is how we create a description. Now below is the way we can use it

Browser(“Browser”).Page(“Page”).WebEdit(obj_Desc).set “Test”
When we say .WebEdit(obj_Desc) we define one more property for our
description that was not earlier defined that is it’s a text box (because QTPs
WebEdit boxes map to text boxes in a web page).

If we know that we have more than 1 element with same description on the
page then we must define “index” property for the that description

Consider the HTML code given below

<--!input type="”textbox”" name="”txt_Name”"-->


<--!input type="”textbox”" name="”txt_Name”"-->

Now the html code has two objects with same description. So distinguish
between these 2 objects we will use the “index” property. Here is the
description for both the object

For 1st textbox:


obj_Desc(“html tag”).value= “INPUT”
obj_Desc(“name”).value= “txt_Name”
obj_Desc(“index”).value= “0”

For 2nd textbox:


obj_Desc(“html tag”).value= “INPUT”
obj_Desc(“name”).value= “txt_Name”
obj_Desc(“index”).value= “1”

Consider the HTML Code given below:

<--!input type="”textbox”" name="”txt_Name”"-->


<--!input type="”radio”" name="”txt_Name”"-->

We can use the same description for both the objects and still distinguish
between both of them
obj_Desc(“html tag”).value= “INPUT”
obj_Desc(“name”).value= “txt_Name”

When I want to refer to the textbox then I will use the inside a WebEdit object
and to refer to the radio button I will use the description object with the
WebRadioGroup object.

Browser(“Browser”).Page(“Page”).WebEdit(obj_Desc).set “Test” ‘Refers to the


text box
Browser(“Browser”).Page(“Page”).WebRadioGroup(obj_Desc).set “Test”
‘Refers to the radio button
But if we use WebElement object for the description then we must define the
“index” property because for a webelement the current description would
return two objects.

Getting Child Object:

We can use description object to get all the objects on the page that matches
that specific description. Suppose we have to check all the checkboxes present
on a web page. So we will first create an object description for a checkboxe
and then get all the checkboxes from the page

Dim obj_ChkDesc

Set obj_ChkDesc=Description.Create
obj_ChkDesc(“html tag”).value = “INPUT”
obj_ChkDesc(“type”).value = “checkbox”

Dim allCheckboxes, singleCheckBox

Set allCheckboxes =
Browse(“Browser”).Page(“Page”).ChildObjects(obj_ChkDesc)

For each singleCheckBox in allCheckboxes

singleCheckBox.Set “ON”

Next

The above code will check all the check boxes present on the page. To get all
the child objects we need to specify an object description.

If you wish to use string arguments [1], same thing can be accomplished by
simple scripting.

Code for that would be:

i=0

Do While Browse(“Browser”).Page(“Page”).WebCheckBox("html
tag:=INPUT",type:=checkbox, "index:="&i).Exist

Browse(“Browser”).Page(“Page”).WebCheckBox("html
tag:=INPUT",type:=checkbox, "index:="&i).Set "ON"

i=i+1
Loop

Possible Operation on Description Objects

Consider the below code for all the solutions


Dim obj_ChkDesc

Set obj_ChkDesc=Description.Create
obj_ChkDesc(“html tag”).value = “INPUT”
obj_ChkDesc(“type”).value = “checkbox”

Q: How to get the no. of description defined in a collection


A: obj_ChkDesc.Count ‘Will return 2 in our case

Q: How to remove a description from the collection


A: obj_ChkDesc.remove “html tag” ‘would delete the html tag property from
the collection

Q: How do I check if property exists or not in the collection?


A: The answer is that it’s not possible. Because whenever we try to access a
property which is not defined its automatically added to the collection. The
only way to determine is to check its value that is use a if statement “if
obj_ChkDesc(“html tag”).value = empty then”.

Q: How to browse through all the properties of a properties collection?


A: Two ways
1st:
For each desc in obj_ChkDesc
Name=desc.Name
Value=desc.Value
RE = desc.regularexpression
Next
2nd:
For i=0 to obj_ChkDesc.count - 1
Name= obj_ChkDesc(i).Name
Value= obj_ChkDesc(i).Value
RE = obj_ChkDesc(i).regularexpression
Next

Hierarchy of test description:

When using programmatic descriptions from a specific point within a test


object hierarchy, you must continue to use programmatic descriptions
from that point onward within the same statement. If you specify a test object
by its object repository name after other objects in the hierarchy have
been described using programmatic descriptions, QuickTest cannot identify the
object.

For example, you can use Browser(Desc1).Page(Desc1).Link(desc3), since it


uses programmatic descriptions throughout the entire test object hierarchy.
You can also use Browser("Index").Page(Desc1).Link(desc3), since it uses
programmatic descriptions from a certain point in the description (starting
from the Page object description).

However, you cannot use Browser(Desc1).Page(Desc1).Link("Example1"), since


it uses programmatic descriptions for the Browser and Page objects but
then attempts to use an object repository name for the Link test object
(QuickTest tries to locate the Link object based on its name, but cannot
locate it in the repository because the parent objects were specified using
programmatic descriptions).

When and Where to use Descriptive programming?

Below are some of the situations when Descriptive Programming can be


considered useful:

1. One place where DP can be of significant importance is when you are


creating functions in an external file. You can use these function in various
actions directly , eliminating the need of adding object(s) in object repository
for each action[If you are using per action object repository]

2. The objects in the application are dynamic in nature and need special
handling to identify the object. The best example would be of clicking a link
which changes according to the user of the application, Ex. “Logout <>”.

3. When object repository is getting huge due to the no. of objects being
added. If the size of Object repository increases too much then it decreases the
performance of QTP while recognizing a object. [For QTP8.2 and below
Mercury recommends that OR size should not be greater than 1.5MB]

4. When you don’t want to use object repository at all. Well the first question
would be why not Object repository? Consider the following scenario which
would help understand why not Object repository
Scenario 1: Suppose we have a web application that has not been developed
yet.Now QTP for recording the script and adding the objects to repository
needs the application to be up, that would mean waiting for the application to
be deployed before we can start of with making QTP scripts. But if we know
the descriptions of the objects that will be created then we can still start off
with the script writing for testing
Scenario 2: Suppose an application has 3 navigation buttons on each and every
page. Let the buttons be “Cancel”, “Back” and “Next”. Now recording action
on these buttons would add 3 objects per page in the repository. For a 10 page
flow this would mean 30 objects which could have been represented just by
using 3 objects. So instead of adding these 30 objects to the repository we can
just write 3 descriptions for the object and use it on any page.

5. Modification to a test case is needed but the Object repository for the same
is Read only or in shared mode i.e. changes may affect other scripts as well.

6. When you want to take action on similar type of object i.e. suppose we have
20 textboxes on the page and there names are in the form txt_1, txt_2, txt_3
and so on. Now adding all 20 the Object repository would not be a good
programming approach.
POSTED BY RAJ VELUR AT 4:13 AM 2 COMMENTS
LABELS: DESCRIPTIVE, PROGRAMMING

QTP & Reporter Objects


Reporter Object is used for sending information to the test results. With the
help of this object you can:

* >Report the status of test results (like pass, fail, warning)


* >Enable/Disable reporting of step(s) following the statement.
* >Retrieve the folder path in which the current test's results are stored.
* >Retrieve the run status at the current point of the run session.

There are some very important methods and properties associated with it.
ReporterEvent Method:

I think this is a very common method used with Reporter object. I am sure even
if you have worked on QTP for a relatively short period, you would have come
across this.

Its syntax:

Reporter.ReportEvent EventStatus, ReportStepName, Details

where EventStatus can be:

0 or micPass: If this step runs test passes which is shown in test report.

1 or micFail: If this step runs test fails which is shown in test report.

2 or micDone: Used to send message to the test report and does not affect
status of test.
3 or micWarning: Again, used to send warning message to the test report and
does not affect status of test.

and

ReportStepName is name of step

and

Details are the user defined details for the given step.

For Example:

Reporter.ReportEvent micPass, "Login Authorization", "The user-defined step


passed."

Filter property

There can be situations where we don't want the full status displayed on the
test report. This property can be used to selectively filter the status of your
tests.

Its syntax:

Reporter.Filter = NewMode

where NewMode can be:

0 or rfEnableAll: This is the default mode. All reported events are displayed in
the Test Results.

1 or rfEnableErrorsAndWarnings: Only those events with a warning or fail status


are displayed in the Test Results.

2 or rfEnableErrorsOnly: Only those events with a fail status are displayed in


the Test Results.

3 or rfDisableAll: All events in the Test Results are disabled.

ReportPath Property

This is used to get the path in which current test results are stored.

Its syntax:
Path_of_Results = Reporter.ReportPath

RunStatus Property

This is used to get the current status of the run session

Its syntax:

Reporter.RunStatus

For Example:

if Reporter.RunStatus = 0 then flag=1;


POSTED BY RAJ VELUR AT 4:07 AM 0 COMMENTS
LABELS: REPORTER OBJECTS

QTP & File Handling


When we need to interact with text files using QTP. Interaction can be(but not
limited to) in the form of reading input from a file, writing output to a file.
This post describe in detail "File handling using QTP".

We use FSO object to do this.

What is FSO?

FSO stands for File System Object. This is used to support text file creation and
manipulation through the TextStream object and is contained in the Scripting
type library (Scrrun.dll)

The FSO Object Model has a rich set of properties, methods and events to
process folders and files.

How to create a file?

We first create a FSO object using CreateObject and then create a text file
using CreateTextFile.

For Example: Suppose you want to create a file called "test.txt" located in C:

Dim fso, file, file_location

file_location = "C:\file_location"

Set fso = CreateObject(“Scripting.FileSystemObject”)


Set file = fso.CreateTextFile(file_location, True) // True--> file is to be
overwritten if it already exists else false

We would use the same example for the rest of this post.

How to open a file?

Set file= fso.OpenTextFile("C:\file_location", ForWriting, True)

//2nd argument can be ForReading, ForWriting, ForAppending

//3rd argument is "True" if new file has to be created if the specified file
doesn’t exist else false, blank signify false.

How to read content from a file?

Use ReadLine() method

For example:

Set file= fso.OpenTextFile("C:\file_location", ForReading, True) //2nd


argument should always be "ForReading" in order to read contents from a file

Do while file.AtEndofStream <> True

data = file.ReadLine()

msgbox data

Loop

How to write content to a file?

You can use Write() or WriteLine() Methods to write text into a file. The
difference between the Write() and WriteLine() Method is that the latter
automatically inserts a new line character while the former doesn’t insert a
new line character.

For example:

Set file= fso.OpenTextFile("C:\file_location", ForWriting, True) //2nd argument


should always be "ForWriting" in order to write contents to a file

file.Write("This is a place to get all your qtp")

file.Write("questions and answers solved.")


//Output will be:

This is a place to get all your qtp questions and answers solved.

while

file.WriteLine("This is a place to get all your qtp")

file.Write("questions and answers solved.")

//Output will be:

This is a place to get all your qtp

questions and answers solved.

How to delete content?

Use DeleteFile() method to delete a file from a particular location

Foe Example:

file_location = "C:\file_location"

Set fso = CreateObject(“Scripting.FileSystemObject”)

fso.DeleteFile(file_location)

qtp,textfile,read,write,delete
POSTED BY RAJ VELUR AT 4:04 AM 2 COMMENTS
LABELS: FILEHANDLING

QTP Tips
Does QuickTest Professional support Macintosh operating systems?
No, QTP will not run on this OS.

What to do if you are not able to run QTP from quality center?
This is for especially for new users with QTP.
Check that you have selected Allow other mercury products to run tests and
components from Tools--> Options--> Run Tab.

How to rename a checkpoint (QTP 9.0)?


Example:
Window("Notepad").WinEditor("Edit").Check CheckPoint("Edit")
In the above example, the user would like to change the name of the
CheckPoint object from "Edit" to something more meaningful.
Note:
This functionality is new to QuickTest Professional 9.0.This is not available for
QTP 8.2 and below.
1. Right-click on the Checkpoint step in the Keyword View or on the Checkpoint
object in Expert View.
2. Select "Checkpoint Properties" from the pop-up menu.
3. In the Name field, enter the new checkpoint name.
4. Click . The name of the checkpoint object will be updated within the script.
Example:
Window("Notepad").WinEditor("Edit").Check CheckPoint("NewCheckPointName")
Note:
You must use the QuickTest Professional user interface to change the name of
the checkpoint. If you manually change the name of the checkpoint in the
script, QuickTest Professional will generate an error during replay. The error
message will be similar to the following:
"The "" CheckPoint object was not found in the Object Repository. Check the
Object Repository to confirm that the object exists or to find the correct name
for the object."
The CheckPoint object is not a visible object within the object repository, so if
you manually modify the name, you may need to recreate the checkpoint to
resolve the error.

What are the files and subfolders of a QuickTest Professional test?


The files and folders hold binary and text data that are required for the test to
run successfully.
The following table provides a description, the type, and comments regarding
the files that make up a QuickTest Professional test.

File Name

Description

Type

Comments Regarding File

Test.tsp

Test settings

Binary

Do not edit
Default.xls

Data table parameters

Excel similar

Can be edited using Excel

Parameters.mtr

Parameterization information

Binary

Do not edit

Action

Action folder (See other table)

Default.cfg
Load test configuration file
Text
Do not edit

Default.prm
Load test configuration file
Text
Do not edit

Default.usp
Load test configuration file
Text
Do not edit

.usr
Load test configuration file
Text
Do not edit

Thick_usr.dat
Load test configuration file
Text
Do not edit
Thin_usr.dat
Load test configuration file
Text
Do not edit
Files within Action folder:

File Name

Description

Type

Comments Regarding File

Script.mts

Action script

Text

Edit text preceding the @@ sign only

Resource.mtr

Object Repository

Binary

Do not edit

Snapshots

Active screen files

Folder

Do not edit
There are few more files extensions like
.MTB Batch File
.LCK Locked

When to use a Recovery Scenario and when to us on error resume next?


Recovery scenarios are used when you cannot predict at what step the error
can occur or when you know that error won't occur in your QTP script but could
occur in the world outside QTP, again the example would be "out of paper", as
this error is caused by printer device driver. "On error resume next" should be
used when you know if an error is expected and dont want to raise it, you may
want to have different actions depending upon the error that occurred. Use
err.number & err.description to get more details about the error.

What is the difference between an Action and a function?


Action is a thing specific to QTP while functions are a generic thing which is a
feature of VB Scripting. Action can have a object repository associated with it
while a function can't. A function is just lines of code with some/none
parameters and a single return value while an action can have more than one
output parameters.

Where to use function or action?


Well answer depends on the scenario. If you want to use the OR feature then
you have to go for Action only. If the functionality is not about any automation
script i.e. a function like getting a string between to specific characters, now
this is something not specific to QTP and can be done on pure VB Script, so this
should be done in a function and not an action. Code specific to QTP can also
be put into an function using DP. Decision of using function/action depends on
what any one would be comfortable using in a given situation.

How to add a constant number in a datatable?


This is more to do with MS excel then QTP!! but useful to know because at
times it becomes frustrating to the novices.
Just append ' to the number
Ex: if you wish to enter 1234567 in datatable then write it as '1234567

How can i check if a parameter exists in DataTable or not?


The best way would be to use the below code:
on error resume next
val=DataTable("ParamName",dtGlobalSheet)
if err.number<> 0 then
'Parameter does not exist
else
'Parameter exists
end if

How can i check if a checkpoint passes or not?


chk_PassFail = Browser(...).Page(...).WebEdit(...).Check
(Checkpoint("Check1"))
if chk_PassFail then
MsgBox "Check Point passed"
else MsgBox "Check Point failed"
end if

Change the mode of the file Read only to Write


strApptEnterPath = "C:\Documents and settings\krao\Desktop\environment.xml"
Set objFile = oFSO.GetFile(strApptEnterPath)
If objFile.Attributes AND 1 Then
objFile.Attributes = objFile.Attributes - 1
End If

Uninstall a Software Using VBScript , QTP


This works for uninstalling most applications. In this example I will show how AutoCAD
2005 can be uninstalled using a VBScript. Open Regedit and look in
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\
Uninstall search for the application and find a the product code that is in GUID format
looking like this: {5783F2D7-0301-0409-0002-0060B0CE6BBA} It might be something
else for you.

The code below will uninstall AutoCAD 2005 as well as Express Tools. Copy the code
below into Notepad and give the file the extension vbs.

on error resume next

Set WshShell = CreateObject(”WScript.Shell”)

‘ Uninstall Express Tools

WshShell.Run “msiexec /x {5783F2D7-0311-0409-0000-0060B0CE6BBA} /q”,1,true

‘ Uninstall AutoCAD 2005

WshShell.Run “msiexec /x {5783F2D7-0301-0409-0002-0060B0CE6BBA} /q”,1,true

Changing System Date and time through QTP


newTime="03:40:00"
newDate=Date+1
Dim oShellSet
oShell=CreateObject("WScript.Shell")
oShell.run "cmd /k date" &CStr(" "&newDate)&"& exit"
oShell.run "cmd /k time" &CStr(" "&newTime)&"& exit"
set oShell=nothing
curDateTime=now
msgbox curDateTime

Start the Services through QTP


strComputer = "."
strService = " 'W32Time' "
Set objWMIService = GetObject("winmgmts:"& _
"{impersonationLevel=impersonate}!\\"& strComputer & "\root\
cimv2")Set colListOfServices =
objWMIService.ExecQuery("Select * from _ Win32_Service Where
Name ="& strService & " ")
For Each objService in colListOfServices
objService.StartService()
Next

Note : here strService is Services Name which you are going


to start. you get this name from control panel\
Administrative Tools\Services... and right click and select
properties on the Service , here you can find Service Name.

Stop the Services through QTP


strComputer = "."
strService = " 'W32Time' "
Set objWMIService = GetObject("winmgmts:"& _
"{impersonationLevel=impersonate}!\\"& strComputer & "\root\cimv2")Set
colListOfServices = objWMIService.ExecQuery("Select * from _ Win32_Service
Where Name ="& strService & " ")
For Each objService in colListOfServices
objService.StopService()
Next

Note : here strService is Services Name which you are going to start. you get this
name from control panel\Administrative Tools\Services... and right click and
select properties on the Service , here you can find Service Name.

Get the Results from Command prompt through QTP


Dim WshShell, oExecSet
WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("net time")
'We scan and display the command output flow
Do While oExec.StdOut.AtEndOfStream <> True
strCmdString= oExec.StdOut.ReadLine
Exit do
Loop
msgbox strCmdString

Fine Rename through QTP


dim spath,fso,f,sname
if count(wscript.arguments)<>0 then
spath=wscript.arguments(0)
set fso=createobject("scripting.filesystemobject")
'this is in the rightclick menu, so it can spare further
test for existence, otherwise, you should.
if fso.fileexists(spath) then
set f=fso.getfile(spath)
sname=f.name
f.name=sname & ".original"
set f=nothing
end if
set fso=nothing
end if

Kill the Process Through QTP


Killprocess = "Process name" per ex : calc.exe
Set ProcessList =
GetObject("winmgmts://.").InstancesOf("win32_process")
For Each Process In ProcessList
If Process.Name = KillProcess Then
Process.Terminate
End IfNext

Get the folders from "C" Drive


Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFldr = objFSO.GetFolder("C:\")
Set Fldrs = objFldr.SubFolders
For Each Fldr In Fldrs
WScript.Echo Fldr
Next
Changing the Data in Excel sheets from all cloumns and rows
Option Explicit
Rem We use "Option Explicit" to help us check for coding mistakes
Rem the Excel Application
Dim objExcel
Rem the path to the excel file
Dim excelPath
Rem how many worksheets are in the current excel file
Dim worksheetCount
Dim counter
Rem the worksheet we are currently getting data from
Dim currentWorkSheet
Rem the number of columns in the current worksheet that have data in them
Dim usedColumnsCount
Rem the number of rows in the current worksheet that have data in them
Dim usedRowsCount
Dim row
Dim column
Rem the topmost row in the current worksheet that has data in it
Dim top
Rem the leftmost row in the current worksheet that has data in it
Dim left
Dim Cells
Rem the current row and column of the current worksheet we are reading
Dim curCol
Dim curRow
Rem the value of the current row and column of the current worksheet we are
reading
Dim word
Rem find the value like "Testing\ATS" with in the Cell Data
Dim mypos
Rem split the Cell data
Dim myarray
Rem Find the Local Machine Name
Dim WshNetwork
Dim Computername
set WshNetwork= WScript.CreateObject("Wscript.Network")
Computername = WshNetwork.Computername
Rem where is the Excel file located?
excelPath = "C:\Documents and Settings\krao\Desktop\Inputs.xls"
'WScript.Echo "Reading Data from " & excelPath
Dim oFSO , objFile
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = oFSO.GetFile(excelPath)
' Checks for file attributes. This is a check for file being readonly. As the latests is
taken from VSTS it will be marked as readonly. This code will uncheck the
Readonly property
If objFile.Attributes AND 1 Then
objFile.Attributes = objFile.Attributes - 1
End If
Rem Create an invisible version of Excel
Set objExcel = CreateObject("Excel.Application")
Rem don't display any messages about documents needing to be converted
Rem from old Excel file formats
objExcel.DisplayAlerts = 0
Rem open the excel document
objExcel.Workbooks.open excelPath ', True , true
Rem How many worksheets are in this Excel documents
workSheetCount = objExcel.Worksheets.Count
'WScript.Echo "We have " & workSheetCount & " worksheets"
Rem Loop through each worksheet
For counter = 1 to workSheetCount
'WScript.Echo "Reading data from worksheet " & counter & vbCRLF
Set currentWorkSheet = objExcel.ActiveWorkbook.Worksheets(counter)
Rem how many columns are used in the current worksheet
usedColumnsCount = currentWorkSheet.UsedRange.Columns.Count
Rem how many rows are used in the current worksheet
usedRowsCount = currentWorkSheet.UsedRange.Rows.Count
Rem What is the topmost row in the spreadsheet that has data in it
top = currentWorksheet.UsedRange.Row
Rem What is the leftmost column in the spreadsheet that has data in it
left = currentWorksheet.UsedRange.Column
Set Cells = currentWorksheet.Cells
Rem Loop through each row in the worksheet
For row = 1 to (usedRowsCount-1)
Rem Loop through each column in the worksheet
For column = 0 to usedColumnsCount-1
Rem only look at rows that are in the "used" range
curRow = row+top
Rem only look at columns that are in the "used" range
curCol = column+left
Rem get the value/word that is in the cell
word = Cells(curRow,curCol).Value
Rem find the value like "Testing\ATS" with in the Cell Data
mypos=inStrRev(word,"Testing\ATS")
If mypos>=1 Then
Rem split the Cell data
myarray=Split(word,"ATS",-1,1)
If myarray(0)="D:\Testing\" Then
Rem Change the Data "D:\Testing" to "C:\Testing"
myarray(0)="C:\Testing\"
Rem Add Total Cell Data
word=myarray(0)&"ATS"&myarray(1)
Rem Enter the Modified Data in Cell
Cells(curRow,curCol).Value=word
End If
End If
Rem Change the Cell Data(machine name) other then Local machine name
If Ucase(word)= "ALP-QASIM13-2K3" Then
Cells(curRow,curCol).Value=Computername
End If
Rem display the column on the screen
'WScript.Echo (word)
Next
Next
Rem We are done with the current worksheet, release the memory
Set currentWorkSheet = Nothing
Next
objExcel.workbooks(1).save
objExcel.Workbooks(1).Close
objExcel.Quit
Set currentWorkSheet = Nothing
Rem We are done with the Excel object, release it from memory
Set objExcel = Nothing

Find out list of Data bases in SQL (SQL Query)


sp_databases
Posted by Kamesh at 4:47 AM 0 comments

Kill the Process if the process is under System not in User Using QTP
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "cmd /k cd\ & cd c:\windows\system32 & taskkill /F /IM
ProcessName.exe"
''''' like "services.exe"
Posted by Kamesh at 4:43 AM 0 comments

Verify whether Database is exist or not if not Create DB in SQL


if not exists(select * from sys.databases where name = 'selftest')
create database selftest ''' Here selftest is DB Name
Posted by Kamesh at 4:39 AM 0 comments

Tuesday, April 7, 2009


Connect the Data Base and Retrieve the Data from tables use QTP
'Variable Declaration
Option Explicit
Dim Dsn_conn,rs,PTime,NowDate
Dim myarray,DiffADate
Dim strServer,strUid,strQry
Dim objConnection
' Action parameters
strServer=parameter("Server") ' This is Server Name
strUid=parameter("Uid") ' User Id
Set objConnection=Createobject("ADODB.Connection")
Dsn_conn= "DRIVER=SQL
Server;SERVER="&strServer&";UID="&strUid&";APP=QuickTest
Professional;WSID="&strServer&";Trusted_Connection=Yes"
objConnection.Open(Dsn_conn)
If err.number <> 0 Then
Reporter.ReportEvent 1 ,"DBConnection","Unable to Connect to the
database"&"Err Description = " & err.Description
Else
Reporter.ReportEvent 0 ,"DBConnection","Connection Succeeded"
End If
Set rs=CreateObject("ADODB.RecordSet")
strQry = "UPDATE ELinkQueues.dbo.ELKMasterArchive SET ProcessedTime =
DATEADD(""Day"", -10, ProcessedTime) WHERE (ProcessedTime IS NOT
NULL) AND (Status = 2 OR Status = 3)" ' this is Query
Set rs=objconnection.execute(strQry)
Set rs=objconnection.execute("Select * from
ELinkQueues.dbo.ELKMasterArchive")
rs.MoveFirst
Do While Not rs.EOF
PTime=rs.fields.item("ProcessedTime")
Exit Do
rs.movenext
Loop
rs.Close
objConnection.Close
Posted by Kamesh at 2:52 AM 0 comments

Wednesday, April 1, 2009

Change the Data in XML File


Set oFSO = CreateObject("Scripting.FileSystemObject")
strApptEnterPath = "C:\Documents and Settings\krao\Desktop\environment.xml"
If CheckFileExists(strApptEnterPath) Then
Set objFile = oFSO.GetFile(strApptEnterPath)
' Checks for file attributes. This is a check for file being readonly. As the latests is taken
from VSTS it will be marked as readonly. This code will uncheck the Readonly property
If objFile.Attributes AND 1 Then
objFile.Attributes = objFile.Attributes - 1
End If
Else
ExitAction "Fail"
End If
set objReadFile = OpenFile(strApptEnterPath,1)
strContents = objReadFile.ReadAll
iTmpLoc = Instr(strContents,"ELK_DATA_FILES" & vbcrlf & vbtab & vbtab & "")
strTmpVal = left(strContents,iTmpLoc-1)
strFinal = strTmpVal & "ELK_DATA_FILES" & vbcrlf & vbtab & vbtab & ""
strContents = replace(strContents,strFinal,"")
iTmpLoc = Instr(strContents,"")
strTmpVal = left(strContents,iTmpLoc-1)
' this is the exact if condition in the logic section.
strIfCondString = "C" & right(strTmpVal,len(strTmpVal) - 1)
strFinal = strFinal & strIfCondString & ""
strContents = replace(strContents,strTmpVal & "","")
strFinal = strFinal & strContents
objReadFile.close
set objReadFile = OpenFile(strApptEnterPath,2)
objReadFile.write strFinal
objReadFile.close
Set objReadFile = Nothing
Set objFile = Nothing
Function CheckFileExists (FilePath)
CheckFileExists = oFSO.FileExists(FilePath)
End Function
Function OpenFile (FilePath,mode)
set OpenFile = oFSO.OpenTextFile(FilePath, mode, True)
End Function

Select the option from Context menu


' right click and select Required option
intIdx=13 'points the which option to select in the right click menu
wpfWindow("Eclipsys Gateway My").SwfWindow("Prescription
Writer").SwfTable("dgOMP").Click 20,20,micRightBtn
Set WshShell = CreateObject("WScript.Shell")
For intLoop = 1 To intIdx
WshShell.sendkeys "{DOWN}"
Next
WshShell.sendkeys "{ENTER}"
Set WshShell = nothing
Posted by Kamesh at 10:26 PM 0 comments

Converting HTML Text to Plain Text


HTML and XML are very common entities in the testing/automation world. At time
we are required to convert the HTML/XML to a Plain text version. Example of
such a conversion can be seen below
The converted text for about HTML
would be “Click on the Login link”. One example of such a situation is Reading
the description text of a Step

Find out all the drives including Caption,size from one machine
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _ "SELECT * FROM
Win32_DiskDrive",,48)
For Each objItem in colItems
msgbox "Caption: " & objItem.Caption
msgbox "DeviceID: " & objItem.DeviceID
msgbox "Partitions: " & objItem.Partitions
msgbox "Size: " & objItem.Size
Next

Add all Recovery scenarios to new test through code


Dim qtApp 'As QuickTest.Application ' Declare the Application object variable

Dim qtTestRecovery 'As QuickTest.Recovery ' Declare a Recovery object


variable
Dim intIndex ' Declare an index variable
' Open QuickTest and prepare objects variables

Set qtApp = CreateObject("QuickTest.Application") ' Create the Application

objectqtApp.Launch ' Start QuickTest

qtApp.New ' Open a new test

qtApp.Visible = True ' Make the QuickTest application visible

Set qtTestRecovery = qtApp.Test.Settings.Recovery ' Return the Recovery


object for the current test
If qtTestRecovery.Count > 0 Then ' If there are any default scenarios specified
for the test qtTestRecovery.RemoveAll ' Remove them

End If
' Add recovery scenarios

qtTestRecovery.Add "C:\Recovery.qrs", "ErrMessage", 1 ' Add the "ErrMessage"


scenario as the first scenario

qtTestRecovery.Add "C:\Recovery.qrs", "AppCrash", 2 ' Add the "AppCrash"


scenario as the second scenario

qtTestRecovery.Add "C:\Recovery.qrs", "ObjDisabled", 3 ' Add the "ObjDisabled"


scenario as the third scenario
' Enable all scenarios

For intIndex = 1 To qtTestRecovery.Count ' Iterate the scenarios

qtTestRecovery.Item(intIndex).Enabled = True ' Enable each Recovery Scenario


(Note: the 'Item' property is default and can be omitted)

Next
' Enable the recovery mechanism (with default, on errors, setting)

qtTestRecovery.Enabled = True
'Ensure that the recovery mechanism is set to be activated only after errors

qtTestRecovery.SetActivationMode "OnError"

'OnError is the default, the other option is "OnEveryStep".


Set qtApp = Nothing ' Release the Application object

Set qtTestRecovery = Nothing ' Release the Recovery object


Verify Whether DataBase is Exist or Not and if it's not Restore given Database in
Data Base through QTP
'Variable Declaration
Option Explicit
Dim Dsn_conn , rs , oServer , strServer,strUid,strQry , strDBName , fso, msg ,
FileStatus
Dim objConnection , oRestore ,SQLDMORestore_Database , strFilePath ,
strActualPath
' Action parameters
strServer=parameter("Server")''''' Server Name where SQL is Running
strUid=parameter("Uid") '''''' User Id which have permissions to logon SQL
strDBName=Parameter("DBName") '''' DB Name which DB you have to Restore
strFilePath=Parameter("FilePath") '' Path of the DB file
Set objConnection=Createobject("ADODB.Connection")
Dsn_conn= "DRIVER=SQL
Server;SERVER="&strServer&";UID="&strUid&";APP=QuickTest
Professional;WSID="&strServer&";Trusted_Connection=Yes"
objConnection.Open(Dsn_conn)
If err.number <> 0 Then
Reporter.ReportEvent 1 ,"DBConnection","Unable to Connect to the
database"&"Err Description = " & err.Description
Else
Reporter.ReportEvent 0 ,"DBConnection","Connection Succeeded"
End If
Set rs=CreateObject("ADODB.RecordSet")
' Verify whether Data base is Exist or not
strQry = "if not exists(select * from sys.databases where name = 'selftest') create
database selftest"
Set rs=objconnection.execute(strQry)
'rs.Close
objConnection.Close
' Verify whether DB File is Exist in C Drive or not
strActualPath="C:\selftest.bak"
FileStatus=ReportFileStatus(strActualPath)
Function ReportFileStatus(filespec)
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(filespec)) Then
msg = "True"
Else
msg = "False"
End If
ReportFileStatus = msg
set fso=nothing
End Function
' Copy the DB File From given path to C Drive
If Filestatus="True" Then
Call RestoreDBFromFile(strServer,strDBName,strActualPath)
Else
Set fso = CreateObject("Scripting.FileSystemObject")
fso.copyFile strFilePath,"C:\"
FileStatus=ReportFileStatus(strActualPath)
If Filestatus="True" Then
Reporter.ReportEvent 0,"Data Base File"," Is Copied"
Call RestoreDBFromFile(strServer,strDBName,strActualPath)
Else
Reporter.ReportEvent 1,"Data Base File"," Is Not Copied"
End If
End If
' Delete DB File From C Drive
DeleteAFile(strActualPath)
Sub DeleteAFile(filespec)
Set fso = CreateObject("Scripting.FileSystemObject")
fso.DeleteFile(filespec)
End Sub
Sub RestoreDBFromFile(ServerName , DBName , BackupToRestore )
'simple err checking
If ServerName = "" Or DBName = "" Or BackupToRestore = "" Then
Reporter.ReportEvent 1,"DB Connection ", "You MUST provide server name,
database name, and the name of the bak file you want to restore"
Exit Sub
End If
'open connection to server
Set oServer =CreateObject("SQLDMO.SQLServer")
With oServer
.LoginSecure = True
.Connect ServerName
End With
'also need a restore object
Set oRestore = CreateObject("SQLDMO.Restore")
With oRestore
.Database = DBName
.Action = SQLDMORestore_Database
.ReplaceDatabase = True
.Files = BackupToRestore
.SQLRestore oServer
End With
Set oRestore = Nothing
oServer.DisConnect
Set oServer = Nothing
Reporter.ReportEvent 0,"Data Base","Data Base is Restored with Name :
"&DBName
End Sub
Posted by Kamesh at 4:17 AM 0 comments

how to get the column values and column header through QTP from Infragistics
UltraGrid(If Applications are developed using Net advantage Controls)
rowcount=WpfWindow("Eclipsys Gateway My").SwfWindow("Custom
View").SwfTable("grFilter").GetNAProperty("Rows.Count")
'Then to access each row:
For I = 0 TO rowcount-1
Set currentRow = WpfWindow("Eclipsys Gateway My").SwfWindow("Custom
View").SwfTable("grFilter").GetNAProperty("Rows["+CSTR(I)+"]")
' To get a specific cell text for the current row
cellText =WpfWindow("Eclipsys Gateway My").SwfWindow("Custom
View").SwfTable("grFilter").GetNAProperty("Rows["+CSTR(I)+"].Cells[3].Text")
msgbox cellText
Next

iColIndex = 2
strColKey = "value"
SET grid = WpfWindow("Eclipsys Gateway My").SwfWindow("Custom
View").SwfTable("grFilter")
msgbox
grid.GetNAProperty("DisplayLayout.Bands[0].Columns["+CSTR(iColIndex)
+"].Header.Caption")
msgbox grid.GetNAProperty("DisplayLayout.Bands[0].Columns["+strColKey
+"].Header.Caption")
Posted by Kamesh at 4:04 AM 0 comments

How to find the Network UserName


Set wshNetwork =CreateObject( "WScript.Network" )
strUserName = wshNetwork.UserName
msgbox strUserName
TEST AUTOMATION FRAMEWORK

This section gives the introduction about test automation framework, various
types of the framework and the analysis of the best suitable framework for the
application under test (the application under test is referred as AUT). This also includes
the detailed description of the format of the input (the input to the framework is referred
as the test tables) that is given to our test automation framework.

1.1 RECORD/PLAYBACK MYTH

The test automation tool vendors market their product as the main feature of the
tool is the ability to capture the user actions and later to playback them. Here is the basic
paradigm for GUI-based automated regression testing – the so called Record/Playback
method (also called as Capture/Replay approach)

1. Design a test case in the test management tool.

2. Using the capture feature of the automation testing tool record the user actions. The
result is a macro-like script where each user action is presented.

3. Enhance the recorded script with verification points, where some property or data is
verified against an existing baseline. Add delay and wait states points where the different
actions are synchronized.

4. Playback the scripts and observe the results in the log of the test management tool.

The basic drawback in this method is the scripts resulting from this method
contain hard-coded values which must change if anything at all changes in our AUT. The
costs associated with maintaining such scripts are astronomical, and unacceptable.
These scripts are not reliable, even if the application has not changed, and often fail on
replay (pop-up windows, messages, and other things can happen that did not happen
when the test was recorded).

If the tester makes an error entering data, etc., the test must be re-recorded. If
the application changes the test must be re-recorded. All that is being tested are things
that already work. Areas that have errors are encountered in the recording process
(which is manual testing, after all). These bugs are reported, but a script cannot be
recorded until the software is corrected. So logically nothing is tested by this approach.

Play with WinRunner by recording and playing it back. Refer the WinRunner
Tutorial & WinRunner User Guide

<!--[if !vml]-->
<!--[endif]-->

So, avoid using "Record/Playback" as a method of automating testing. This


method is fraught with problems, and is the most costly (time consuming) of all methods
over the long term. The record/playback feature of the test tool is useful for determining
how the tool is trying to process or interact with the application under test, and can give
us some ideas about how to develop your test scripts, but beyond that, its usefulness
ends quickly.

1.2 TYPES OF TEST AUTOMATION FRAMEWORKS

As we have eliminated Record/Playback method, let us explore about the


existing automation methodologies. There are several test automation frameworks
available, among these the selection is made based on the factors such as reusability of
both the scripts and the test assets. The different test automation frameworks available
are as follows,

<!--[if !supportLists]--> <!--[endif]-->Test Script Modularity

<!--[if !supportLists]--> <!--[endif]-->Test Library Architecture

<!--[if !supportLists]--> <!--[endif]-->Data-Driven Testing


<!--[if !supportLists]--> <!--[endif]-->Keyword-Driven or Table-Driven
Testing

<!--[if !supportLists]--> <!--[endif]-->Hybrid Test Automation

1.2.1 Test Script Modularity

The test script modularity framework is the most basic of the frameworks. It's a
well-known programming strategy to build an abstraction layer in front of a component to
hide the component from the rest of the application. This insulates the application from
modifications in the component and provides modularity in the application design. When
working with test scripts (in any language or proprietary environment) this can be
achieved by creating small, independent scripts that represent modules, sections, and
functions of the application-under-test. Then these small scripts are taken and combined
them in a hierarchical fashion to construct larger tests. The use of this framework will
yield a higher degree of modularization and add to the overall maintainability of the test
scripts.

1.2.2 Test Library Architecture

The test library architecture framework is very similar to the test script modularity
framework and offers the same advantages, but it divides the application-under-test into
procedures and functions (or objects and methods depending on the implementation
language) instead of scripts. This framework requires the creation of library files
(SQABasic libraries, APIs, DLLs, and such) that represent modules, sections, and
functions of the application-under-test. These library files are then called directly from
the test case script. Much like script modularization this framework also yields a high
degree of modularization and adds to the overall maintainability of the tests.

1.2.3 Data-Driven Testing

A data-driven framework is where test input and output values are read from data
files (ODBC sources, CVS files, Excel files, DAO objects, ADO objects, and such) and
are loaded into variables in captured or manually coded scripts. In this framework,
variables are used for both input values and output verification values. Navigation
through the program, reading of the data files, and logging of test status and information
are all coded in the test script. This is similar to table-driven testing (which is discussed
shortly) in that the test case is contained in the data file and not in the script; the script is
just a "driver," or delivery mechanism, for the data. In data-driven testing, only test data
is contained in the data files.

1.2.3.1 Merits of data-driven testing

The merits of the Data-Driven test automation framework are as follows,

<!--[if !supportLists]--> <!--[endif]-->Scripts may be developed while


application development is still in progress

<!--[if !supportLists]--> <!--[endif]-->Utilizing a modular design, and using


files or records to both input and verify data, reduces redundancy and
duplication of effort in creating automated test scripts

<!--[if !supportLists]--> <!--[endif]-->If functionality changes, only the


specific "Business Function" script needs to be updated

<!--[if !supportLists]--> <!--[endif]-->Data input/output and expected


results are stored as easily maintainable text records.

<!--[if !supportLists]--> <!--[endif]-->Functions return "TRUE" or "FALSE"


values to the calling script, rather than aborting, allowing for more
effective error handling, and increasing the robustness of the test scripts.
This, along with a well-designed "recovery" routine, enables "unattended"
execution of test scripts.

1.2.3.2 Demerits of data-driven testing

The demerits of the Data-Driven test automation framework are as follows,

<!--[if !supportLists]--> <!--[endif]-->Requires proficiency in the Scripting


language used by the tool (technical personnel)
<!--[if !supportLists]--> <!--[endif]-->Multiple data-files are required for
each Test Case. There may be any number of data-inputs and
verifications required, depending on how many different screens are
accessed. This usually requires data-files to be kept in separate
directories by Test Case

<!--[if !supportLists]--> <!--[endif]-->Tester must not only maintain the


Detail Test Plan with specific data, but must also re-enter this data in the
various required data-files

<!--[if !supportLists]--> <!--[endif]-->If a simple "text editor" such as


Notepad is used to create and maintain the data-files, careful attention
must be paid to the format required by the scripts/functions that process
the files, or script-processing errors will occur due to data-file format
and/or content being incorrect

1.2.4 Keyword-Driven Testing

This requires the development of data tables and keywords, independent of the
test automation tool used to execute them and the test script code that "drives" the
application-under-test and the data. Keyword-driven tests look very similar to manual
test cases. In a keyword-driven test, the functionality of the application-under-test is
documented in a table as well as in step-by-step instructions for each test. In this
method, the entire process is data-driven, including functionality.

1.2.4.1 Example

In order to open a window, the following table is devised, and it can be used for
any other application, just it requires just changing the window name.

Test Table for Opening a Window

Window Control Action Arguments

Window Name Menu Click File, Open


Window Name Menu Click Close

Window Name Pushbutton Click Folder Name

Window Name Verify Results

Once creating the test tables, a driver script or a set of scripts is written that
reads in each step executes the step based on the keyword contained the Action field,
performs error checking, and logs any relevant information.

1.2.4.2 Merits of keyword driven testing

The merits of the Keyword Driven Testing are as follows,

<!--[if !supportLists]--> <!--[endif]-->The Detail Test Plan can be written in


Spreadsheet format containing all input and verification data.

<!--[if !supportLists]--> <!--[endif]-->If "utility" scripts can be created by


someone proficient in the automated tool’s Scripting language prior to the
Detail Test Plan being written, then the tester can use the Automated
Test Tool immediately via the "spreadsheet-input" method, without
needing to learn the Scripting language.

<!--[if !supportLists]--> <!--[endif]-->The tester need only learn the "Key


Words" required, and the specific format to use within the Test Plan. This
allows the tester to be productive with the test tool very quickly, and
allows more extensive training in the test tool to be scheduled at a more
convenient time.

1.2.4.3 Demerits of keyword driven testing

The demerits of the Keyword Driven Testing are as follows,

<!--[if !supportLists]--> <!--[endif]-->Development of "customized"


(Application-Specific) Functions and Utilities requires proficiency in the
tool’s Scripting language. (Note that this is also true for any method)
<!--[if !supportLists]--> <!--[endif]-->If application requires more than a
few "customized" Utilities, this will require the tester to learn a number of
"Key Words" and special formats. This can be time-consuming, and may
have an initial impact on Test Plan Development. Once the testers get
used to this, however, the time required to produce a test case is greatly
improved.

1.2.5 Hybrid Test Automation Framework

The most commonly implemented framework is a combination of all of the above


techniques, pulling from their strengths and trying to mitigate their weaknesses. This
hybrid test automation framework is what most frameworks evolve into over time and
multiple projects. The most successful automation frameworks generally accommodate
both Keyword-Driven testing as well as Data-Driven scripts.

This allows data driven scripts to take advantage of the powerful libraries and
utilities that usually accompany a keyword driven architecture. The framework utilities
can make the data driven scripts more compact and less prone to failure than they
otherwise would have been.

The utilities can also facilitate the gradual and manageable conversion of existing
scripts to keyword driven equivalents when and where that appears desirable. On the
other hand, the framework can use scripts to perform some tasks that might be too
difficult to re-implement in a pure keyword driven approach, or where the keyword driven
capabilities are not yet in place. The following sections describe its architecture, merits
and demerits.

Our test automation framework is a


Hybrid Test Automation Framework

<!--[if !vml]-->
<!--[endif]-->

1.2.5.1 Hybrid Test Automation Framework Architecture

The framework is defined by the Core Data Driven Engine, the Component
Functions, and the Support Libraries. While the Support Libraries provide generic
routines useful even outside the context of a keyword driven framework, the core engine
and component functions are highly dependent on the existence of all three elements.

The test execution starts with the LAUNCH TEST(1) script. This script invokes
the Core Data Driven Engine by providing one or more High-Level Test Tables to
CycleDriver(2). CycleDriver processes these test tables invoking the SuiteDriver(3) for
each Intermediate-Level Test Table it encounters. SuiteDriver processes these
intermediate-level tables invoking StepDriver(4) for each Low-Level Test Table it
encounters. As StepDriver processes these low-level tables it attempts to keep the
application in synch with the test. When StepDriver encounters a low-level command for
a specific component, it determines what Type of component is involved and invokes the
corresponding Component Function(5) module to handle the task.

The Application Map is referred to App Map. This App Map in WRAFS is the
Application Map file created from GUI Map of WinRunner

<!--[if !vml]--><!--[endif]-->

All of these elements of the framework rely on the information provided in the
App Map to interface or bridge the automation framework with the application being
tested. The App Map is the only means by which the framework could identify the
objects in the application under test. Each of these elements is described in more detail
in the following sections. The following figure shows the diagrammatic representation of
the Hybrid Test Automation Framework.

Some Basic Useful re-usable Scripts in QTP


General Functions which might be useful in the projects:-

Array Basics
Some basic info about creating and using arrays.
' The easiest way create an array is to simply declare it as follows
Dim strCustomers()
' Another method is to define a variable and then set it as an array afterwards
Dim strStaff
strStaff = Array("Alan","Brian","Chris")
' Yet another way is to use the split command to create and populate the array
Dim strProductArray
strProductArray = "Keyboards,Laptops,Monitors"
strProductArray = Split(strProductArray, ",")
' To itterate through the contents of an array you can use the For Each loop
Dim strItem
For Each strItem In strProductArray
MsgBox strItem
Next
' This will also itterate through the loop
Dim intCount
For intCount = LBound(strProductArray) To UBound(strProductArray)
Msgbox strProductArray(intCount)
Next
' This will itterate through the array backwards
For intCount = UBound(strProductArray) To LBound(strProductArray) Step -1
Msgbox strProductArray(intCount)
Next
' To add extra data to an array use Redim Preserve
Redim Preserve strProductArray(3)
strProductArray(3) = "Mice"
' To store the contents of an array into one string, use Join
Msgbox Join(strProductArray, ",")
' To delete the contents of an array, use the Erase command
Erase strProductArray
Date Manipulation Examples
Some date manipulation functions.

' show todays date


MsgBox Date
' show the time
MsgBox Time

' show both the date and time


MsgBoxNow

' calculate the minimum Date of Birth for someone who is 18 years old
strMinDoB = DateAdd("yyyy", -18, Date)
MsgBox strMinDob

' show the number of years difference between strMinDob and today
MsgBox DateDiff("yyyy", strMinDob, Date)

' show the hour portion of the time


MsgBox DatePart("h", Time)

' show the day portion of the date


MsgBox Day(strMinDob)

' show the month portion of the date


MsgBox Month(strMinDob)

' show the year portion of the date


MsgBox Year(strMinDob)

' show the weekday portion of the date


' Sunday=1, Monday=2, --> Saturday=7
MsgBox WeekDay(strMinDob)

Note: Acceptable 'Interval' parameters for DatePart, DateAdd and DateDiff...


"yyyy" = Year
"q" = Quarter
"m" = Month
"y" = Day of year
"d" = Day
"w" = Weekday
"ww" = Week of year
"h" = Hour
"n" = Minute
"s" = Second

Get Child Obects


Find all checkboxes on a webpage.
Here's a basic example that will find and tick all of the checkboxes on the QTP
Helper login screen.
Dim objDescription
Dim objCheckBoxes
Dim iCount

' create description objects used to locate check boxes


Set objDescription = Description.Create()

' set the object properties so it looks only for web check boxes
objDescription("micclass").Value = "WebCheckBox"

' check that the user isn't already logged in


If Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebButton("Name:=Logout").Exist(1) Then

' click logout


Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebButton("Name:=Logout").Click
End If

' get the check boxes from the page


Set objCheckBoxes = Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").ChildObjects(objDescription)

' for each check box found


For iCount = 0 to objCheckBoxes.Count - 1

' tick the check box


Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebCheckBox(objCheckBoxes(iCount)).Set "ON"

Next

Compare Arrays
Compare the contents of two arrays.
' Example usage
sA = Array("A", "B", "D")
sB = Array("A", "C", "B")

MsgBox CompareArrays(sA, sB)


' =============================================================
' function: CompareArrays
' desc : Compares the content of two arrays and checks that
' they each contain the same data, even if in a
' different order
' params : arrArray1 is the base array
' arrArray2 is the array to compare
' returns : True if they contain same data, False otherwise
' =============================================================
Function CompareArrays(arrArray1, arrArray2)

Dim intA1
Dim intA2
Dim blnMatched

' check that the arrays are the same size


If UBound(arrArray1) <> UBound(arrArray2) then

' arrays are different size, so return false and exit function
CompareArrays = False
Exit Function

End if

' for each element in the first array


For intA1 = LBound(arrArray1) to UBound(arrArray1)

' initialise this to false


blnMatched = False

' for each element in the second array


For intA2 = LBound(arrArray2) to UBound(arrArray2)

' compare the content of the two arrays


If arrArray1 (intA1) = arrArray2 (intA2) Then
blnMatched = True
Exit For
End If

Next ' next element in second array

' if the element was not found in array two, return false and exit function
If Not blnMatched then
CompareArrays = False
Exit Function
End If

Next ' next element in first array

' if the function got this far, then the arrays contain the same data
CompareArrays = True

End Function ' CompareArrays

Custom Report Entry


Creating a customised entry in the results.

' Example usage


CustomReportEntry micFail, "Custom Report Example", "
This is a custom report entry!
"

' =============================================================
' function: CustomReportEntry
' desc : Creates a customized entry in the result file, you
' can use standard HTML tags in the message.
' params : strStatus is the result, micPass, micFail etc
' strStepName is the name of the step
' strMessage is the failure message, this can contain
' html tags
' returns : Void
' =============================================================
Function CustomReportEntry(strStatus, strStepName, strMessage)
' create a dictionary object
Set objDict = CreateObject("Scripting.Dictionary")

' set the object properties


objDict("Status") = strStatus
objDict("PlainTextNodeName") = strStepName
objDict("StepHtmlInfo") = strMessage
objDict("DllIconIndex") = 206
objDict("DllIconSelIndex") = 206
objDict("DllPAth") = "C:\Program Files\Mercury Interactive\QuickTest
Professional\bin\ContextManager.dll"

' report the custom entry


Reporter.LogEvent "User", objDict, Reporter.GetContext

End Function 'CustomReportEntry

Bcreating Custom Libraries


An example of how to create your own custom library.
This example will show you how to create your own customised code
library, using Visual Basic 6 as an example.

First thing to do is open Visual Basic and create a new Active X DLL project...
Before we add any code, we should give the Project and the Class Library
sensible names.

Here I've called the project "QTP"...

For the Class Library I've simply called it "Library"...

Now we can add a function to our Library. For this example I'm going to use a
very
basic function which will simply display a message box with a given parameter
value...

Next thing we need to do is create the DLL, this can be done from the File
menu in Visual Basic...

Note that during the development of the DLL, you can simply press F5 to run
the code in Visual
Basic. We can then still call the function from QTP, this allows us to put break-
points inside
the Visual Basic code and do some debugging.

Another thing to note is that when you finish the DLL and want to use it on
other machines,
you will need to register the DLL on the system. This can be done by simply
dragging and dropping
the DLL onto the file "RegSvr32.exe", which can be found in your Windows\
System32 folder.
Now that we have our new library ready, we can call the functions from QTP...

Dim objDLL

' create an object for our new library


Set objDLL = CreateObject("QTP.Library")

' call the function from the library


objDLL.QTPHelper_Example "Easy!"

' destroy the object


Set objDLL = Nothing

And here is the end result...

Using methods like this will open up several new doors for your automation by
allowing you to
execute code which isn't as easy to implement in VB Script as it is in other
languages.

Running DOS Commands


Running Dos Commands

' =============================================================
' Sub : ExecuteDosCommand
' desc : Run a single-line DOS command
' params : Command to run
' returns : void
' =============================================================
Sub ExecuteDosCommand(strCommand)

Dim objShell

' create the shell object


Set objShell = CreateObject("WSCript.shell")

' run the command


objShell.run strCommand

' destroy the object


Set objShell = Nothing

End Sub 'ExecuteDosCommand

Export Data Sheet


Export a data sheet at runtime.
' =============================================================
' function: ExportDataSheet
' desc : Exports a data sheet
' params : strFile - full path to save the exported xls, note
' that any existing xls will be deleted
' strSheet - sheet to export
' returns : void
' =============================================================
Function ExportDataSheet(strFile, strSheet)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the xls doesn't already exist
If objFS.FileExists(strFile) Then
' delete it if it exists
ObjFS.DeleteFile strFile

End If
' export the data table
DataTable.ExportSheet strFile, strSheet
' destroy the object
Set objFS = Nothing
End Function 'ExportDataSheet

Execute a Stored Procedure


Some code that should help you execute a stored procedure.

' set the parameters of your database here


strDatabaseName = ""
strUser = ""
strPassword = ""
strStoredProcedureName = ""

' create the database object


Set objDB = CreateObject("ADODB.Command")
' set the connection string
objDB.ActiveConnection = "DRIVER={Microsoft ODBC for Oracle}; " & _
"SERVER=" & strDatabaseName & _
";User ID=" & strUser & ";Password=" & strPassword & " ;"

' set the command type to Stored Procedures


objDB.CommandType = 4
objDB.CommandText = strStoredProcedureName

' define Parameters for the stored procedure


objDB.Parameters.Refresh
' set parameters for stored procedure (i.e. two parameters here)
objDB.Parameters(0).Value = "Param1"
objDB.Parameters(1).Value = "Param2"

' execute the stored procedure


objDB.Execute()
' destroy the object
Set objDB = Nothing

Execute Method In Regular Expressions


Executing a regular expression to find text within a string.

MsgBox RegularExpExample("QTP.", "QTP1 QTP2 qtp3 QTP4")

' =============================================================
' function: RegularExpExample
' desc : Example of how to use the regular expression object
' to find text within a string
' params : strPattern is the regular expression
' strString is the string to use the expression on
' returns : An example string showing the results of the search
' =============================================================
Function RegularExpExample(strPattern, strString)

Dim objRegEx, strMatch, strMatches


Dim strRet

' create regular expression object


Set objRegEx = New RegExp

' set the pattern


objRegEx.Pattern = strPattern
' set it be not case sensitive
objRegEx.IgnoreCase = True

' set global flag so we search all of the string, instead of just searching
' for the first occurrence
objRegEx.Global = True

' execute search


Set strMatches = objRegEx.Execute(strString)

' for each match


For Each strMatch in strMatches

strRet = strRet & "Match found at position '" & _


strMatch.FirstIndex & "' - Matched Value is '" & _
strMatch.Value & "'" & vbCRLF

Next

RegularExpExample = strRet

End Function ' RegularExpExample

Export Data Table


Export a data table at runtime.
' =============================================================
' function: ExportDataTable
' desc : Exports a data table
' params : strFile - full path to save the exported xls, note
' that any existing xls will be deleted
' returns : void
' =============================================================
Function ExportDataTable(strFile)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the xls doesn't already exist
If objFS.FileExists(strFile) Then
' delete it if it exists
ObjFS.DeleteFile strFile

End If
' export the data table
DataTable.Export strFile
' destroy the object
Set objFS = Nothing
End Function 'ExportDataTable
Export Data Sheet
Export a data sheet at runtime.
' =============================================================
' function: ExportDataSheet
' desc : Exports a data sheet
' params : strFile - full path to save the exported xls, note
' that any existing xls will be deleted
' strSheet - sheet to export
' returns : void
' =============================================================
Function ExportDataSheet(strFile, strSheet)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the xls doesn't already exist
If objFS.FileExists(strFile) Then
' delete it if it exists
ObjFS.DeleteFile strFile

End If
' export the data table
DataTable.ExportSheet strFile, strSheet
' destroy the object
Set objFS = Nothing
End Function 'ExportDataShee

Read From Excel File


Read all the data from an Excel file.

' =============================================================
' function: ReadXLS
' desc : Reads a sheet from an XLS file and stores the content
' in a multi-dimensional array
' params : strFileName is XLS file to read, including path
' strSheetName is the name of the sheet to read, i.e "Sheet1"
' returns : Multi-dimensional array containing all data from
' the XLS
' =============================================================
Function ReadXLS(strFileName,strSheetName)

Dim strData()
Dim objFS, objExcel, objSheet, objRange
Dim intTotalRow, intTotalCol
Dim intRow, intCol

' create the file system object


Set objFS = CreateObject("Scripting.FileSystemObject")

' ensure that the xls file exists


If Not objFS.FileExists(strFileName) Then

' issue a fail if the file wasn't found


Reporter.ReportEvent micFail, "Read XLS", "Unable to read XLS file, file not
found: " & strFileName
' file wasn't found, so exit the function
Exit Function

End If ' file exists

' create the excel object


Set objExcel = CreateObject("Excel.Application")

' open the file


objExcel.Workbooks.open strFileName

' select the worksheet


Set objSheet = objExcel.ActiveWorkbook.Worksheets(strSheetName)

' select the used range


Set objRange = objSheet.UsedRange

' count the number of rows


intTotalRow=CInt(Split(objRange.Address, "$")(4)) - 1

' count the number of columns


intTotalCol= objSheet.Range("A1").CurrentRegion.Columns.Count

' redimension the multi-dimensional array to accomodate each row and column
ReDim strData(intTotalRow, intTotalCol)

' for each row


For intRow = 0 to intTotalRow - 1
' for each column
For intCol =0 to intTotalCol - 1

' store the data from the cell in the array


strData(intRow, intcol) = Trim(objSheet.Cells(intRow + 2,intcol + 1).Value)

Next ' column

Next ' row

' close the excel object


objExcel.DisplayAlerts = False
objExcel.Quit

' destroy the other objects


Set objFS = Nothing
Set objExcel = Nothing
Set objSheet = Nothing

' return the array containing the data


ReadXLS = strData

End Function ' ReadXLS

File Browser
Opens a standard dialog which allows the user to choose a file.
' =============================================================
' function : FileBrowser
' desc : Opens a standard Open File Dialog
' params : strTitle - the title to apply to the dialog
' strFilter - the filter to apply to the dialog
' returns : The selected file, including path
' =============================================================
Public Function FileBrowser(strTitle, strFilter)

Dim objDialog
' create a common dialog object
Set objDialog = CreateObject("MSComDlg.CommonDialog")
' set the properties and display the dialog
With objDialog
.DialogTitle = strTitle
.Filter = strFilter
.MaxFileSize = 260
.ShowOpen
End With
' return the selected file
FileBrowser = objDialog.FileName
' destroy the object
Set objDialog = Nothing

End Function ' FileBrowser


File Exists
Check to see if a local or network file exists.
' =============================================================
' function: CheckFileExists
' desc : Checks to see if a file exists
' params : strFile - full path of the file to find
' returns : True if file exists, False otherwise
' =============================================================
Function CheckFileExists(strFile)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source file exists
If objFS.FileExists(strFile) Then
' file exists, return true
CheckFileExists = True

Else

' file exists, return false


CheckFileExists = False

End If

End Function 'CheckFileExists

Folder Exists
Check to see if a local or network folder exists.
' =============================================================
' function: CheckFolderExists
' desc : Checks to see if a folder exists
' params : strFolder - full path of the folder to find
' returns : True if folder exists, False otherwise
' =============================================================
Function CheckFolderExists(strFile)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source file exists
If objFS.FolderExists(strFolder) Then
' file exists, return true
CheckFolderExists = True

Else

' file exists, return false


CheckFolderExists = False

End If
' destroy the object
Set objFS = Nothing

End Function 'CheckFolderExists

Create Folder
Create a local or network folder.
' =============================================================
' function: FolderCreate
' desc : Creates a folder
' params : strFolderPath - the folder to create (full path)
' returns : void
' =============================================================
Function FolderCreate(strFolderPath)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' create the folder
If Not objFS.FolderExists(strFolderPath) Then
objFS.CreateFolder strFolderPath
End If
' destroy the object
Set objFS = Nothing

End Function 'FolderCreate

Delete Folder
Delete a local or network folder.
' =============================================================
' function: FolderDelete
' desc : Deletes a folder and all of it's contents
' params : strFolder - the folder to delete
' returns : void
' =============================================================

Function FolderDelete(strFolder)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source folder exists
If Not objFS.FolderExists(strFolder) Then
' fail if the source does not exist
reporter.ReportEvent micFail, "Delete Folder", "Unable to Delete Folder '"&
strFolder &"', It Does Not Exist"
Else
' delete the folder
objFS.DeleteFolder strFolder

End If
' destroy the object
Set objFS = Nothing

End Function 'FolderDelete


Move Folder
Move a local or network folder.
' =============================================================
' function: FolderMove
' desc : Moves a folder and all of its files to a new path
' params : strSourceFolder - the folder to copy
' strDestinationFolder - the location to copy to
' returns : void
' =============================================================
Function FolderMove(strSourceFolder, strDestinationFolder)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source folder exists
If Not objFS.FolderExists(strSourceFolder) Then
' fail if the source does not exist
reporter.ReportEvent micFail, "Move Folder", "Source Folder '"& strSourceFolder
&"' Does Not Exist"
Else
' check that the destination folder doesn't already exist
If Not objFS.FolderExists(strDestinationFolder) Then

' move the folder


objFS.MoveFolder strSourceFolder, strDestinationFolder
Else
' fail if the target folder was already in place
reporter.ReportEvent micFail, "Move Folder", "Unable to Move Folder as the
Target '" & strDestinationFolder & "' Already Exists"

End If

End If
' destroy the object
Set objFS = Nothing

End Function 'FolderMove


Copy Folder
Copy a local or network folder.
' =============================================================
' function: FolderCopy
' desc : Copys a folder and all of its files to a new path
' params : strSourceFolder - the folder to copy
' strDestinationFolder - the location to copy to
' returns : void
' =============================================================

Function FolderCopy(strSourceFolder, strDestinationFolder)


Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source folder exists
If Not objFS.FolderExists(strSourceFolder) Then
' fail if the source does not exist
reporter.ReportEvent micFail, "Copy Folder", "Source Folder '"& strSourceFolder
&"' Does Not Exist"
Else
' create the destination folder if it doesn't already exist
If Not objFS.FolderExists(strDestinationFolder) Then
objFS.CreateFolder(strDestinationFolder)
End If
' copy the folder
objFS.CopyFolder strSourceFolder, strDestinationFolder

End If
' destroy the object
Set objFS = Nothing

End Function 'FolderCopy


Folder Exists
Check to see if a local or network folder exists.
' =============================================================
' function: CheckFolderExists
' desc : Checks to see if a folder exists
' params : strFolder - full path of the folder to find
' returns : True if folder exists, False otherwise
' =============================================================
Function CheckFolderExists(strFile)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source file exists
If objFS.FolderExists(strFolder) Then
' file exists, return true
CheckFolderExists = True

Else

' file exists, return false


CheckFolderExists = False

End If
' destroy the object
Set objFS = Nothing

End Function 'CheckFolderExists


Read a Text File
Example of how to read a text file line-by-line.

' reading a file line by line

Const ForReading = 1

' create file system object


Set objFS = CreateObject("Scripting.FileSystemObject")

' first check that the file exists


If objFS.FileExists("c:\TextFile.txt") Then
' open the text file for reading
Set objFile = objFS.OpenTextFile("c:\TextFile.txt", ForReading, False)

' do until at end of file


Do Until objFile.AtEndOfStream

' store the value of the current line in the file


strLine = objFile.ReadLine

' show the line from the file


MsgBox strLine

Loop ' next line

' close the file


objFile.Close

Set objFile = Nothing

Else ' file doesn't exist

' report a failure


Reporter.ReportEvent micFail, "Read File", "File not found"

End if ' file exists

' destroy the objects


Set objFS = Nothing

Write to a File
Example of how to write text to a file.
' =============================================================
' function: AppendFile
' desc : Writes a line of text to a text file, text file is
' created if it doesn't already exist
' params : strFileName is the name of the file to write to
' strLine is the text to write to the file
' returns : void
' =============================================================
Function AppendFile(strFileName, strLine)

Dim objFS

Const ForAppending = 8

' create the file system object


Set objFS = CreateObject("Scripting.FileSystemObject")

' open/create the text file


Set objFile = objFS.OpenTextFile(strFilename, ForAppending, True)

' write the line


objFile.WriteLine strLine

' close the file


objFile.Close

End Function ' AppendFile

Get Temporary File Name


Generate a unique temporary file name.
' =============================================================
' function: GetTemporaryFileName
' desc : Generates a unique file name in the windows
' temporary folder
' params : none
' returns : A unique temporary file, including path
' =============================================================
Function GetTemporaryFileName
Const TemporaryFolder = 2
Dim objFS
Dim objTempFolder
' create the file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' get the path to the temporary folder
Set objTempFolder = objFS.GetSpecialFolder(TemporaryFolder)
' return the path plus a unique temporary file name
GetTemporaryFileName = objTempFolder.Path & "\" & objFS.GetTempName
' destroy the object
Set objFS = Nothing
Set objTempFolder = Nothing
End Function 'GetTemporaryFileName
Create Unique File Name
Create a unique file name.

' =============================================================
' function: UniqueFileName
' desc : Creates a unique file name
' params : strType - file extension
' returns : unique file name of specified type
' =============================================================
Function UniqueFileName(strType)

dim strReturn
' make sure there is a dot before the type
If left(strType,1) <> "." then strType = "." & strType

' create the file name using the date & time, and remove the / and : chars
strReturn = day(date) & month(date) & year(date) & hour(time) & minute(time)
& second(time) & strType

' return the file name


UniqueFileName = strReturn

End Function 'UniqueFileName

Compare Files
Compare the contents of two text files.

' =============================================================
' function: CompareFiles
' desc : Compares two text files
' params : strFile1 is the first file
' strFile2 is the second file
' returns : True if they are the same, False otherwise
' =============================================================
Function CompareFiles(strFile1, strFile2)

Dim objFS
Dim objFileA, objFileB
Dim strLineA, strLineB
dim intCompareResult

' create a file scripting object


Set objFS = CreateObject("Scripting.FileSystemObject")
' open each of the files for reading
Set objFileA = objFS.OpenTextFile(strFile1, 1)
Set objFileB = objFS.OpenTextFile(strFile2, 1)

' repeat the following until we hit the end of one of the files
Do While ((objFileA.AtEndOfStream <> True) OR (objFileB.AtEndOfStream <>
True))

' read the next line from both files


strLineA = objFileA.ReadLine
strLineB = objFileB.ReadLine

' perform a comparison on the line from each file


intCompareResult = StrComp(strLineA,strLineB,0)

' if the value of the comparison is not 0, lines are different


If (intCompareResult <> 0) Then

' found a difference in the files, so close them both


objFileA.Close
objFileB.Close

' destroy the object


Set objFS = Nothing

' return false


CompareFiles = False

' exit the function


Exit Function

End If ' if different


Loop ' until end of file

' close both files


objFileA.Close
objFileB.Close

' destroy the object


Set objFS = Nothing

' if function got this far, means files are the same, so return True
CompareFiles = True

End Function 'CompareFiles

Create Desktop Shortcut


Create a shortcut on the desktop.

' =============================================================
' function: CreateDesktopShortcut
' desc : Creates a shortcut on the desktop
' params : strTargetPath is the full path to the file you
' are creating the shortcut to, i.e. c:\doc\me.txt
' strLinkName is the name of the shortcut, as it
' appears on the desktop
' strDesc is the description to set within the shortcut
' returns : void
' =============================================================
Sub CreateDesktopShortcut(strTargetPath, strLinkName, strDesc)

Dim objShell, objShortCut


Dim strDesktopFolder

' ensure that the link name is valid


if Right(Lcase(strLinkName,4)) <> ".lnk" Then strLinkName = strLinkName &
".lnk"

' create a shell object


Set objShell = CreateObject("WScript.Shell")

' get the desktop folder


strDesktopFolder = objShell.SpecialFolders("AllUsersDesktop")

' create required shortcut object on the desktop


Set objShortCut = objShell.CreateShortcut(strDesktopFolder & "\" &
strLinkName)

' set the path within the shortcut


objShortCut.TargetPath = strTargetPath

' set the description


objShortCut.Description = strDesc

' save the shortcut


objShortCut.Save

End Sub ' CreateDesktopShortcut

Read From Excel File


Read all the data from an Excel file.

' =============================================================
' function: ReadXLS
' desc : Reads a sheet from an XLS file and stores the content
' in a multi-dimensional array
' params : strFileName is XLS file to read, including path
' strSheetName is the name of the sheet to read, i.e "Sheet1"
' returns : Multi-dimensional array containing all data from
' the XLS
' =============================================================
Function ReadXLS(strFileName,strSheetName)

Dim strData()
Dim objFS, objExcel, objSheet, objRange
Dim intTotalRow, intTotalCol
Dim intRow, intCol

' create the file system object


Set objFS = CreateObject("Scripting.FileSystemObject")

' ensure that the xls file exists


If Not objFS.FileExists(strFileName) Then

' issue a fail if the file wasn't found


Reporter.ReportEvent micFail, "Read XLS", "Unable to read XLS file, file not
found: " & strFileName
' file wasn't found, so exit the function
Exit Function

End If ' file exists

' create the excel object


Set objExcel = CreateObject("Excel.Application")

' open the file


objExcel.Workbooks.open strFileName

' select the worksheet


Set objSheet = objExcel.ActiveWorkbook.Worksheets(strSheetName)
' select the used range
Set objRange = objSheet.UsedRange

' count the number of rows


intTotalRow=CInt(Split(objRange.Address, "$")(4)) - 1

' count the number of columns


intTotalCol= objSheet.Range("A1").CurrentRegion.Columns.Count

' redimension the multi-dimensional array to accomodate each row and column
ReDim strData(intTotalRow, intTotalCol)

' for each row


For intRow = 0 to intTotalRow - 1

' for each column


For intCol =0 to intTotalCol - 1

' store the data from the cell in the array


strData(intRow, intcol) = Trim(objSheet.Cells(intRow + 2,intcol + 1).Value)

Next ' column

Next ' row

' close the excel object


objExcel.DisplayAlerts = False
objExcel.Quit

' destroy the other objects


Set objFS = Nothing
Set objExcel = Nothing
Set objSheet = Nothing

' return the array containing the data


ReadXLS = strData

End Function ' ReadXLS

Get Child Obects


Find all checkboxes on a webpage.
Here's a basic example that will find and tick all of the checkboxes on the QTP
Helper login screen.
Dim objDescription
Dim objCheckBoxes
Dim iCount

' create description objects used to locate check boxes


Set objDescription = Description.Create()

' set the object properties so it looks only for web check boxes
objDescription("micclass").Value = "WebCheckBox"

' check that the user isn't already logged in


If Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebButton("Name:=Logout").Exist(1) Then

' click logout


Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebButton("Name:=Logout").Click

End If

' get the check boxes from the page


Set objCheckBoxes = Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").ChildObjects(objDescription)

' for each check box found


For iCount = 0 to objCheckBoxes.Count - 1

' tick the check box


Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebCheckBox(objCheckBoxes(iCount)).Set "ON"

Next

Get Disk Information


Get information about one of your disk drives.

Dim intSectors, intBytes, intFreeC, intTotalC, intTotal ,intFreeb

' include this windows api


extern.Declare micLong, "GetDiskFreeSpace", "kernel32.dll",
"GetDiskFreeSpaceA", micString+micByref, micLong+micByref,
micLong+micByref,micLong+micByref,micLong+micByref

' set these values


intSectors = 255
intBytes = 255
intFreeC = 255
intTotalC = 255

' calculate the disk space, using C: in this example


intSpaceAvailable = extern.GetDiskFreeSpace("c:\", intSectors, intBytes,
intFreeC, intTotalC)
' calculate the totals
intTotal = intTotalC * intSectors * intBytes
intFreeb = intFreeC * intSectors * intBytes

' show the outputs


msgBox intSectors
msgBox intBytes
msgBox intFreeC
msgBox intTotalC
msgbox intTotal
msgBox intFreeb
Get IP Address
Get your machines IP address.

' =============================================================
' function: GetIPAddress
' desc : Returns the IP address of the PC
' params : Void
' returns : IP Address
' =============================================================
Function GetIPAddress()

' get the ip addresses


Set IPConfigSet = GetObject("winmgmts:
{impersonationLevel=impersonate}").ExecQuery _
("select IPAddress from Win32_NetworkAdapterConfiguration where
IPEnabled=TRUE")

' for each item in the collection


For Each IPConfig in IPConfigSet

' if the item isn't empty


If Not IsNull(IPConfig.IPAddress) Then
' loop through the addresses
For i = LBound(IPConfig.IPAddress) to UBound(IPConfig.IPAddress)

' set the return alue


ipAddr = IPConfig.IPAddress(i)

Next

End If

Next

' destroy the object


Set IPConfigSet = Nothing

' return the ip


GetIPAddress = ipAddr

End Function ' GetIPAddress

Get System Information


Get system information like User Name and Computer Name.

Dim objNet

' create a network object


Set objNet = CreateObject("WScript.NetWork")

' show the user name


MsgBox "User Name: " & objNet.UserName

' show the computer name


MsgBox "Computer Name: " & objNet.ComputerName

' show the domain name


MsgBox "Domain Name: " & objNet.UserDomain

' destroy the object


Set objNet = Nothing

Get System Variable Value


Get a value from a Windows System Variable.

' for example to get the oracle home path


MsgBox GetSystemVariable("ORACLE_HOME")

' =============================================================
' function: GetSystemVariable
' desc : Get the value of a system variable
' params : strSysVar is the variable name
' returns : Content of variable name
' =============================================================
Function GetSystemVariable(strSysVar)

Dim objWshShell, objWshProcessEnv

' create the shell object


Set objWshShell = CreateObject("WScript.Shell")
Set objWshProcessEnv = objWshShell.Environment("Process")

' return the system variable content


GetSystemVariable = objWshProcessEnv(strSysVar)

End Function ' GetSystemVariable


Get Temporary File Name
Generate a unique temporary file name.
' =============================================================
' function: GetTemporaryFileName
' desc : Generates a unique file name in the windows
' temporary folder
' params : none
' returns : A unique temporary file, including path
' =============================================================
Function GetTemporaryFileName
Const TemporaryFolder = 2
Dim objFS
Dim objTempFolder
' create the file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' get the path to the temporary folder
Set objTempFolder = objFS.GetSpecialFolder(TemporaryFolder)
' return the path plus a unique temporary file name
GetTemporaryFileName = objTempFolder.Path & "\" & objFS.GetTempName
' destroy the object
Set objFS = Nothing
Set objTempFolder = Nothing
End Function 'GetTemporaryFileName
Import Data Sheet
Import a data sheet into your test at runtime.
' =============================================================
' function: ImportDataSheet
' desc : Imports a single data sheet
' params : strFile - full path of the xls file with the sheet
' strSource - name of the sheet on the xls
' strTarget - name of the sheet to import it to
' returns : void
' =============================================================
Function ImportDataSheet(strFile, strSource, strTarget)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source file exists
If objFS.FileExists(strFile) Then
' ensure that our target sheet exists
DataTable.AddSheet strTarget
' import the sheet
DataTable.Importsheet strFile, strSource, strTarget
Else
' fail if the xls was not found
Reporter.ReportEvent micFail, "Import Data Table", "Unable to Import Data
Table From '" & strFile & "', File Does Not Exist"
End If
' destroy the object
Set objFS = Nothing
End Function 'ImportDataSheet

Import Data Table


Import a data table into your test at runtime.
' =============================================================
' function: ImportDataTable
' desc : Imports a data table
' params : strFile - full path of the xls file to import
' returns : void
' =============================================================
Function ImportDataTable(strFile)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source file exists
If objFS.FileExists(strFile) Then
' import the data table
DataTable.Import strFile
Else
' fail if the xls was not found
Reporter.ReportEvent micFail, "Import Data Table", "Unable to Import Data
Table From '" & strFile & "', File Does Not Exist"
End If
' destroy the object
Set objFS = Nothing
End Function 'ImportDataTable

Sending Key Presses (SendKeys)


Examples of how to simulate key presses.
Dim objShell
' Create the shell object
Set objShell = CreateObject ("WSCript.shell")
' Various key press examples
objShell.SendKeys "Hello" ' Hello
objShell.SendKeys "{F4}" ' F4
objShell.SendKeys "^{F4}" ' CTRL-F4
objShell.SendKeys "+{F4}" ' SHIFT-F4
objShell.SendKeys "%{F4}" ' ALT-F4
' Destroy the object
Set objShell = Nothing

Locate Method (Checking text within text)


Using Locate to determine if specific text exists within a string.

MsgBox LocateText("www.QTPHelper.com", "QTP")


MsgBox LocateText("www.QTPHelper.com", "QTP.*.com")
' =============================================================
' function: LocateText
' desc : Uses a regular expression to locate text within a string
' params : strString is the string to perform the search on
' strPattern is the regular expression
' returns : True if the pattern was found, False otherwise
' =============================================================
Function LocateText(strString, strPattern)

Dim objRegEx

' create the regular expression


Set objRegEx = New RegExp

' set the pattern


objRegEx.Pattern = strPattern

' ignore the casing


objRegEx.IgnoreCase = True

' perform the search


LocateText = objRegEx.Test(strString)

' destroy the object


Set objRegEx = Nothing

End Function ' LocateText

Write to a Log File


Write information to a log file.

' =============================================================
' function: WriteLog
' desc : Writes a message to a log file. File is created
' inside a Log folder of the current directory
' params : strCode is a code to prefix the message with
' strMessage is the message to add to the file
' returns : void
' =============================================================
Function WriteLog(strCode, strMessage)

Dim objFS
Dim objFile
Dim objFolder
Dim strFileName

' create a file system object


Set objFS = CreateObject("Scripting.FileSystemObject")

' is there a log folder in the directory that we are currently working
If Not objFS.FolderExists(objFS.GetAbsolutePathName(".") & "\log") Then

' if there is no log folder, create one


Set objFolder = objFS.CreateFolder(objFS.GetAbsolutePathName(".") & "\log")

End If ' folder exists

' set a name for the log file using year, month and day values
strFileName = objFS.GetAbsolutePathName(".") & "\log\" & year(date) &
month(date) & day(date) & ".log"

' create the log file


Set objFile = objFS.OpenTextFile(strFileName, 8, True)

' in case of any issues writing the file


On Error Resume Next

' write the log entry, include a carriage return


objFile.Write Date & ", " & Time & ", " & strCode & ", " & strMessage & vbcrlf

' disable the on error statement


On Error GoTo 0

' close the log file


objFile.Close

' destrory the object


Set objFS = Nothing

End Function ' WriteLog

Loop Basics
Some basic information about various loop types.
' Loops allow you to run a group of statements repeatidly.
'
' There are four types of loop available, all very easy to
' use and understand. This code sample will explain how
' to use each type of loop.
'

' Do...Loop

' The Do...Loop will run a block of statements repeatidly


' while a condition is True, or until a condition becomes True

' Check these two examples of Do...While, there is one major difference
' between them. In Example A the cose will check the value of intCounter
' before it enters the loop, but in Example B the code will enter the
' loop regardless of the value of intCounter.

' Example A
intCounter = 0
Do While intCounter < 5
intCounter = intCounter + 1
MsgBox intCounter
Loop

' Example B
intCounter = 0
Do
intCounter = intCounter + 1
MsgBox intCounter
Loop While intCounter <5

' Here is the same examples using the Do...Until


' Example A
intCounter = 0
Do Until intCounter = 6
intCounter = intCounter + 1
MsgBox intCounter
Loop

' Example B
intCounter = 0
Do
intCounter = intCounter + 1
MsgBox intCounter
Loop Until intCounter = 6
' For...Next
' For...Next Loops will execute a series of statements until a specific counter
value
' is reached.
For iCounter = 1 To 5
MsgBox iCounter
Next

' You can add a Step keyword to define how much the counter should increase
with each
' itteration of the loop
For iCounter = 1 To 10 Step 2
MsgBox iCounter
Next

' The Step keyword can also be used to itterate backwards


For iCounter = 5 to 1 Step -1
MsgBox iCounter
Next

' For...Each

' Another variation on the For...Next loop is the For...Each loop. The For...Each
' loop is used to execute a series of statements for each object in a collection,
' i.e. each element of an array. For example...
Dim strPeopleList
Dim strPerson
strPeopleList = Array("Alan", "Bob", "Craig", "Dan")
For Each strPerson in strPeopleList
MsgBox strPerson
Next
' While...Wend Loops
'
' This type of loop will execute a series of statements as long as
' a given condition is true.
' Note: It's advisable to avoid using this type of loop, you should
' us the Do...Loop instead
' Here's an example anyway...
iCounter = 0
While iCounter < 5
iCounter = iCounter + 1
Msgbox iCounter
Wend
Minimize QTP
Minimize the main QTP window.

' =============================================================
' function: MinimizeQTP
' desc : Minimize QTP window
' params : None
' returns : void
' =============================================================
Function MinimizeQTP()

dim objQTP

' create a qtp object


Set objQTP = getObject("","QuickTest.Application")

' set the window state to minimized


objQTP.WindowState = "Minimized"

' destroy the object


Set objQTP = Nothing
End Function 'MinimizeQTP

Move File
Move a file from one location to another.
' =============================================================
' function: FileMove
' desc : Moves a file from one location to another
' params : strFile - full path to the source file
' strTarget - the folder to move the file to
' returns : void
' =============================================================
Function FileMove(strFile, strTarget)

Dim objFS

' create a file system object


Set objFS = CreateObject("Scripting.FileSystemObject")

' check that the source file exists


If Not objFS.FileExists(strFile) Then

' fail if the source does not exist


reporter.ReportEvent micFail, "Move File", "Unable to Move the File '"& strFile
&"', It Does Not Exist"

Else

' create the destination folder if it doesn't already exist


If Not objFS.FolderExists(strTarget) Then

objFS.CreateFolder(strTarget)
End If

' move the file


objFS.MoveFile strFile, strTarget

End If

' destroy the object


Set objFS = Nothing

End Function 'FileMove


Move Folder
Move a local or network folder.
' =============================================================
' function: FolderMove
' desc : Moves a folder and all of its files to a new path
' params : strSourceFolder - the folder to copy
' strDestinationFolder - the location to copy to
' returns : void
' =============================================================
Function FolderMove(strSourceFolder, strDestinationFolder)
Dim objFS
' create a file system object
Set objFS = CreateObject("Scripting.FileSystemObject")
' check that the source folder exists
If Not objFS.FolderExists(strSourceFolder) Then
' fail if the source does not exist
reporter.ReportEvent micFail, "Move Folder", "Source Folder '"& strSourceFolder
&"' Does Not Exist"
Else
' check that the destination folder doesn't already exist
If Not objFS.FolderExists(strDestinationFolder) Then
' move the folder
objFS.MoveFolder strSourceFolder, strDestinationFolder
Else
' fail if the target folder was already in place
reporter.ReportEvent micFail, "Move Folder", "Unable to Move Folder as the
Target '" & strDestinationFolder & "' Already Exists"

End If

End If
' destroy the object
Set objFS = Nothing

End Function 'FolderMove


Displaying Dialog Boxes
How to display and use various types of dialog box.
' display a basic message box
MsgBox "Hi, this is a message box", vbOkOnly, "Message Title"

' prompt the user with a question


strAnswer = InputBox("Hi, how are you today?","Question")
' show the user what they just typed
MsgBox "You are - " & strAnswer

' ask the user to select an option


strAnswer = MsgBox("Do you want to proceed?", vbYesNo, "Question")
' show the user what they just selected
If strAnswer = vbNo Then
MsgBox "You selected No"
Else
MsgBox "You selected Yes"
End If
Note: Here are the various message types you can play with...
vbOKOnly
vbOKCancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
vbRetryCancel
vbCritical
vbQuestion
vbExclamation
vbInformation

Capture Screenshot
Capture and save a PNG of the entire screen.
' =============================================================
' function: ScreenShot
' desc : Creates a png of the entire screen
' params : n/a
' returns : name of saved png
' =============================================================
Function ScreenShot()
dim strPNG
dim objDesktop
' set a unique file name using the date/time
strPNG = "C:\Screenshot_" & day(date) & month(date) & year(date) & _
& hour(time) & minute(time) & second(time) & ".png"
' desktop object
Set objDesktop = Desktop
' capture a png of the desktop
obj.CaptureBitmap strPNG, true
' return the file name
ScreenShot = strPNG
' destroy the object
Set objDesktop = Nothing
End Function 'ScreenShot

Override Existing Object Method


Override an existing object method.
' override the Set method with SetWithDebug
RegisterUserFunc "WebEdit", "Set", "SetWithDebug"

' =============================================================
' function : SetWithDebug
' desc : Sets the value of an edit box with additional logging
' =============================================================
Function SetWithDebug(objEdit, strValue)

' your additional logging here


' set the text
SetWithDebug = objEdit.Set(strValue)

End Function

Registering a Procedure
Register a procedure with an object class.

' add GetItemsCount as a method of the WebList class


RegisterUserFunc "WebList", "GetItemsCount", "GetItemsCountFunction"

' =============================================================
' function : GetItemsCountFunction
' desc : Returns the number of items from a weblist
' =============================================================
Function GetItemsCountFunction(objWebList)

If (objWebList = Nothing) Then


GetItemsCount = 0
Else
GetItemsCount = objWebList.GetROProperty("Items Count")
End If

End Function

Using Programmatic Descriptions


Using Programmatic Descriptions to interact with a web page.
This example will illustrate how to use programmatic descriptions to interact
with a web page, www.QTPHelper.com to be more exact...
Note that I've used a simple regular expression in the Browser and Page
description, just in case the titles change in the future.
' click the Home link
Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").Link("Text:=Home").Click

' check that the user isn't already logged in


If Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebButton("Name:=Logout").Exist(1) Then

' click logout


Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebButton("Name:=Logout").Click

End If ' user logged in

' set the username


Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebEdit("Name:=username").Set "User"

' set the password


Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebEdit("Name:=passwd").Set "Password"

' tick the remember-me tickbox


Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebCheckBox("Name:=remember").Set "ON"

Query a Database
Simple example of how to query an access database.
dim objDB
dim objRS
dim intCounter
' create a database and recordset objects
Set objDB = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.RecordSet")
' configure the connection
objDB.Provider="Microsoft.Jet.OLEDB.4.0"
objDB.Open "c:\MyTestDatabase.mdb"
' count the number of records in the employee table
objRS.Open "SELECT COUNT(*) from Employee" , objDB
Msgbox "There are " & objRS.Fields(0).Value & " records in the employee table."
' destroy the objects
Set objDB = Nothing
Set objRS = Nothing
Read a Text File
Example of how to read a text file line-by-line.

' reading a file line by line


Const ForReading = 1

' create file system object


Set objFS = CreateObject("Scripting.FileSystemObject")

' first check that the file exists


If objFS.FileExists("c:\TextFile.txt") Then

' open the text file for reading


Set objFile = objFS.OpenTextFile("c:\TextFile.txt", ForReading, False)

' do until at end of file


Do Until objFile.AtEndOfStream

' store the value of the current line in the file


strLine = objFile.ReadLine

' show the line from the file


MsgBox strLine

Loop ' next line

' close the file


objFile.Close

Set objFile = Nothing

Else ' file doesn't exist

' report a failure


Reporter.ReportEvent micFail, "Read File", "File not found"
End if ' file exists

' destroy the objects


Set objFS = Nothing

Read From Excel File


Read all the data from an Excel file.

' =============================================================
' function: ReadXLS
' desc : Reads a sheet from an XLS file and stores the content
' in a multi-dimensional array
' params : strFileName is XLS file to read, including path
' strSheetName is the name of the sheet to read, i.e "Sheet1"
' returns : Multi-dimensional array containing all data from
' the XLS
' =============================================================
Function ReadXLS(strFileName,strSheetName)

Dim strData()
Dim objFS, objExcel, objSheet, objRange
Dim intTotalRow, intTotalCol
Dim intRow, intCol

' create the file system object


Set objFS = CreateObject("Scripting.FileSystemObject")

' ensure that the xls file exists


If Not objFS.FileExists(strFileName) Then

' issue a fail if the file wasn't found


Reporter.ReportEvent micFail, "Read XLS", "Unable to read XLS file, file not
found: " & strFileName
' file wasn't found, so exit the function
Exit Function

End If ' file exists

' create the excel object


Set objExcel = CreateObject("Excel.Application")

' open the file


objExcel.Workbooks.open strFileName

' select the worksheet


Set objSheet = objExcel.ActiveWorkbook.Worksheets(strSheetName)

' select the used range


Set objRange = objSheet.UsedRange

' count the number of rows


intTotalRow=CInt(Split(objRange.Address, "$")(4)) - 1

' count the number of columns


intTotalCol= objSheet.Range("A1").CurrentRegion.Columns.Count

' redimension the multi-dimensional array to accomodate each row and column
ReDim strData(intTotalRow, intTotalCol)

' for each row


For intRow = 0 to intTotalRow - 1

' for each column


For intCol =0 to intTotalCol - 1
' store the data from the cell in the array
strData(intRow, intcol) = Trim(objSheet.Cells(intRow + 2,intcol + 1).Value)

Next ' column

Next ' row

' close the excel object


objExcel.DisplayAlerts = False
objExcel.Quit

' destroy the other objects


Set objFS = Nothing
Set objExcel = Nothing
Set objSheet = Nothing

' return the array containing the data


ReadXLS = strData

End Function ' ReadXLS

Read from the Registry


Read a value from a key in the registry.

' =============================================================
' function : RegistryRead
' desc : Read a value from the registry
' params : strRoot is the root key, i.e. "HKLM", "HKCU"
' strPath is the path to read, i.e.
' "Software\Test\Automation"
' returns : Value from the registry key
' =============================================================
Function RegistryRead(strRoot, strPath)
' create the shell object
Set objShell = CreateObject("WScript.Shell")

' read the key


strValue = objShell.RegRead(strRoot & "\" & strPath)

' return the value


RegistryRead = strValue

' destroy the object


Set objShell = Nothing

End Function 'RegistryRead

Registering a Procedure
Register a procedure with an object class.

' add GetItemsCount as a method of the WebList class


RegisterUserFunc "WebList", "GetItemsCount", "GetItemsCountFunction"

' =============================================================
' function : GetItemsCountFunction
' desc : Returns the number of items from a weblist
' =============================================================
Function GetItemsCountFunction(objWebList)

If (objWebList = Nothing) Then


GetItemsCount = 0
Else
GetItemsCount = objWebList.GetROProperty("Items Count")
End If
End Function

Replace Method
Using the replace method to find and replace text in a string.

MsgBox ReplaceText("Automating with QTP is rubbish.", "rubbish.", "great!")

MsgBox ReplaceText("QTP is a great automation tool but I can't use


it","but.*","!")

' =============================================================
' function: ReplaceText
' desc : Uses a regular expression to replace text within a string
' params : strString is the string to perform the replacement on
' strPattern is the regular expression
' strReplacement is the replacement string
' returns : The finished string
' =============================================================
Function ReplaceText(strString, strPattern, strReplacement)

Dim objRegEx

' create the regular expression


Set objRegEx = New RegExp

' set the pattern


objRegEx.Pattern = strPattern

' ignore the casing


objRegEx.IgnoreCase = True

' make the replacement


ReplaceText = objRegEx.Replace(strString, strReplacement)
' destroy the object
Set objRegEx = Nothing

End Function ' ReplaceText

Write to the Registry


Write a value to the Registry.

' =============================================================
' Sub : RegistryWrite
' desc : Writes a key value to the registry
' params : strRoot is the root key, i.e. "HKLM", "HKCU"
' strPath is the path to create, i.e.
' "Software\Test\Automation"
' strValue is the value to write in the key
' returns : void
' =============================================================
Function RegistryWrite(strRoot, strPath, strValue)

' create the shell object


Set objShell = CreateObject("WScript.Shell")

' write the key


objShell.RegWrite strRoot & "\" & strPath, strValue, "REG_SZ"

' destroy the object


Set objShell = Nothing

End Function 'RegistryWrite


Read from the Registry
Read a value from a key in the registry.

' =============================================================
' function : RegistryRead
' desc : Read a value from the registry
' params : strRoot is the root key, i.e. "HKLM", "HKCU"
' strPath is the path to read, i.e.
' "Software\Test\Automation"
' returns : Value from the registry key
' =============================================================
Function RegistryRead(strRoot, strPath)

' create the shell object


Set objShell = CreateObject("WScript.Shell")

' read the key


strValue = objShell.RegRead(strRoot & "\" & strPath)

' return the value


RegistryRead = strValue

' destroy the object


Set objShell = Nothing

End Function 'RegistryRead

Delete from the Registry


Delete a key from the registry.

' =============================================================
' function: RegistryDelete
' desc : Deletes a key from the registry
' params : strRoot is the root key, i.e. "HKLM", "HKCU"
' strPath is the path to delete, i.e.
' "Software\Test\Automation"
' returns : void
' =============================================================
Function RegistryDelete(strRoot, strPath)

' create the shell object


Set objShell = CreateObject("WScript.Shell")

' delete the key


strValue = objShell.RegDelete(strRoot & "\" & strPath)

' destroy the object


Set objShell = Nothing

End Function 'RegistryDelete

Custom Report Entry


Creating a customised entry in the results.

' Example usage


CustomReportEntry micFail, "Custom Report Example", "
This is a custom report entry!
"

' =============================================================
' function: CustomReportEntry
' desc : Creates a customized entry in the result file, you
' can use standard HTML tags in the message.
' params : strStatus is the result, micPass, micFail etc
' strStepName is the name of the step
' strMessage is the failure message, this can contain
' html tags
' returns : Void
' =============================================================
Function CustomReportEntry(strStatus, strStepName, strMessage)

' create a dictionary object


Set objDict = CreateObject("Scripting.Dictionary")

' set the object properties


objDict("Status") = strStatus
objDict("PlainTextNodeName") = strStepName
objDict("StepHtmlInfo") = strMessage
objDict("DllIconIndex") = 206
objDict("DllIconSelIndex") = 206
objDict("DllPAth") = "C:\Program Files\Mercury Interactive\QuickTest
Professional\bin\ContextManager.dll"

' report the custom entry


Reporter.LogEvent "User", objDict, Reporter.GetContext

End Function 'CustomReportEntry

Write to a Log File


Write information to a log file.

' =============================================================
' function: WriteLog
' desc : Writes a message to a log file. File is created
' inside a Log folder of the current directory
' params : strCode is a code to prefix the message with
' strMessage is the message to add to the file
' returns : void
' =============================================================
Function WriteLog(strCode, strMessage)

Dim objFS
Dim objFile
Dim objFolder
Dim strFileName

' create a file system object


Set objFS = CreateObject("Scripting.FileSystemObject")

' is there a log folder in the directory that we are currently working
If Not objFS.FolderExists(objFS.GetAbsolutePathName(".") & "\log") Then

' if there is no log folder, create one


Set objFolder = objFS.CreateFolder(objFS.GetAbsolutePathName(".") & "\log")

End If ' folder exists

' set a name for the log file using year, month and day values
strFileName = objFS.GetAbsolutePathName(".") & "\log\" & year(date) &
month(date) & day(date) & ".log"

' create the log file


Set objFile = objFS.OpenTextFile(strFileName, 8, True)

' in case of any issues writing the file


On Error Resume Next

' write the log entry, include a carriage return


objFile.Write Date & ", " & Time & ", " & strCode & ", " & strMessage & vbcrlf
' disable the on error statement
On Error GoTo 0

' close the log file


objFile.Close

' destrory the object


Set objFS = Nothing

End Function ' WriteLog


Check Service is Running
Check to see if a windows service is running.

' =============================================================
' function: CheckIfServiceIsRunning
' desc : Check to see if a service is running
' params : strServiceName is the name of the service
' returns : True if running, False otherwise
' =============================================================
Function CheckIfServiceIsRunning(strServiceName)

Dim objShell, blnStatus

' create the shell object


Set objShell= CreateObject("Shell.Application")
blnStatus = objShell.IsServiceRunning(strServiceName)

' return status of service


CheckIfServiceIsRunning = blnStatus

End Function 'CheckIfServiceIsRunning


Basic String Manipulation
Basic functions for string manipulation.

Function: String
Accepts a number and a character. Returns a string created with the character
that is repeated the given number of times.

' example
MsgBox String(5,"A")

Function: Len
Returns the number of characters from a given string.

' example
strMyName = "Joe Bloggs"
MsgBox "The Name '" & strMyName & "' is " & Len(strMyName) & " characters
long"

Function: Instr
Accepts two strings and returns True if the second string is contained within
the first.

' example
If Instr("Hello, welcome to www.QTPHelper.com!", "QTP")>0 Then MsgBox
"Found"

Function: Left
Returns the given number of left-most characters from a string
' example
MsgBox Left("Joe Bloggs", 3)

Function: Right
Returns the given number of right-most characters from a string

' example
MsgBoxRight("Joe Bloggs", 6)

Function: LCase
Returns a given string in lower-case

' example
MsgBox LCase("JoE BloGGs")

Function: UCase
Returns a given string in upper-case

' example
MsgBox UCase("joe bloggs")
Get System Information
Get system information like User Name and Computer Name.

Dim objNet

' create a network object


Set objNet = CreateObject("WScript.NetWork")

' show the user name


MsgBox "User Name: " & objNet.UserName
' show the computer name
MsgBox "Computer Name: " & objNet.ComputerName

' show the domain name


MsgBox "Domain Name: " & objNet.UserDomain

' destroy the object


Set objNet = Nothing

Get Disk Information


Get information about one of your disk drives.

Dim intSectors, intBytes, intFreeC, intTotalC, intTotal ,intFreeb

' include this windows api


extern.Declare micLong, "GetDiskFreeSpace", "kernel32.dll",
"GetDiskFreeSpaceA", micString+micByref, micLong+micByref,
micLong+micByref,micLong+micByref,micLong+micByref

' set these values


intSectors = 255
intBytes = 255
intFreeC = 255
intTotalC = 255

' calculate the disk space, using C: in this example


intSpaceAvailable = extern.GetDiskFreeSpace("c:\", intSectors, intBytes,
intFreeC, intTotalC)

' calculate the totals


intTotal = intTotalC * intSectors * intBytes
intFreeb = intFreeC * intSectors * intBytes

' show the outputs


msgBox intSectors
msgBox intBytes
msgBox intFreeC
msgBox intTotalC
msgbox intTotal
msgBox intFreeb

Get System Variable Value


Get a value from a Windows System Variable.

' for example to get the oracle home path


MsgBox GetSystemVariable("ORACLE_HOME")

' =============================================================
' function: GetSystemVariable
' desc : Get the value of a system variable
' params : strSysVar is the variable name
' returns : Content of variable name
' =============================================================
Function GetSystemVariable(strSysVar)

Dim objWshShell, objWshProcessEnv

' create the shell object


Set objWshShell = CreateObject("WScript.Shell")
Set objWshProcessEnv = objWshShell.Environment("Process")

' return the system variable content


GetSystemVariable = objWshProcessEnv(strSysVar)
End Function ' GetSystemVariable

Using Description Objects


Using Description Objects to interact with a web page.
This example will illustrate how to use description objects to interact with a
web page, www.QTPHelper.com to be more exact...
Note that for the Browser and Page I've used programmatic descriptions, but
for the buttons, edits and check-boxes I've used Description Objects. Also take
note of the regular expression in the Browser and Page description, just in case
the titles change in the future.
You can add more properties to your description objects if you need to, i.e. if
your web page has numerous objects of the same type with similar property
values.
Dim objLogout
Dim objUser
Dim objPass
Dim objRemember

' create description objects for each item we are dealing with
Set objLogout = Description.Create()
Set objUser = Description.Create()
Set objPass = Description.Create()
Set objRemember = Description.Create()

' define the properties of each item


objLogout("Name").Value = "Logout"
objUser("Name").Value = "username"
objPass("Name").Value = "passwd"
objRemember("Name").Value = "remember"

' check that the user isn't already logged in


If Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebButton(objLogout).Exist(1) Then
' click logout
Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebButton(objLogout).Click

End If

' set the user name


Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebEdit(objUser).Set "User"

' set the password


Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebEdit(objPass).Set "Password"

' tick the remember-me tickbox


Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebCheckBox(objRemember).Set "ON"

Using Programmatic Descriptions


Using Programmatic Descriptions to interact with a web page.
This example will illustrate how to use programmatic descriptions to interact
with a web page, www.QTPHelper.com to be more exact...
Note that I've used a simple regular expression in the Browser and Page
description, just in case the titles change in the future.
' click the Home link
Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").Link("Text:=Home").Click

' check that the user isn't already logged in


If Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebButton("Name:=Logout").Exist(1) Then
' click logout
Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebButton("Name:=Logout").Click

End If ' user logged in

' set the username


Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebEdit("Name:=username").Set "User"

' set the password


Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebEdit("Name:=passwd").Set "Password"

' tick the remember-me tickbox


Browser("Title:=QTP Helper.*").Page("Title:=QTP
Helper.*").WebCheckBox("Name:=remember").Set "ON"

What is QuickTest Automation Object Model?


It's a way to write scripts so as to automate your QuickTest operations.

Some places where we can use AOM


This is a small list of places (but not limited to) where we can use AOM. Thumb
Rule - Use it at any place where you find yourself doing repetitive tasks while
using QTP.
• AOM can come handy when you have a large no of scripts to be uploaded to
QC. A simple script can save you hours of manual work!
• Use AOM to initialize QTP options and settings like add-ins etc.
• You can use AOM to call QTP from other application: For ex: You can write a
macro for calling QTP from excel.
Caution: AOM should be used outside of QTP and not within the script (during
playback). Though there is no harm using it inside but some of the AOM
statements might fail.

How to write AOM scripts?


You need to understand that the very root of QT AOM is Application Object.
Every automation script begins with the creation of the QuickTest "Application"
object. Creating this object does not start QuickTest. It simply provides an
object from which you can access all other objects, methods and properties of
the QuickTest automation object model.You can create only one instance of
the Application object. You do not need to recreate the QuickTest Application
object even if you start and exit QuickTest several times during your script.
Once you have defined this object you can then successfully work and perform
operations on other objects given in Quick Test Pro > Documentation >
QuickTest Automation Reference.
For ex: Let us connect to TD QC using AOM and open a script "qtp_demo"
Dim qt_obj 'Define a Quick Test object
qt_obj = CreateObject("Quick Test.Application") ' Instantiate a QT Object. It
does not start QTP.
qt_obj.launch ' Launch QT
qt_obj.visible ' Make QT visible
qt_obj.TDConnection.Connect "http://tdserver/tdbin", _ 'Referencing
TDConnection Object
"TEST_DOMAIN", "TEST_Project", "Ankur", "Testing", False ' Connect to Quality
Center
If qt_obj.TDConnection.IsConnected Then ' If connection is successful
qt_obj.Open "[QualityCenter] Subject\tests\qtp_demo", False ' Open the test
Else
MsgBox "Cannot connect to Quality Center" ' If connection is not successful,
display an error message.
End If
To quickly generate an AOM script with the current QTP settings. Use the
Properties tab of the Test Settings dialog box (File > Settings) OR the General
tab of the Options dialog box (Tools > Options) OR the Object Identification
dialog box (Tools > Object Identification). Each contain a "Generate Script"
button. Clicking this button generates a automation script file (.vbs) containing
the current settings from the corresponding dialog box.
You can run the generated script as is to open QuickTest with the exact
configuration of the QuickTest application that generated the script, or you can
copy and paste selected lines from the generated files into your own
automation script.
Reference: Quick Test Pro > Documentation > QuickTest Automation Reference.

What is QuickTest Automation Object Model?


It's a way to write scripts so as to automate your QuickTest operations.

Some places where we can use AOM


This is a small list of places (but not limited to) where we can use AOM. Thumb
Rule - Use it at any place where you find yourself doing repetitive tasks while
using QTP.
• AOM can come handy when you have a large no of scripts to be uploaded to
QC. A simple script can save you hours of manual work!
• Use AOM to initialize QTP options and settings like add-ins etc.
• You can use AOM to call QTP from other application: For ex: You can write a
macro for calling QTP from excel.
Caution: AOM should be used outside of QTP and not within the script (during
playback). Though there is no harm using it inside but some of the AOM
statements might fail.

How to write AOM scripts?


You need to understand that the very root of QT AOM is Application Object.
Every automation script begins with the creation of the QuickTest "Application"
object. Creating this object does not start QuickTest. It simply provides an
object from which you can access all other objects, methods and properties of
the QuickTest automation object model.You can create only one instance of
the Application object. You do not need to recreate the QuickTest Application
object even if you start and exit QuickTest several times during your script.
Once you have defined this object you can then successfully work and perform
operations on other objects given in Quick Test Pro > Documentation >
QuickTest Automation Reference.
For ex: Let us connect to TD QC using AOM and open a script "qtp_demo"
Dim qt_obj 'Define a Quick Test object
qt_obj = CreateObject("Quick Test.Application") ' Instantiate a QT Object. It
does not start QTP.
qt_obj.launch ' Launch QT
qt_obj.visible ' Make QT visible
qt_obj.TDConnection.Connect "http://tdserver/tdbin", _ 'Referencing
TDConnection Object
"TEST_DOMAIN", "TEST_Project", "Ankur", "Testing", False ' Connect to Quality
Center
If qt_obj.TDConnection.IsConnected Then ' If connection is successful
qt_obj.Open "[QualityCenter] Subject\tests\qtp_demo", False ' Open the test
Else
MsgBox "Cannot connect to Quality Center" ' If connection is not successful,
display an error message.
End If
To quickly generate an AOM script with the current QTP settings. Use the
Properties tab of the Test Settings dialog box (File > Settings) OR the General
tab of the Options dialog box (Tools > Options) OR the Object Identification
dialog box (Tools > Object Identification). Each contain a "Generate Script"
button. Clicking this button generates a automation script file (.vbs) containing
the current settings from the corresponding dialog box.
You can run the generated script as is to open QuickTest with the exact
configuration of the QuickTest application that generated the script, or you can
copy and paste selected lines from the generated files into your own
automation script.
Reference: Quick Test Pro > Documentation > QuickTest Automation Reference.
<!--[if !vml]-->
<!--[endif]-->

Hybrid Test Automation Framework

<!--[if !vml]--> <!--[endif]-->

APPLICATION MAP

The Application Map is one of the most critical components, which is used for
mapping the objects from names humans can recognize to a data format useful for the
automation tool. For a given project it is needed to define a naming convention or
specific names for each component in each window as well as a name for the window
itself. Then use the Application Map to associate that name to the identification method
needed by the automation tool to locate and properly manipulate the correct object in the
window.

Application Map not only gives the ability to provide useful names for the objects,
it also enables the scripts and keyword driven tests to have a single point of
maintenance on the object identification strings. Thus, if a new version of an application
changes the title of the window or label of the components or the index of an image
element within it, they should not affect the test tables. The changes will require only a
quick modification in one place--inside the Application Map.

COMPONENT FUNCTIONS

Component Functions are those functions that actively manipulate or interrogate


component objects. In test automation framework there are different Component
Function modules for each type of component that are encountered (Window,
CheckBox, TextBox, Image, Link, etc,).

Component Function modules are the application-independent extensions


applied to the functions already provided by the automation tool. However, unlike those
provided by the tool, the extra code to help with error detection, error correction, and
synchronization are added. These modules can readily use the application-specific data
stored in the Application Map and test tables as necessary. In this way, these
Component Functions are developed once and are used again and again by every
application tested.

Another benefit from Component Functions is that they provide a layer of


insulation between the application and the automation tool. Without this extra layer,
changes or "enhancements" in the automation tool itself can break existing scripts and
the table driven tests. Each Component Function modules will define the keywords or
"action words" that are valid for the particular component type it handles.

The component Functions takes the windows name in which the component
resides, the actual component name on which the action is to be performed, the values
needed for performing the action and the type of action to be performed as its
arguments. The Component Function keywords and their arguments define the low-level
vocabulary and individual record formats will be used to develop the test tables.
TEST TABLES

The input to the framework apart from the application map are the test tables, which
holds the arguments needed for the Component Functions and other information. There
are three levels in which the test tables are organized, they are as follows,

<!--[if !supportLists]--> <!--[endif]-->Low-Level Test Tables (or) Step


Tables

<!--[if !supportLists]--> <!--[endif]-->Intermediate-Level Test Tables (or)


Suite Tables

<!--[if !supportLists]--> <!--[endif]-->High-Level Test Tables (or) Cycle


Tables.

LOW-LEVEL TEST TABLES

Low-level Test Tables or Step Tables contain the detailed step-by-step


instructions of the tests. Using the object names found in the Application Map, and the
vocabulary defined by the Component Functions; these tables specify what window,
what component, and what action to take on the component. The columns in the Step
Tables are as follows,

<!--[if !supportLists]--> <!--[endif]-->Action Command

<!--[if !supportLists]--> <!--[endif]-->Window Name

<!--[if !supportLists]--> <!--[endif]-->Component Name

<!--[if !supportLists]--> <!--[endif]-->Values Need to Perform the Specified


Action

The StepDriver module is the one that initially parses and routes all low-level
instructions that ultimately drive our application.

INTERMEDIATE-LEVEL TEST TABLES


Intermediate-level Test Tables or Suite Tables do not normally contain such low-
level instructions. Instead, these tables typically combine Step Tables into Suites in
order to perform more useful tasks. The same Step Tables may be used in many Suites.
In this way the minimum numbers of Step Tables necessary are developed. Then they
are organized in Suites according to the purpose and design of the tests, for maximum
reusability. The columns in the Suite Tables are as follows,

<!--[if !supportLists]--> <!--[endif]-->Step Table Name

<!--[if !supportLists]--> <!--[endif]-->Specific Arguments to be Passed to


the Step Tables

The Suite Tables are handled by the SuiteDriver module which parses each
record in the Suite Table and passes each Step Table to the StepDriver module for
processing.

HIGHER-LEVEL TEST TABLES

High-level Test Tables or Cycle Tables combine intermediate-level Suites into Cycles.

The Suites can be combined in different ways depending upon the testing Cycle which is
efficient to execute. Each Cycle will likely specify a different type or number of tests. The
columns in the Cycle Tables are as follows,

<!--[if !supportLists]--> <!--[endif]-->Suite Table Name

<!--[if !supportLists]--> <!--[endif]-->Specific Arguments to be Passed to


the Suite Table

These Cycles are handled by the CycleDriver module which passes each Suite
to SuiteDriver for processing.

CORE DATA DRIVEN ENGINE

The Core Data Driven Engine is the primary part of the framework and it has
three main modules, they are as follows
<!--[if !supportLists]--> <!--[endif]-->StepDriver

<!--[if !supportLists]--> <!--[endif]-->SuiteDriver

<!--[if !supportLists]--> <!--[endif]-->CycleDriver

CycleDriver processes Cycles, which are high-level tables listing Suites of tests
to execute. CycleDriver reads each record from the Cycle Table, passing SuiteDriver
each Suite Table it finds during this process. SuiteDriver processes these Suites, which
are intermediate-level tables listing Step Tables to execute. SuiteDriver reads each
record from the Suite Table, passing StepDriver each Step Table it finds during this
process. The following figure represents the Core Data Driven Engine,

<!--[if !vml]-->

<!--
[endif]-->

Core Data Drive Engine

StepDriver processes these Step Tables, which are records of low-level


instructions developed in the keyword vocabulary of the Component Functions.
StepDriver parses these records and performs some initial error detection, correction,
and synchronization making certain that the window and\or the component planned to
manipulate is available and active. StepDriver then routes the complete instruction
record to the appropriate Component Function for final execution.

SUPPORT LIBRARIES

The Support Libraries are the general-purpose routines and utilities that let the
overall automation framework do what it needs to do. They are the modules that provide
services like,

<!--[if !supportLists]--> <!--[endif]-->File Handling


<!--[if !supportLists]--> <!--[endif]-->String Handling

<!--[if !supportLists]--> <!--[endif]-->Buffer Handling

<!--[if !supportLists]--> <!--[endif]-->Variable Handling

<!--[if !supportLists]--> <!--[endif]-->Database Access

<!--[if !supportLists]--> <!--[endif]-->Logging Utilities

<!--[if !supportLists]--> <!--[endif]-->System\Environment Handling

<!--[if !supportLists]--> <!--[endif]-->Application Mapping Functions

<!--[if !supportLists]--> <!--[endif]-->System Messaging or System API


Enhancements and Wrappers

They also provide traditional automation tool scripts access to the features of our
automation framework including the Application Map functions and the keyword driven
engine itself. Both of these items can vastly improve the reliability and robustness of
these scripts until such time that they can be converted over to keyword driven test
tables.

Posted by aman at 1:43 AM

Using the Dictionary Object in QTP

As an alternative to using environment variables to share values between


actions, you can use the Dictionary object. The Dictionary object enables you to assign
values to variables that are accessible from all actions (local and external) called in the
test in which the Dictionary object is created.

'In order to have IntelliSense for the Dictionary object, and have it recognized by other
actions, it is added to the registry

Dim WshShell

Set WshShell =CreateObject("WScript.Shell")


WshShell.RegWrite "HKCU\Software\Mercury Interactive\QuickTest Professional\
MicTest\ReservedObjects\GlobalDictionary\ProgID", "Scripting.Dictionary","REG_SZ"

Set WshShell = Nothing

' After updating the registry, you must close and reopen QuickTest Professional.

'
************************************************************************
***********

' Available methods

' -----------------------------

' Exists

GlobalDictionary.Exists(<Key Name>) ' Returns True or False

' Remove

GlobalDictionary.Remove(<Key Name>) ' Remove a specific key

' RemoveAll

GlobalDictionary.RemoveAll ' Removes all keys

' Add

GlobalDictionary.Add <Key Name>, <Value> ' Create a new key and assigns its value

' Item

GlobalDictionary.Item(<Key Name>) ' Gets/Sets a key value

Labels: Functions, VBscript

Regular Expression
Objects and text strings with varying (changeable) values or we can say dynamic values can be
identified by QuickTest using Regular expressions.

Regular expressions can be used:


 To define property values of an object.
 To parameterize a step.
 To create a checkpoint with changeable values.

Important points regarding Regular expressions:

You can use regular expressions only for values of type string.

When any special character in a regular expression is preceded by a backslash (\), QuickTest
searches for the literal character.

You can define a regular expression for a constant value, a Data Table parameter value, an
Environment parameter value, or a property value in a programmatic description.

For more common options to create Regular Expressions, see QTP User Guide.

Instead of writing more about QTP regular expressions, lets quickly jump to examples.

Below you will find examples.

QTP Regular Expression Example 1

[This is just an example using Yahoo mail inbox. Your inbox unread mails may differ from the one
shown in this example]

1. Launch QTP and open a new test.


2. Open Internet Explorer.
[Now we have QTP with a blank test and Google open.]
3. Click on Record in order to start recording.
4. Copy and paste this URL (http://mail.yahoo.com) in the browser's address bar to open Yahoo mail
login.
5. Type your user name and password to login to Yahoo mail.
6. When Yahoo mail is open, click on the Inbox link as shown in the screenshot below.[ Note: The
Inbox can contain any number of mails. At any given point of time, Inbox(5) means 5 unread mails]
7. Click on Stop in order to stop recording. Then my recorded code looks like this:
Browser("Browser").Page("Page").Sync
Browser("Browser").Navigate "https://login.yahoo.com/config/login_verify2?&.src=ym"
Browser("Browser").Page("Yahoo! Mail: The best").WebEdit("login").Set "piyush
Browser("Browser").Page("Yahoo! Mail: The best").WebEdit("passwd").SetSecure
"4801a2cbf793b46aad67194b5cbc961c091f"
Browser("Browser").Page("Yahoo! Mail: The best").WebButton("Sign In").Click
Browser("Browser").Page("Yahoo! Mail - piyush@yahoo.com").Link("Inbox (6)").Click

Now if you don't check any mail in your inbox and log out and then again run this code it will work fine.

But if you check any mail like if I check one mail in my inbox then it will be Inbox(5), then if I run this
code it will fail because the link has changed from Inbox(6) to Inbox(5) and shows the below
mentioned error.

"Cannot identify the object Inbox(6) (of class Link). Verify that this object`s properties match an
object currently displayed in your application."

Now we will change the above code with the help of regular expression so that it will work even if there
is only one unread mail.

In QTP go to Resources (menu) ->Object Repository.

Object Repository window will open. Select the object "Inbox(6)". Click on the label Inbox(6) inside
Value column and then click on "<=>" button which will appear.

When you click on the button, it will open 'Value Configuration Options' window. On this window click
on Regular Expression check box. When you click on checkbox it will show warning . Just click on Yes.

Now in the Constant text box inside the displayed window( what I have entered "Inbox \([5-6]\)" and
click Ok and close Object Repository window.

This Regular Expression setting which we have done works for inbox unread mails between 5 and 6
e.g. if your inbox says inbox(5) or inbox(6).

Run the test. It passes for me because I had 5 unread mails in my inbox (inbox(5)).
You can do this setting according to your convenience e.g. [1-5] for unread mails between 1 and 5 and
so on.

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

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

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

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

3) Read two numbers and display the sum?

Dim num1,num2, sum


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

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

Dim p,t, r, si
p=inputbox ("Enter Principle")
t=inputbox ("Enter Time")
r=inputbox ("Enter Rate of Interest")
si= (p*t*r)/100 ' p= principle amount, t=time in years, r= rate of interest
msgbox ("Simple Interest is " &si)
5) Read Four digit number, calculate & display the sum of the number or display
Error message if the number is not a four digit number?

Dim num, sum


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

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

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

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

a) If average marks Greater than or equal to 75, grade is Distinction


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

Dim e,m,p,c, tot


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

8) Display Odd numbers up to n?

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

9) Display Even numbers up to n?

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

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

Dim num, n, fso, myfile


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

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

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

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

Dim num, n, sum


n= inputbox ("Enter a Value")
sum=0
For num= 1 to n step 1
sum= sum+num
Next
msgbox sum
13) Display Natural numbers sum up to n? (using While...Wend Loop)

Dim num, n, sum


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

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

Dim num, n, sum


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

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

Function NNumCou (n)


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

16) Verify weather the entered 10 digit value is a numeric value or not?

Dim a,x,y,z,num
num=Inputbox ("Enter a Phone Number")
d1= left (num,1)
d10=Right (num,1)
d2=mid (num, 2, len (1))
d3=mid (num, 3, len (1))
d4=mid (num, 4, len (1))
d5=mid (num, 5, len (1))
d6=mid (num, 6, len (1))
d7=mid (num, 7, len (1))
d8=mid (num, 8, len (1))
d9=mid (num, 9, len (1))

If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and
isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and
isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and
isnumeric (d10) = "True" Then

msgbox "It is a Numeric Value"


else
Msgbox "It is NOT Numeric"
End If

17) Verify weather the entered value is a 10 digit value or not and Numeric value or
not? (Using multiple if conditions)

Dim a,x,y,z,num
num=Inputbox ("Enter a Phone Number")
d1= left (num,1)
d10=Right (num,1)
d2=mid (num, 2, len (1))
d3=mid (num, 3, len (1))
d4=mid (num, 4, len (1))
d5=mid (num, 5, len (1))
d6=mid (num, 6, len (1))
d7=mid (num, 7, len (1))
d8=mid (num, 8, len (1))
d9=mid (num, 9, len (1))

If len (num) =10 Then

If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and
isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and
isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and
isnumeric (d10) = "True" Then
msgbox "It is a Numeric Value"
End If
End If

If len (num) <> 10 Then


Msgbox "It is NOT valid Number "
End If

QTP Code Base


Methods in QTP

'************ Set Output Parameter for use in subsequent components


'************
Parameter("submissionName") = Parameter("insuredName")

'************ Local Parameter initialization '************


LocalParameter("role")=Parameter("role")

'************ Role '************


If Parameter("role") = "Agent" Then
'insert code here
Else
'insert code here
End If

'************ Delay '************


delay1 = 5

'************ Parse '************


DataTable("automationname") = ".*" & Parameter("searchString") & ".*" ' for
"The Row You Know"
Browser("...").FlexApplication("...").FlexCanvas("mainScreen").FlexBox("...").Fle
xCanvas("Overview").FlexPanel("What's New").FlexLabel("The Row You
Know").Output CheckPoint("What's New Row X")

debug below
Parameter("companyName") = "07_Daniel"
Parameter("searchString") = "Assigned to"
debug above
Browser("...").FlexApplication("...").FlexCanvas("mainScreen").FlexBox("...").Fle
xCanvas("Overview").FlexPanel("What's New").Output CheckPoint("What's New
Table")

'************ Search a string and parse it '************


messageSegment = Split( DataTable("Item_1"), Parameter("searchString") )
If messageSegment(0) = DataTable("Item_1") Then
'msgbox "same same"
messageSegment_2= Split( DataTable("Item_2"), Parameter("searchString") )
If messageSegment_2(0) = DataTable("Item_2") Then
'msgbox "same same here too"
Else
Parameter("valueObtained") = Trim( messageSegment_2(1) )
'msgbox Trim( messageSegment_2(1) )
End If
Else
Parameter("valueObtained") = Trim( messageSegment(1) )
End If

'************ Open Submission '************


comapnyRegEx = ".*" & DataTable("insuredName") & ".*"
ready =
Browser("...").FlexApplication("...").FlexCanvas("mainScreen").FlexDividedBox("
Home").FlexPanel("casesPanel").FlexDividedBox("index:15").FlexDataGrid("con
tentGrid").FlexBox("automationname:="&insuredRegEx ).Exist
aName =
Browser("...").FlexApplication("...").FlexCanvas("mainScreen").FlexDividedBox("
Home").FlexPanel("casesPanel").FlexDividedBox("index:15").FlexDataGrid("con
tentGrid").FlexBox("automationname:="&insuredRegEx ).GetROProperty("auto
mationname")
aName =
Browser("...").FlexApplication("...").FlexCanvas("mainScreen").FlexDividedBox("
Home").FlexPanel("casesPanel").FlexDividedBox("index:15").FlexDataGrid("con
tentGrid").FlexBox("automationname:="&insuredRegEx ).GetROProperty("auto
mationname")

Browser("...").FlexApplication("...").FlexCanvas("mainScreen").FlexDividedBox("
Home").FlexPanel("casesPanel").FlexDividedBox("index:15").FlexDataGrid("con
tentGrid").DoubleClick aName
Browser("...").FlexApplication("...").FlexCanvas("mainScreen").FlexDividedBox("
Home").FlexPanel("casesPanel").FlexDividedBox("index:15").FlexDataGrid("con
tentGrid").DoubleClick aName

'************ Do Loop '************


generateBar = Browser("...").FlexApplication("...").FlexBox("index:4").Exist
Do Until generateBar = False
generateBar = Browser("...").FlexApplication("...").FlexBox("index:4").Exist

If generateBar = False Then


Browser("...").FlexApplication("...").FlexPanel("External Data
Report:").FlexButton("Close window.").Click
End If
Loop
'************ Increment index number '***********
numNotes = 5
initialIndex=2
For Iterator = 0 To numNotes-1 Step 1
msgbox Iterator
initialIndex=initialIndex+12
msgbox initialindex
Next
resultIndex = ("index:"&initialIndex)
msgbox resultIndex

'************ Programmatically parse and verify the text in PDF docs using
clipborad to text '************
string1 = "Hello World"
len_data = len(string1)
i=0
file_path = "C:\qtp\pdftotext.text"
Set clipboard = createobject("mercury.clipboard")
Set fso = createobject("scripting.filesystemobject")
Set notepad = fso.createtextfile(file_path,8)

'************ Start recording click on Edit menu--select all, 'click on Edit menu--
copy, click on pdf file to get deselect 'the text...'************
Window("Adobe Reader").Activate
Window("Adobe Reader").WinMenu("Menu").Select "Edit;"
Window("Adobe Reader").WinMenu("Menu").Select "Edit;"
Window("Adobe Reader").Activate

get_text = clipboard.gettext
notepad.Write get_text
notepad.Close

Set notepad = fso.opentextfile(file_path,1)

Do while notepad.AtEndofStream <> true


get_data = notepad.readline
search_data = instr(get_data, "Hello World")
capture_data = mid(get_data,search_data,len_data)

If capture_data = string1 then


i = i+1
Else

End if

Loop
'msgBox ("the text is found in" &i &"rows")

'************ Len function '************


'Returns the number of characters in a string or the number of bytes required to
store a variable.
Dim MyString
MyString = Len("VBSCRIPT") ' MyString contains 8.

'************ Increment using Do While statements '************


increment = 0
counter =0
Do While increment = increment+1
counter = counter=1
Loop While False

'************ Programmatically parse and verify the text in PDF docs using
clipborad to text '************
LocalParameter("filePath") = "C:\qtp\"
LocalParameter("fileType") = "parsePDF.xls"
LocalParameter("verifyText") = "Stephanie Cassady"
LocalParameter("pdfDoc") = "cover letter.pdf"

filePath = LocalParameter("filePath")
localPath = LocalParameter("filePath")&LocalParameter("fileType")
snapData = LocalParameter("verifyText")

Dim captureData
lenData = Len(snapData)
i=0
rowCounter=0
filePath = localPath
Set clipboard = createobject("mercury.clipboard")
Set fso = createobject("scripting.filesystemobject")
Set notepad = fso.createtextfile(filePath,8)

'************ Open PDF file '************


SystemUtil.Run "C:\Program Files\Adobe\Reader 8.0\Reader\
AcroRd32.exe","",filePath,""
Window("Adobe Reader").WinMenu("Menu").Select "File;"
Window("Adobe Reader").Dialog("Open").WinEdit("File name:").Set
LocalParameter("filePath")
Window("Adobe Reader").Dialog("Open").WinEdit("File name:").Type
micReturn
Window("Adobe
Reader").Dialog("Open").WinListView("SysListView32").Activate
LocalParameter("pdfDoc")
Window("Adobe Reader").Activate
Window("Adobe Reader").WinMenu("Menu").Select "Edit;"
Window("Adobe Reader").WinMenu("Menu").Select "Edit;"
Window("Adobe Reader").Close

getText = clipboard.gettext
notepad.Write getText
notepad.Close

Set notepad = fso.opentextfile(filePath, 1)

Do while notepad.AtEndofStream <> true


getData = notepad.readline
searchData = InStr(getData, snapData)
rowcounter = rowcounter+1

If searchData <>0 Then


captureData = Mid(getData,searchData,lenData)
End If

If captureData = string1 Then


i = i+1
'msgBox rowCounter
rowNumber = rowcounter
'msgBox rowNumber
Else

End if

Loop

If captureData Then
msgBox "The '"&captureData &"' text were found in the number " &searchData
&" position on row "&rowNumber+1
Else
msgBox "The were no text found in this document that matches what you're
looking for. Code: ID-10-T, S-U-E"
End If

'************ Calculate index '************


numNotes = Parameter("numNotes")

initialIndex = 7
For Iterator = 1 To numNotes-1 Step 1
initialIndex=initialIndex+13
Next
resultIndex = ("index:"&initialIndex)
buttonIndex = ("index:"&initialIndex+1)
shareIndex = ("index:"&initialIndex+5)

LocalParameter("shareNote") = resultIndex
LocalParameter("share") = shareIndex

'************ Report Status '************


Public Function assertTrue( bExpression, aOptions )
Set oOptions = GetOpts( ARRAY ( _
"sEvent", "AssertTrue", _
"sLogMessage", "Expected the given expression to return TRUE" _
), aOptions)
'Return true or false
assertTrue = reportStatus(bExpression, oOptions("sEvent"), _
oOptions("sLogMessage"))
End Function

If assertTrue(userMarcus.exists(NULL)) Then
userMarcus.edit(ARRAY("Role", "Agile SCRUM Master"))
End If

'************ Ubound Arrays '************


A = "1"
B = "2"
C = "3"

i=1
basic100 = "Basic (100%)"
ParArray = Array(A, B,C)
n = Ubound (ParArray)
msgBox n

For i = 0 To n Step 1
msgBox ParArray(i)
msgBox ParArray(i) <> Empty
If ParArray(i) <> Empty Then
Reporter.ReportEvent micPass, "Verify whether the field is populated with data",
" The "&basic100&" field is not empty."
msgBox i
Else
Reporter.ReportEvent micFail, "Verify whether the field is populated with data",
" The "&basic100&" field is EMPTY."
msgBox i
End If
Next
'************ Lbound Arrays '************
A = "1"
B = "2"
C = "3"

i=1
basic100 = "Basic (100%)"
ParArray = Array(A, B,C)',(a,b,c)
n = Ubound (ParArray)
msgBox n

For i = 0 To n Step 1
msgBox ParArray(i)
msgBox ParArray(i) <> Empty
If ParArray(i) <> Empty Then
Reporter.ReportEvent micPass, "Verify whether the field is populated with data",
" The "&basic100&" field is not empty."
msgBox i
Else
Reporter.ReportEvent micFail, "Verify whether the field is populated with data",
" The "&basic100&" field is EMPTY."
msgBox i
End If
Next

'************ Calculate Variable Index '************


lookIndex =15
result = 0

i =6
j =0
k =4

numRows = 6

For i = 6 To numRows*3 Step 3


k = k+2
j = i-k
If (i =lookIndex) Then
resultName = j
msgbox resultName
Exit for
End If

Next
'************ Calculate Variable Index 2'************
j=0
i=6
k=4
'Index number for that column within that row
resultColumnIndex=0
'Extracted value from the flex property
rowIndex=12
'Number of rows
max=3
'The index number of the last row. e.g. for 4 rows - the last index number would
be 12
range=(max+1)*3

For i=6 to range Step 3


k=k+2
' msgbox "k="&k
j=i-k
'msgbox "j="&j
If i=lookIndex Then
resultColumnIndex=j
' msgbox j
Exit for
End If
Next
msgbox result

'************ String Compare'************


'Step 1: Fetch the Text from the Text Field.
strText = Browser(b).Page(P).Frame(f).WebEdit(T).getROProperty("value")
'Step 2: Fetch the Text from the Table
strTBL_text = Browser(B).Page(p).Frame(f).WebTable(w).GetCellData(1,1)

'Step 3: Comparision
If strComp(strText,strTBL_text) = 0 then
Reporter.ReportEvent micPass, "PASS","PASS"
Else
Reporter.ReportEvent micFail,"FAIL","FAIL"
End If

'************ Create new and close excel'************


Dim xlApp
Dim xlBook
Dim xlSheet

Set xlApp=CreateObject("Excel.Application")
Set xlBook=xlApp.workbooks.add
Set xlSheet=xlBook.activesheet
xlSheet.cells(1,1)="helloo"

xlBook.saveas "c:test.xls"
xlApp.quit

'************ Send Mail'************

SendTo=".......@........com"
SendToCC=".......@........com"
Subject="QTP mail"
Body1="This mail is generated from QTP Environment"
Attachment="C:\Spec.xls"

Call SendMail(SendTo, Subject, Body1, Attachment)

Function SendMail(SendTo, Subject, Body, Attachment)


Set ol=CreateObject("Outlook.Application")
Set Mail=ol.CreateItem(0)
'ol.DisplayAlerts = False
Mail.to=SendTo
Mail.CC=SendToCC
Mail.Subject=Subject
Mail.Body=Body
If (Attachment <> "") Then
Mail.Attachments.Add(Attachment)
End If
Mail.Send
ol.Quit
Set Mail = Nothing
Set ol = Nothing
End Function

'************ Send Mail'************

Function AttachHTMLAsMailContent(sSendTo,
sSendToCC,sSendToBCC,sSubject,sHtmlPath)

Dim objOutlook
Dim objOutlookMsg
Dim olMailItem

' Create the Outlook object and the new mail object.
Set objOutlook = CreateObject("Outlook.Application")
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)

' Define mail recipients


objOutlookMsg.To = sSendTo
objOutlookMsg.CC = sSendToCC
objOutlookMsg.BCC = sSendToBCC

' Body of the message

With objOutlookMsg
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(sHtmlPath,1)
strText = ts.ReadAll
.HTMLBody = strText
.Display
End With

' Send the message


objOutlookMsg.Send
wait(3)

' Release the objects


set objOutlook = nothing
set objOutlookMsg = nothing

End Function

'Sample usage
'AttachHTMLAsMailContent "MyName@abc.com","","","TestResults-
MultipleAttachments","D:TestCase.html"

'************ Calling an XML file'************


Dim oXML
Set oXML = CreateObject(”Microsoft.XMLDOM”)
oXML.Load sPathToXML

Set oXML = Nothing

'************ Creating an XML file'************


Set objdoc=XMLUtil.CreateXML()
objdoc.loadFile = "C:\Test.xml"

set root = objdoc.GetRootElement()


set children = root.ChildElements()

set firstchild = children.item(1)


set secondchild = children.item(1).ChildElements()

For i = 1 to secondchild.count()
secondchild.item(i).ElementName()
Next

'************ Upadate an XML file'************


createdCompanyName = Environment.Value("createdCompanyName")
Select Case serviceSelect
Case "Appraisal"
'Appraisal XML
Const XMLDataFile = "Q:\Automation Framework\Quality Center\005 Library\
Appraisal.xml"

Set xmlDoc = CreateObject("Microsoft.XMLDOM")


xmlDoc.Async = False
xmlDoc.Load(XMLDataFile)

'Update the name of the company


Set node = xmlDoc.SelectSingleNode("/Environment/Variable[0]/Name")
node.Text = createdCompanyName

'Save changes
xmlDoc.Save(XMLDataFile)

'************ Create an XML file'************

serviceSelection = "Home Inspection - General" 'DataTable("serviceSelect",


dtGlobalSheet)
' newCompanyName = Envrionment.Value("createdCompanyName")
newCompanyName = "ABC"

Const XMLDataFile = "Q:\Automation Framework\Quality Center\005 Library\


Verticals.xml"
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = False
xmlDoc.Load(XMLDataFile)

Select Case serviceSelection


Case "Appraisal"
'Update the name of the company
Set node = xmlDoc.SelectSingleNode("/Environment/Variable[0]/Appraisal")
node.Text = newCompanyName

Case "Home Warranty"


'Update the name of the company
Set node = xmlDoc.SelectSingleNode("/Environment/Variable[1]/Warranty")
node.Text = newCompanyName

Case "Home Inspection - General"


'Update the name of the company
Set node = xmlDoc.SelectSingleNode("/Environment/Variable[2]/Inspection")
node.Text = newCompanyName
End Select

'Save changes
xmlDoc.Save(XMLDataFile)

End Function

'************ Read an XML file'************

Const XMLDataFile = "Q:\Automation Framework\Quality Center\005 Library\


Verticals.xml"
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = False
xmlDoc.Load(XMLDataFile)

serviceSelection = "Home Inspection - General" 'DataTable("serviceSelect",


dtGlobalSheet)
Select Case serviceSelection
Case "Appraisal"
'Get the company name
Set node =
xmlDoc.SelectSingleNode("/Environment/Variable[0]/Appraisal/text()")
msgBox "Company Name: " & node.NodeValue

Case "Home Warranty"


'Get the company name
Set node =
xmlDoc.SelectSingleNode("/Environment/Variable[1]/Warranty/text()")
msgBox "Company Name: " & node.NodeValue

Case "Home Inspection - General"


'Get the company name
Set node =
xmlDoc.SelectSingleNode("/Environment/Variable[2]/Inspection/text()")
msgBox "Company Name: " & node.NodeValue

End Select

'************ Command line execution************


Dim qtApp 'As QuickTest.Application ' Declare the Application object variable
Dim qtTest 'As QuickTest.Test ' Declare a Test object variable

Set qtApp = CreateObject("QuickTest.Application") ' Create the Application


object
qtApp.Launch ' Start QuickTest
qtApp.Visible = False ' Make the QuickTest application visible

'***************************************************************************
******************************************************
' Run suite QA Deployment Sanity Test
qtApp.Open "C:\Temp\simple_test", True ' Open the test in read-only mode

' set run settings for the test


Set qtTest = qtApp.Test
qtTest.Run ' Run the test

'Email Status
WScript.StdOut.Write "Status is:" & qtTest.LastRunResults.Status ' Check the
results of the test run

' Close the test


qtTest.Close

Set qtResultsOpt = Nothing ' Release the Run Results Options object
Set qtTest = Nothing ' Release the Test object
Set qtApp = Nothing ' Release the Application object

'***************************************************************************
******************************************************
'Call scripts and execute
'Load common functions from library
Execute getTextFileContent("\\server\path\libraryFileName","Unicode")

'Set initial test run option parameter


strRunCode = "intTestRunOptionId = 2" & vbLF

'Load QTP test code


strRunCode = strRunCode & _
getTextFileContent("\\server\path\yourQTPTestName\Action1\Script.mts","utf-
8")
'Execute test
Execute strRunCode

'***************************************************************************
******************************************************
'Filter email messages in MS Outlook
Const olFolderInbox = 6

Set objOutlook = CreateObject("Outlook.Application")


Set objNamespace = objOutlook.GetNamespace("MAPI")
Set objFolder = objNamespace.GetDefaultFolder(olFolderInbox)

Set colItems = objFolder.Items


Set colFilteredItems = colItems.Restrict("[Subject] = 'Project Proposal'")

For Each objMessage In colFilteredItems


objMessage.PrintOut
Next

'***************************************************************************
******************************************************
'Lock PC after QTP run
Set obj = CreateObject("WScript.Shell")
sCmnd = "%windir%\SYSTEM32\rundll32.exe user32.dll,LockWorkStation"
obj.Run sCmnd, 0, False

'***************************************************************************
******************************************************
'File Compare
public function FileComparison(in File1, inFile2, out Result)
{
auto SaveFile = "Somefile in which the compared files are saved for future
viewing."

Result = file_compare(File1, File2, SaveFile, 0);

return(Result);
}

'***************************************************************************
******************************************************
'Outlook API
sServer = "mse20be3,mse20.exchange.ms" '"your.server.address.here"
sMailbox = "Arnold Conchas" '"mailboxName"

' build the ProfileInfo string


sProfileInfo = sServer & vbLf & sMailbox

' create your session and log on


Set oSession = CreateObject("MAPI.Session")
oSession.Logon "mse20/aconchas", "Saida0708", False, True, 0, True,
sProfileInfo

' create your Inbox object and get the messages collection
Set oInbox = oSession.Inbox
Set oMessageColl = oInbox.Messages

' get the first message in the collection


Set oMessage = oMessageColl.GetFirst

If oMessage Is Nothing Then


MsgBox "No messages found"
Else
' loop through inbox
Do
With oMessage
' message data:
Debug.Print .Subject & vbCrLf & .TimeReceived & vbCrLf & .Text
' this triggers the clever Outlook security dialog:
'Debug.Print .Sender(1) & vbCrLf & .Recipients(1)
Debug.Print
End With

Set oMessage = oMessageColl.GetNext


Loop Until oMessage Is Nothing
End If

'Logoff your session and cleanup


oSession.Logoff

Set oMessage = Nothing


Set oMessageColl = Nothing
Set oInbox = Nothing
Set oSession = Nothing

'***************************************************************************
******************************************************
'Outlook message extraction
Dim strBody ' Body
Const olFolderInbox = 6 ' Folder Constant in VBScript.
Dim objMail ' Mail Object.
Dim strFilter ' Filter For Messages
Dim strSubject 'What are we looking for?
strSubject = "Something" 'Change this to whatever subject fragment you want.

On Error Resume Next

' **** Create Instance of Outlook Application ********* '


Set objOutlook = CreateObject("Outlook.Application")

' **** Get NameSpace of Outlook Application ********* '


Set objNameSpace = objOutlook.GetNameSpace("MAPI")

' **** Get Inbox Folder of Outlook Application ********* '


Set objDefaultFolder = objNameSpace.GetDefaultFolder( olFolderInbox )

' **** Get Mail Messages in Folder **************** '


Set objMailItems = objDefaultFolder.Items

' ***** Filter Messages by Unread Flag And Sort Then in Descending Order
********** '
strFilter = "[UnRead] = True"
Set objResMailItems = objMailItems.Restrict( strFilter )
objResMailItems.Sort "[UnRead]",True

' ***** Loop on Unread Items ************** '


For Each objMail In objResMailItems

' ******* Search a mail with the given Subject ************ '
If InStr(objMail.Subject,strSubject) > 0 Then
strBody = objMail.Body
objMail.UnRead = False 'Marke message as unread
Exit For
End If

Next
Msgbox strBody
'***************************************************************************
******************************************************
'Send Keys
Set WshShell = CreateObject("WScript.Shell")
Browser("Browser").Page("Dashboard").WebEdit("WebEdit").Set "7208"
WshShell.SendKeys "{ENTER}"
Set WshShell = Nothing

'Send Key Codes


Key ----- Argument
BACKSPACE {BACKSPACE}, {BS}, or {BKSP}
BREAK {BREAK}
CAPS LOCK {CAPSLOCK}
DEL or DELETE {DELETE} or {DEL}
DOWN ARROW {DOWN}
END {END}
ENTER {ENTER} or ~
ESC {ESC}
HELP {HELP}
HOME {HOME}
INS or INSERT {INSERT} or {INS}
LEFT ARROW {LEFT}
NUM LOCK {NUMLOCK}
PAGE DOWN {PGDN}
PAGE UP {PGUP}
PRINT SCREEN {PRTSC}
RIGHT ARROW {RIGHT}
SCROLL LOCK {SCROLLLOCK}
TAB {TAB}
UP ARROW {UP}
F1 {F1}
F2 {F2}
F3 {F3}
F4 {F4}
F5 {F5}
F6 {F6}
F7 {F7}
F8 {F8}
F9 {F9}
F10 {F10}
F11 {F11}
F12 {F12}
F13 {F13}
F14 {F14}
F15 {F15}
F16 {F16}

Key ------ Special Character


SHIFT +
CTRL ^
ALT %

'***************************************************************************
******************************************************
'Search email web based client
Browser("micClass:=Browser").Page("micClass:=Page").Frame("html
id:=canvas_frame").WebElement("innerText:=info@emailiwant.com","html
tag:=SPAN","index:=0").Click
'***************************************************************************
******************************************************
'Open link from email
Define the collection
Set oDesc = Description.Create()
oDesc("micclass").Value = "Link"
Wait (0.5)

Set Links =
Browser("micClass:=Browser").Page("micClass:=Page").ChildObjects(oDesc)

NumberOfLinks = Links.Count()
nLoopCount = 0

Do Until svType > 0 or nLoopCount = NumberOfLinks


nLoopCount = nLoopcount + 1

svOuterHTML = Links(nLoopCount).GetROProperty("outerHTML")

svType = InStr(svOuterHTML, "http://mydomain/")

Loop
Links(nLoopCount).Click

'***************************************************************************
******************************************************
'Query DB by using and caliing stored procedure
Set objDB = CreateObject("ADODB.Connection")
strDSN = "DRIVER=SQL Server; DATABASE=[databasename];APP=QuickTest
Professional;SERVER=[servername];Description=Testconnection"
objDB.Open(strDSN)
Set objRec = objDB.Execute("exec [spname] '[param1]','[param2'")
Do Until objRec.EOF
Msgbox objRec.Fields("[column]")
objRec.MoveNext
Loop
Set objRec = Nothing
Set objDB = Nothing

'***************************************************************************
******************************************************
Set cnn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cnn.ConnectionString ="CONNECTION STRING"
cnn.open
query = "QUERY HERE"
rs.open query,cnn
rs.movefirst
msgbox rs(0)
msgbox rs(1)

'***************************************************************************
******************************************************
'Get last date of the month
MsgBox DateSerial(Year(Now), 1 + Month(Now), 0)

'***************************************************************************
******************************************************
sub LastDateOfCurMonth()
dim lstDateCurMonth, fstDateCurMonth, fstDateNxtMonth
fstDateCurMonth="01/" & Month(date) & "/" & Year(Date)
fstDateNxtMonth=DateAdd("m",1,fstDateCurMonth)
lstDateCurMonth=DateAdd("d",-1,fstDateNxtMonth)
wscript.echo "Last Date of Current Month is: " & lstDateCurMonth
End Sub

call LastDateOfCurMonth

'***************************************************************************
******************************************************
accruedPeriod = 16

eomonth = DateSerial(Year(Now), 2 + Month(Now), 0)


dateNow = Date + accruedPeriod
numDay = -DateDiff("d",eomonth, dateNow)

msgBox numDay

'Mousemove on flex

On Sun, Aug 9, 2009 at 11:29 PM, Arnold Conchas wrote:

'ManualStep "Step 1", "Type text in the note, then click the Share button on the
New Note ", "A Share Note message pop up displays with the following: · 'Are you
sure you want to share the selected note with the agent?' · Yes button · No button"
'ManualStep "Step 2", "Select 'Send e-mail to agent', then click the Yes button",
"The pop-up closes and a notification displays in the What's New area"

'Share Note
numNotes = Parameter("numNotes")

initialIndex = 7
For Iterator = 1 To numNotes-1 Step 1
initialIndex=initialIndex+13
Next
resultIndex = ("index:"&initialIndex)
buttonIndex = ("index:"&initialIndex+1)
shareIndex = ("index:"&initialIndex+5)

LocalParameter("shareNote") = resultIndex
LocalParameter("share") = shareIndex

actualNumNotes =
Browser("Underwriter").FlexApplication("Underwriter_2").FlexCanvas("mainSc
reen").FlexBox("insuredName").FlexPanel("Notes").FlexBox("notesContainer").g
etROproperty("numchildren")
If actualNumNotes => numNotes Then

Browser("Underwriter").FlexApplication("Underwriter_2").FlexCanvas("mainSc
reen").FlexBox("insuredName").FlexPanel("Notes").FlexBox("shareNote").Mous
eMove
Browser("Underwriter").FlexApplication("Underwriter_2").FlexCanvas("mainSc
reen").FlexBox("insuredName").FlexPanel("Notes").FlexButton("Share").Click

If Parameter("shareProducer") = "Yes" Then


producerStatus =
Browser("Underwriter").FlexApplication("Underwriter_2").FlexPanel("Share
Note").FlexCheckBox("Producer").GetROProperty("selected")
If producerStatus = False Then
Browser("Underwriter").FlexApplication("Underwriter_2").FlexPanel("Share
Note").FlexCheckBox("Producer").Click
End If
Else
producerStatus =
Browser("Underwriter").FlexApplication("Underwriter_2").FlexPanel("Share
Note").FlexCheckBox("Producer").GetROProperty("selected")
If producerStatus = True Then
Browser("Underwriter").FlexApplication("Underwriter_2").FlexPanel("Share
Note").FlexCheckBox("Producer").Click
End If
End If

Select Case Parameter("shareConfirm")


Case "Yes"
Browser("Underwriter").FlexApplication("Underwriter_2").FlexPanel("Share
Note").FlexButton("Yes").Click
Case "No"
Browser("Underwriter").FlexApplication("Underwriter_2").FlexPanel("Share
Note").FlexButton("No").Click
End Select

Browser("Underwriter").FlexApplication("Underwriter_2").FlexCanvas("mainSc
reen").FlexBox("insuredName").FlexPanel("Notes").FlexBox("shareNote").Mous
eMove
Browser("Underwriter").FlexApplication("Underwriter_2").FlexCanvas("mainSc
reen").FlexBox("insuredName").FlexPanel("Notes").FlexBox("notesContainer").
Click

End If

************************
Set olapp = createobject("outlook.application")
set inbox = olapp.getnamespace("mapi").folders

for each fold in inbox


msgbox fold.name
getsubfolders(fold)
next

msgbox inbox.count
sub getunreadmails(objfolder)

set col = objfolder.items

for each mail in col


if mail.unread then
msgbox mail.subject
msgbox mail.sendername
msgbox mail.body
msgbox mail.senton
mail.unread=false
end if
next

end sub
sub getsubfolders(objparentfolder)
set colfolders = objparentfolder.folders
for each objfolder in colfolders
set objsubfolder = objparentfolder.folders(objfolder.name)
if objfolder.name<>"notes" then
getunreadmails(objfolder)
end if
getsubfolders objsubfolder
next
end sub
******************************************

olFolderInbox = 6
varSubject = "Info from Closing.com" 'The subject of your mail
Set objOutlook = CreateObject("outlook.application")
Set objNameSpace = objOutlook.GetNameSpace("MAPI")
Set Inbox = objNameSpace.GetDefaultFolder(olFolderInbox)
Set Mail = Inbox.Items.Restrict("[Subject] = " & Chr(34) & varSubject &
Chr(34) )
'The above line is used to filter mails by subject similarly u can use "From" in
place of subject.
if sail.Count = 1 then
Msgbox "Mail Found"

Else
Msgbox "Mail Not present or there are More than one mail with same subject"
End if
POSTED BY ARNOLD AT 10:41 AM

Day46, 47, 48, 49 & 50 – Framework 


o Introduction to Framework 
o Developing Framework Infrastructure 
o Coding standards 
o Naming Conventions 
o Developing Generic Functions 
o Documentation standards 
o Test Data Management 
o Developing Test Scripts As per the Framework standards 
o Test Scripts Management 
o Test Results Management 
o Handling the script modifications 
o Making User Defined HTML Reports

Please Register Here To attend the training

12:37 AM | Add a comment | Permalink | Blog it | News and politics
January 18

How to find Data Type of a Variable?


 

The data type of a variable can be indentified in two VBScript built-in


functions.
1. Vartype
2. Typename

Vartype returns a numeric value indicating the sub datatype of a


variable.

The below table contains return values that indicate respective


subtypes.

Return Sub
Description
Value Datatype
0 vbEmpty Empty (uninitialized)
1 vbNull Null (no valid data)
2 vbIntegerInteger
3 vbLong Long integer
Single-precision floating-point
4 vbSingle
number
Double-precision floating-
5 vbDouble
point number
6 vbCurrency Currency
7 vbDate Date
8 vbString String
9 vbObject Automation object
10 vbError Error
11 vbBoolean Boolean
Variant (used only with arrays
12 vbVariant
of Variants)
13 vbDataObjectA data-access object
17 vbByte Byte
8192 vbArray Array
 

Ex:

Dim x

x=10
msgbox vartype(x) 'Returns 2
In the above table 2 indicates vbInteger datatype.So x is an integer
type.
Typename directly returns the name of the Sub Datatype of a
variable.

Sub
Description
Datatype
Byte Byte value
Integer Integer value
Long Long integer value
Single Single-precision floating-point value
Double Double-precision floating-point value
Currency Currency value
Decimal Decimal value
Date Date or time value
String Character string value
Boolean Boolean value; True or False
Empty Unitialized
Null No valid data
<object type> Actual type name of an object
Object Generic object
Unknown Unknown object type
Object variable that doesn't yet refer to an
Nothing
object instance
Error Error
 

Ex:

Dim x

x=10
msgbox typename(x) 'Returns “Integer”

There are some more VBScript Built-in functions to find whether a


variable datatype is specific datatype or not.
IsArray – Returns a Boolean value indicating whether a variable is an
array or not.
IsDate – Returns a Boolean value indicating whether an expression
can be converted to a date.
IsEmpty – Returns a Boolean value indicating whether a variable has
been initialized.
IsNull - Returns a Boolean value that indicates whether an expression
contains no valid data (Null).
IsNumeric - Returns a Boolean value indicating whether an
expression can be evaluated as a number.
IsObject - Returns a Boolean value indicating whether an expression
references a valid Automation object.
Built in functions are available for only these datatypes. You can write
built function for every datatype like below…
'*******************************
Function IsString(oValue)

If vartype(oValue)=8 then

IsString=true
Else
IsString=False

End If

End Function
'*******************************
12:20 AM | Add a comment | Permalink | Blog it | VB Script Samples
January 16

The Concept of Keyword Driven Framework


 

In Key Work Driven Framework the script values will be written in


Excel files and QTP will execute them using Driver Script. Now this will
explain how to execute the script which is specified in Excel Files.

There are majorly two approaches followed to make Keyword Driven


Framework.

1. Specify Script Values Directly in the Excel


2. Write Global Functions for each and every application control and
specify those functions as keywords in Excel

Approach 1:

In the below table there are 4 columns


Object Class         :- Class of the object on which we are going to
perform the operation
Object Properties  :- Properties of the object
Operation            :- The method to perform on the object
Value                  :- Input Data

Please remember that there is no method is available called


“SetParent” in QTP. But I am using this word as a condition to set the
parent of the object. I have delimited the Parent Object using “/” and
respectively I have used it for properties.

To go forward I should have the properties specified in my Object


Description Constants.

'Object Properties constants


Public Const GoogleBrowser = "name:=Google"
Public Const GooglePage = "title:=Google"
Public Const SearchEdit = "name:=q"
Public Const SearchButton = "name:=Google Search"
 
Why do we need to specify object properties as constants?

We can specify properties directly in place of constants. But when you


get a failure in the script, you might not able to identify where exactly
the error occurs.

For example, in the above table if the WebEdit step is failed then how
do we figure out the failure for which object in the application by just
using “name:=q” property. If we have assigned those properties to a
constant which is having an understandable name then it will be very
easy to identify for which object the failure occurs.
So now we have Excel Keywords and Object Description Constants. We
have to write driver script. Follow the
below steps prior to write the driver
script.

1. Create a Folder
“KeyWordDrivenSample” in
“C:\” drive
o In this folder create 3
subfolders with the names
“Scripts”,
“Constants”,”KeyWords”
2. Prepare an excel like how it is available in above table Save the
Excel file in the “C:\KeyWordDrivenSample\KeyWords”
folder with the name “ScriptKeywords.xls”
3. Copy above Object Description Constants in a VBS File and save
it in the “C:\KeyWordDrivenSample\Coanstants” with the
name “OR Constants.vbs”
4. Open a new test in QTP and Save the test in “C:\
KeyWordDrivenSample\Scripts” Folder with the name
“Driver Script”

Now you should have the Folder structure like specified below

Now you can save the below script in Driver Script and Run it.

'####################################################
###############
' Objective : This is a driver script for Sample Keyword Driven Framework
' Test Case : Driver Script
' Author : Sudhakar Kakunuri
' Date Created : 01/16/2010
' Date Updated : 01/16/2010
'Updated by : Sudhakar Kakunuri
'####################################################
###############
'##############Initialize Variables and Load
Libraries#############################
ExecuteFile "..\..\Costants\OR Constants.vbs"
'#####################Driver Script
######################################
'Add a new sheet and import keywords
Set dtKeyWords=DataTable.AddSheet("Keywords")
Datatable.ImportSheet "..\..\Keywords\ScriptKeywords.xls","Sheet1","Keywords"
'Get Row Count and Column Colunt of the databable
dtRowCount=dtKeyWords.GetRowCount
dtColumnCount=dtKeyWords.GetParameterCount
 'Use for lop to get values row by row
For dtRow=1 to dtRowCount
dtKeyWords.SetCurrentRow (dtRow)
strObjClass = DataTable("ObjectClass","Keywords")
strObjProperties = DataTable("ObjectProperties","Keywords")
strOperation = DataTable("Operation","Keywords")
strValue = DataTable("Value","Keywords")
If strOperation="SetParent" Then
oParentObjectArray=Split(strObjClass,"/")
oParentObjectPropArray=Split(strObjProperties,"/")
For iParentCount=0 to ubound(oParentObjectArray)
iParent=oParentObjectArray(iParentCount)
iParentProps=oParentObjectPropArray(iParentCount)
If iParentCount=ubound(oParentObjectArray) Then
strParent=strParent&iParent&"("&""""&eval(iParentProps)&""""&")"
Exit For
End If
strParent=strParent&iParent&"("&""""&eval(iParentProps)&""""&")."
Next
ParentObject=strParent
Else
oStatement=ParentObject&"."&strObjClass&"("&""""& eval(strObjProperties)
&""""& ")."& strOperation
If strValue<>"" Then
iStrInputDataArray=split(strValue,",")
For iInputValuesCount=0 to UBound(iStrInputDataArray)
If iInputValuesCount=UBound(iStrInputDataArray) Then
oStatement=oStatement&" "&""""&
iStrInputDataArray(iInputValuesCount) &""""
Exit for
End If
oStatement=oStatement&" "&""""& iStrInputDataArray(iInputValuesCount)
&""""&","
Next
End If
Execute (oStatement)
End If
Next
'####################################################
###############
Note: I have given this as a sample. As of now it only works
with Test Objects.

You might also like