Professional Documents
Culture Documents
00
1
I) Basic features of QTP
2
Version History of QTP
Add-In Manager
QTP supports almost all industry leading technologies, but by default it does not
support, with respect to add in license it supports.
• Activex
• Visual basic
• Web.
Other available Add Ins are: .NET, Java, People soft, Siebel, TE (Terminal
Emulators), SAP for GUI, Sap for Web, Oracle Apps, Web Services etc.
During QTP launching it shows Add in manger dialog box, Add in Manger lists out all
available Add Ins in the company.
User needs to select appropriate Add Ins for his application or AUT.
One can select more than one Add Ins also; if we select unnecessary Add Ins QTP
performance will be reduced.
3
Launching QTP
We can launch QTP BY selecting desktop icon otherwise start > programs> QTP
Professional > QTP.
4
II) Key Elements of QTP Tool Window
5
QTP Tool Window
1) Test Pane:
It is programming interface of QTP, used for creating, editing, viewing and deleting
test scripts.
Test: It is a set of statements or set of one or more actions. (It is a local concept)
6
Key word view- Test in Icon based GUI format.
Note1: Here in test pane Test is same but views are different, if you perform any
modifications in one view those automatically reflects in another view.
Note 2: Technical users use expert view and business user use key word view.
Navigation: Tools Menu> view options> we can use font size and colors etc.
7
2) Active Screen
It has an optional element of QTP, it takes snap shots of every statement that user
performed action or operation on AUT.
It can be used for understanding and editing the test easily.
Active Screen
8
3) Data Table
It has an integrated spread sheet (Excel like), used for Data driven testing.
Navigation: View menu>Data table (for launching and closing)
Data driven Testing: Testing the same task(S) or same operation with multiple sets
of test data.
It can be used in two ways.
1. Enter test data directly into Data Table and use.
2. Importing data from external files (Flat files, excel sheets, etc) and Data
bases (MS access, Sql Server, oracle, etc.)
9
4) Debug Viewer
We use step into, step over and step out commands for debugging. (debug
commands)
Through Debug viewer user can watch variables and change values of variables
temporarily.
10
5) Missing Resources
It can be used for showing missing resources those attached to current test such as
(recovery scenarios, library files etc).
6) Information
This pane shows syntax errors automatically during saving the test.
11
QTP Tool Window-Information Pane
7) QTP Commands
1. Menu options
2. Tool Bar options
3. Short cut keys (for Some important operations only)
File menu: Through file menu user can create, save tests, open existing tests,
export tests in zip format.
Edit Menu: It provides editing options and renaming, deleting and splitting actions.
View menu: Through this menu we can launch and close, active screen, Data Table,
Debug viewer, information, missing resources etc.
Insert Menu: Through this menu user can inserting check points, out put values,
synchronizing points.
12
In this menu step generator available, using this user can generate recordable and
non-recordable scripts.
Through insert menu user can insert VB Script conditional and loop statements and
transaction points (Start and End).
Through insert menu user can create new actions, call existing actions and copy
existing actions.
Automation Menu:
This menu provides Record, Run options and Run setting options
Through this menu we can start normal recording, analog recording and Low level
recording.
Through this menu we can stop recoding, running and also we run tests.
Resources Menu:
This menu provides object repository and recovery scenarios options.
Through this menu we can create /modify/delete objects information and we can
associate repositories.
Through this menu we can create, modify and delete recovery scenarios.
Debug Menu:
This menu provides debug commands for step by step execution.
Through this menu we can insert/remove/break points.
Tools Menu:
This menu provides Tools settings option, view options and object identification
configuration.
Through this menu we can set tool options as well as test pane view options.
In this menu object spy option available, through this we can get object’s
information.(Properties and values)
In this menu Virtual object option available; through this option we can create virtual
objects.
Window Menu:
This menu provides QTP tool window style settings.
Help Menu:
This menu provides QTP help as well as VB Script help.
Through this menu we can contact technical support people and we can send
feedback.
Through this menu we can check for updates and download or install directly.
13
III) QTP Testing Process
Planning
o Analyzing the AUT
o Generating/Selecting Test cases for Automation
o Collecting Test Data
o Automation Framework Implementation
o QTP Tool Settings Configuration
Generating Tests
o Recording
o Keyword driven methodology
o Descriptive Programming
Enhancing Tests
o Inserting Checkpoints
o Inserting Output values
o Adding Comments
o Synchronization
o Parameterization
o Inserting Flow Control Statements
o Calling Functions/Actions
o Generating Steps though Step Generator
o Inserting Transaction Points
o Using Regular Expressions
o Using Environment Variables
Debugging Tests
o Debug Commands & Break Points
o Step by step execution
o Watching Variables
o Changing values of variables
Running Tests
o Normal Execution
14
o Batch Execution
o AOM Scripting
o Tests Running through framework
o Scheduled Execution
Analyzing Results
o QTP Result window
o Defining our own Results
o Exporting Results
o Deleting Results
Reporting Defects
o Manual Defect Reporting
o Tool based Defect Reporting
o Working with Quality Center
Before we begin creating a test, we need to analyze our application and determine
our testing needs.
Then determine the functionality that we want to test. To do this, consider the
various activities that customers perform in our application to accomplish specific
tasks. Which objects and operations are relevant for the set of business processes
that need to be tested? Which operations require customized keywords to provide
additional functionality?
While we are thinking about the business processes we want to test, consider how
we can divide these processes into smaller units, which will be represented by our
test's actions. Each action should emulate an activity that a customer might perform
when using your application.
As we plan, try to keep the amount of steps we plan to include in each action to a
minimum. Creating small, modular actions helps make our tests easier to read,
follow, and maintain.
15
Recording and Running:
1. Normal Recording
It records User Mouse and Keyboard operations on AUT with respect to objects, but
unable to record continuous mouse operations like Digital Signatures, graphs, paints
etc.
During recording QTP generates VbScript statements in Test Pane, Simultaneously it
stores objects information into object repository.
Navigation: Automation>Record
Or
Select Record option on automation toolbar
Or
Use short cut key (F3)
5. Click OK
6. Perform actions on AUT
7. Stop recording.
8. Save the Test
2. Analog Recording:
It records the exact mouse and keyboard operations. We can use this mode for
recording continuous mouse operations. It is not useful for recording normal
operations why because it does not generate steps for each operation, generates
total user actions in a Track File. The Track file is not editable.
Navigation:
1. Keep tool under recording mode
2. Automation >Analog Recording
(OR) Use Short cut Key (Shift + ALT+F3)
16
1. Launch AUT (or we can launch AUT through QTP)
2. Select Record option
3. Automation>Analog Recording
4. Analog Recording Settings Dialog box opens
If we select first option QTP records User operations with respect to Desktop co-
ordinates.
If we select Second option, we have to show the window (AUT), after showing
the Window it records with respect to that window co-ordinates.)
5. Select any one option in the dialog box and click Start Analog record.
6. It records User actions
7. Stop Recording
This mode records at the object level and records all run time objects as window or
winobject Test objects.
Use Low Level Recording for recording in an environment not recognized by QTP.
Navigation:
1. Keep tool under recording mode
2. Automation >Low Level Recording
17
Object Repository
Object Repository:
It is a storage place of QTP where we can store the objects information and it also
acts as interface between the test script and the AUT in order to identify the
objects during execution.
Object:
Object is something, which has structure and properties.
Software objects:
We call windows, WebPages, buttons, edit boxes, check boxes etc.. as software
objects.
Run time objects: The objects present in the AUT. Ex: Buttons, links, etc…
Test Objects: References of Run time objects. Ex: WinEdit, WinButton, WebButton,
Link, etc…
Utility objects
They are QTP reserved objects used for testing and result reporting.
Ex:
1. SystemUtil for launching/closing the application.
2. Reporter for defining results.
3. Services for inserting transaction points
4. Environment for using environment variables
Automation objects/User defined objects
User can create objects; those can be used for performing specific operations. Ex:
Creating objects in file system object class, adodb.connection class, dictionary object
class, excel. Application class etc.
18
Local Repository:
QTP creates a Local Repository for every action automatically during Recording.
That cannot be shared among tests.
Shared Repository:
User (Test Engineer) creates shared repository by adding objects. That can be
shared among number of tests.
Using this method user can perform modifications on objects easily.
19
Operations on Object Repository
Adding objects
a. Local Repository:
Navigation: open local repository (resource menu>object repository)
>objects>Add objects to Local>show the object>click ok
(No need to save separately, it saves automatically)
B. Shared Repository:
Navigation: Resource menu>object repository manager>object>Add
objects>show the window/object>click ok
o Selected object only
o Default object types
o All objects types
o Selected object types
(If we select first option it stores Selected objects only, if we select second option it
stores all default objects, if we select third option it stores All objects including static
objects, if we select fourth option, we have to select object classes then it stores
that class objects, we can select more than one class also.)
Renaming objects
a. Local Repository:
Resources > object repository >select object and right click >choose rename
option >modify the name>release the mouse.>close repository
b. Shared Repository:
Resources >object repository manager>file>open>browse path of the
repository file >file>enable editing>select object &Right click>choose rename
option>modify the name > release mouse>save the file & close repository manager.
Deleting objects
a. Local Repository:
Resources > object repository >select object and right click >choose delete
option >confirm deletion>. >close repository
b. Shared Repository:
Resources >object repository manager>file>open>browse path of the
repository file >file>enable editing>select object &Right click>choose delete
option>confirm the deletion >save the file & close repository manager.
20
Merging Repositories
Note: After merging also, source repository files will be available, if we do not want
source files we can delete.
Note: This feature can be used for preparing tests before the AUT is ready.
Spying objects
For getting objects information, (Test objects names, property & Values) QTP is
providing a feature called Object Spy, using this we can get objects information.
View Options
Locate in Repository
This feature can be used for identifying objects from application to repository.
Navigation: View>Locate in repository >show the object>click Ok>it locates
specified object in the repository.
Highlight in Application
This feature can be used for identifying objects from repository to application.
Navigation: Select object in the repository >view>highlight in application>it
highlights specified objects in the application.
Note: The purpose of this feature is Editing objects information outside of the QTP
21
Descriptive Programming
Entering / Providing objects information directly into the test script is called
Descriptive Programming.
Advantages:
b) Scripts are portable (we can run these scripts from any machine easily)
d) We can start Test Execution process even though Application is not ready.
1. Static Programming
2. Dynamic Programming
Static Programming
In this style of script generation, we provide objects information directly into the
script.
Ex:
Invokeapplication "C:\Program Files\HP\QuickTest
Professional\samples\flight\app\flight4a.exe"
dialog("text:=Login").Activate
dialog("text:=Login").Winedit("attached text:=Agent Name:").Set "asdf"
dialog("text:=Login").Winedit("attached text:=Password:").Set "mercury"
dialog("text:=Login").Winbutton("text:=OK","width:=60").Click
Note:
1. Dialog, WinEdit and WinButton – Test Objects
2. text, attached text - Property names
3. Login, Agent Name:, Password:, OK - Property values or Logical Names of the
Object
4. Activate, Set, Setsecure, Click - Methods
Note2:
If we feel one property information is not sufficient for recognizing the object
uniquely, then we can provide more properties information by separating with
commas.
22
Note 3:
If we want to get objects information (Test objects, properties and values), we can
use object spy feature. This feature is available in Tools Menu, in local repository and
in repository manager.
-------------------------------------------------------------------
If we want maintain ‘Objects information’ in centralized location then we can use
Constants.
Steps:
Creating Constants:
Associate the Library file to QTP (File->Settings->Resources-> Click add (+) icon->
Browse path of the Library file->Click Apply and click Ok buttons
Syntax:
Advantages:
23
Dynamic Programming
Set oLogin=description.Create
Set oAgent=description.Create
Set oPassword=description.Create
Set oOk=description.Create
oLogin("text").value="Login"
oLogin("width").value=320
oLogin("height").value=204
oAgent("attached text").value="Agent Name:"
oPassword("attached text").value="Password:"
oOk("text").value="OK"
Note1: Create Description objects and put into one library file, by associating that
library file, we can generate tests.
----------------------------------------------------
In this style of script creation also, we can maintain Objects information in the
Centralized location by putting collection objects in a Library file.
----------------------------------------------------
24
Methods or Operations
Ex:
Dialog(“Login”).Activate
Window(“Flight Reservation”).Activate
Ex:
Window(“Flight Reservation”).Close
Browser(“Browser”).Close
Select Method:
Ex:
25
B. Window("Flight Reservation").Dialog("Flights Table").WinList("From").Select
"12572
Ex:
x=Window("Flight Reservation").WinComboBox("Fly From:").GetVisibleText
msgbox x
GetRoproperty:
It returns current object property value. It can be used for getting any object’s, any
property value.
Syntax: Variable = object hierarchy.getroproperty (“property name”)
Ex: x=Window("Flight Reservation").WinEdit("Tickets:").GetROProperty ("width")
msgbox x
Navigate Method:
It opens a specified URL in the Browser.
Syntax: object hierarchy.navigate “URL”
Ex: Browser("Yahoo!").Navigate "http://www.google.co.in"
26
Enhancing Tests
After generating the basic test, we have to enhance the test in order to Test the AUT
with respect to requirements.
There are several methods available in QTP for enhancing the TEST.
Inserting Checkpoints
Check point is a verification point, it takes expected result from the user and
compares with actual results during execution and provides test results.
27
1. Standard Checkpoint:
It checks object property values. We can use this checkpoint for checking any
property value.
Keep tool under recording mode > place cursor in desired location > Insert >
check point > Standard checkpoint > Show the object > click okay > select
property and enter expected results & click Ok and stop Recording.
Select Checkpoint statement and right click > choose checkpoint properties
option > modify the value > click Ok.
Select Checkpoint statements and right click > choose delete option.
View > Active Screen >place cursor in desired location >Place mouse pointer on
active screen & right click> choose insert standard checkpoint option > click ok >
enter expected result > click ok
Note: Inserting Standard check points through keyword view same as in expert
view.
Note: We can insert standard checkpoints in 3 ways.
1. Through expert view,
2. Through keyword view,
3. Through Active screen.
2) Text Checkpoint:
Navigation:
Keep tool under Recording mode >Insert menu > checkpoint > Text checkpoint
> Show the object > click ok > Select options
(Match case; ignore spaces, exact match, text not displayed.)
We can select one or more options > click ok & stop Recording.
28
Navigation:
Keep tool under Recording mode > Insert menu> Checkpoint > Text area
checkpoint > Mark the area of text > select one or more options
(Match case, ignore spaces, exact match, text not displayed.)
4. Bitmap checkpoint:
Navigation:
Keep tool under Recording mode > Insert menu > Checkpoint > Bitmap
checkpoint > show the Bitmap >click ok >select “check only selected area”
option if we want to compare part of the bitmap > click ok >stop recording.
5. Database checkpoint:
Navigation:
Insert > checkpoint > Database checkpoint >choose “specify SQL statement
manually” option >click next > click create > select machine data source >
Select DSN (QT_flight32) > click ok > enter SQL statement (select * from
orders) > finish > click ok.
Note: here we do not need to put tool under Recording mode and we do not
need AUT since data is from backend.
Invigilation:
Keep tool under recording mode with web environment
>insert>checkpoint>accessibility checkpoint>show the webpage>click ok>click
ok>stop recording.
Result Criteria:
a) If item is available but not according to W3C rules then fail.
b) If an item is available, according to W3C rules then Pass.
c) If an item is not available then result would be pass
29
7. XML Check point (from Application)
Navigation:
Keep tool under Recording mode in web environment > insert menu >
checkpoint (from application)> show the xml pages >click ok > stop Recording.
Navigation: Insert menu > checkpoint >xml checkpoint (from resource) >
browse path of the XML File > click ok > click ok.
Note: 1. If XML file is an individual and path available, and then we can go for
inserting xml checkpoint from resource.
Note: 2. If XML file is part of web application, separate path is not available then
we can choose inserting XML checkpoints from application.
9. Page checkpoint:
Navigation:
Keep tool under Recording mode with web environment > Insert menu >
checkpoint > Standard checkpoint >show the web page > click ok > click ok >
stop recording.
Navigation: Keep tool under Recording mode under web environment > Insert
menu > checkpoint > standard checkpoint >show the web table > click ok >stop
recording.
30
Inserting Output Values
It is a step in which one or more values are captured during test execution.
The values can later be used as input at a different point in the run session or we
can use as input for another test.
It is stored in run time data table; it is located in QTP result window and can be
retrieved later.
We can use standard output values to output the properties values of most
objects.
Navigation:
Keep tool under Recording mode > Insert menu >output value> standard output
value > show the object > click ok > select property > modify the column name
(if required) > click ok >click ok >stop recording.
We can use Text output values to output text strings displayed in an application.
When creating a text output value we can output a part of the objects text and
we can also specify text before and after options.
Navigation:
Keep tool under recording mode> Insert menu> output value > text output value
> show the text >select one of the option(output text/text before/text after) >
click modify if you want to change the column name > click ok > click ok.> check
in runtime table after running it.
31
3) Text Area output value:
We can use text area output values to output text strings displayed within a
defined area of the screen.
Navigation:
Keep tool under recording mode > insert menu >output value > text area output
value >Mark the text area >click modify the column name if necessary > click ok
> again click ok > check in run time table after running it..
We can use Database output values to output the value of the contents of
database cells.
Navigation:
Insert menu> output value > Database output value> choose specify SQL
statements manually >click next >click create >Select Machine Data source >
Select Driver (QT_flight32) > click ok > enter SQL statement (select *from
orders) > click finish > select data cells > click ok > Run and it will capture and
see the results in run time table.
we can use XML output values to output the values of XML elements in XML
documents.
Navigation: Keep tool under recording mode with web environment > Insert
menu > output value > XML output value from application > Show the XML
document > select elements > click ok >stop recording.
We can use XML output values to output the values of XML elements in XML
documents.
Navigation:
Insert menu >output value> XML output value from resource > browse path of
the XML file > click ok > select elements >click ok.
32
Adding Comments
Purpose of Comments:
Syntax:
Navigation: Select block of statements > Edit menu> Advanced> Comment block
Or
After selecting block of statements use shortcut key Ctrl+M
Or
After selecting comment block, Use shortcut key ctrl+shift+M
QTP adapted VB script engine for applying programming logic to tests. We can
insert VB script conditional statements and loop statements for applying the
logic.
In VB script there are 2 types of conditional statements and four types of loop
statements available.
33
Synchronization
It is a process of matching the speeds of both QTP and AUT in order to get proper
execution and results.
During test execution QTP gives instructions one by one with same speed, but
AUT takes less time for some operations execution and more time for some
operations execution, that time we may not get proper execution and results. In
order to get proper results in between QTP & AUT synchronization is required.
We can insert wait statements in our test in order to make QTP to wait until AUT
completes current operation.
Syntax:
Wait(time in seconds)
Note: If we insert wait statements QTP waits up to maximum time even though
operation is completed.
Place cursor in desired location>keep tool under recording mode > Insert menu
> Synchronization point > show the object > click ok > select property name &
Value (True)>enter time in Mille seconds>click ok>Stop recording.
Syntax:
object hierarchy.waitproperty “property name”,value,time in milli seconds.
34
Increasing Tool default synchronization time:
Note: If we increase QTP tool default time that can be applied for all statements
in the test, but QTP does not wait up to maximum time unnecessarily, After
completion of one statement execution it goes to next statement immediately.
1. Suppose in our test one or more statements only are taking more time for
execution then selecting “Inserting synchronization method” is better.
2. Suppose in our test more statements are taking more time for execution then
selecting “increasing tool time out” .
3. Above two are local features but wait statement is Vbscript feature, even
though some drawbacks are there in using wait statement, it is better to use
wait statement in functions.
Syntax:
Services.StartTransaction "name of the transaction"
-------
statements
---------
--------
services.EndTransaction "name of the transaction"
Note: We can insert multiple transactions points in a test.
35
Parameterization
Passing parameters, through this concept we can pass multiple values.
Data Driven Testing: Testing the Same operation with multiple sets of test
data.
Types of Parameterization:
We can use loop statements for passing sequential numbers & Logical Numbers.
For orderno=1 to 10 step 1 ' for one increment step keyword is not mandatory
Window("Flight Reservation").Activate
Window("Flight Reservation").WinButton("Button").Click
Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order
No.").Set "ON"
Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set orderno
Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
Next
Through Loop Statements we can give strings also but every time user has to
enter data.
For x=1 to 3
Agent =inputbox("enter an Agent Name")
Password=inputbox("enter a password")
invokeapplication "C:\Program Files\Mercury Interactive\QuickTest
Professional\samples\flight\app\flight4a.exe"
36
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set Agent
Dialog("Login").WinEdit("Agent Name:").Type micTab
Dialog("Login").WinEdit("Password:").SetSecure password
Dialog("Login").WinButton("OK").Click
Window("Flight Reservation").Close
Next
QTP adds one data table (Spreadsheet) for every test, we can use Data Table for
Data Driven Testing.
Click on column header>enter the name of the field (like this we can
create number of columns) > Enter Data>connect the data to test
Agent = Datatable("Agent",1)
pwd=Datatable ("Password",1)
invokeapplication "C:\Program Files\Mercury Interactive\QuickTest
Professional\samples\flight\app\flight4a.exe"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set Agent
Dialog("Login").WinEdit("Agent Name:").Type micTab
Dialog("Login").WinEdit("Password:").SetSecure pwd
Dialog("Login").WinButton("OK").Click
Window("Flight Reservation").Close
37
b. Importing test data from external files:
Open Data Table (view>Data table)>place mouse pointer on data table and right
click>file>import from file>Click ok>Browsw path of the file(it imports data from
the flat file)
Connecting Test Data to QTP Test as above and run the test.
Open Data Table (view>Data table)>place mouse pointer on data table and right
click>file>import from file>Click ok>Browse path of the excel sheet (it imports
data from the excel sheet)
Connecting Test Data to QTP Test as above and run the test.
D. Importing test data from Data bases: Through Data table we can import Test
Data from Data bases, but first we have to create /get the DSN(Data source
Name)& we have to use SQL Commands.
1. Creating a Test Database: open MS Access (or we can use any other
database).
Note: DSN Creation is one time activity, by using the DSN we can get data for
number of tests.
38
Environment Variables in QTP
These are global variables; if we want to use some variables globally (From number
of tests) declaring as global variables is better. If we declare as local variables in
number of tests, modifications are difficult.
1. Built in variables: These are system defined variables, we can access from all
tests but these are designed as read only.
Syntax:
Variable = Environment(“environment variable name”)
Ex:
X=Environment (“ActionName”)
Msgbox x
Example Script:
Navigation:
File > settings > Environment > select variable type as user defined > click add icon
(+) > enter variable name & Value > click ok (like this we can create number of
variables) > click export > browse path & enter file name, save with xml extension >
click ok.
Navigation:
File > settings >Environment > select variable type as user defined > check “load
variables and values from the external file” > browse path of the xml file > click
apply & ok.
39
Or
X=environment (“city”)
Msgbox x
40
Actions
Action: A Set of Statements for performing a Task or Tasks.
Purpose of Actions:
Types of Actions:
Operations on Actions:
• Creating Actions
• Splitting Actions
• Renaming Actions
• Deleting Actions
• Calling an Action
• Copying an Action
Creating an Action:
Insert>call to new action>enter name of the action>click ok
Steps:
Splitting an action:
Steps:
41
Note: At a time we can split one actions into 2 actions.
Renaming actions:
Select desired action in action drop down box> edit menu>action>rename
action>modify the name>click ok.
Deleting Actions:
Select desired action in action drop down box>edit menu>action>delete
action>confirm deletion.
Calling an action:
Insert>call to existing action>browse path of the test>select desired action>click ok.
Copying an action:
Insert>call to copy of action>browse path of the test>select desired action>click ok.
42
VB Script
(Fundamentals and Features)
1) Introduction
2) Comments
3) VB Script Variables
4) VB Script Data Types
5) VB Script Operators
6) Input/Output Operations
7) Constants
8) Conditional Statements
9) Loop through Code
10) VB Script Procedures
11) Procedures
12) VBScript syntax rules and guidelines
13) Errors
43
1.0 Introduction
When a VBScript is inserted into a HTML document, the Internet browser will read
the HTML and interpret the VBScript. The VBScript can be executed immediately, or
at a later event.
Microsoft Visual Basic Scripting Edition brings active scripting to a wide variety of
environments, including Web client scripting in Microsoft Internet Explorer and Web
server scripting in Microsoft Internet Information Service.
Windows Script Host is built into Microsoft Windows 98, 2000, and Millennium
Editions and higher versions.
A Windows script is a text file. We can create a script with any text editor as long as
we save our script with a WSH-compatible script extension (.js, vbs, or .wsf).
The most commonly available text editor is already installed on our computer —
Notepad. We can also use your favorite HTML editor, VbsEdit, Microsoft Visual C++,
or Visual InterDev.
1. Start Notepad.
2. Write your script. For example purposes, type Msgbox "Hello VB Script"
3. Save this text file with a .vbs extension (instead of the default .txt extension).
For example, Hello.vbs
4. Navigate to the file you just saved, and double-click it.
5. Windows Script Host invokes the VB Script engine and runs your script. In the
example, a message box is displayed with the message "Hello VB Script"
44
1.3 Hosting Environments and Script Engines
Scripts are often embedded in Web pages, either in an HTML page (on the client
side) or in an ASP page (on the server side). In the case of a script embedded in an
HTML page, the engine component that interprets and runs the script code is loaded
by the Web browser, such as Internet Explorer. In the case of a script embedded in
an ASP page, the engine that interprets and runs the script code is built into Internet
Information Services (IIS).
Windows Script Host executes scripts that exist outside an HTML or ASP page and
that stand on their own as text files.
Generally, we write scripts in either Microsoft JScript or VBScript, the two script
engines that ship with Microsoft Windows 98, 2000 and Millennium Editions. We can
use other script engines, such as Perl, REXX, and Python, with Windows Script Host.
A stand-alone script written in JScript has the .js extension; a stand-alone script
written in VBScript has the .vbs extension. These extensions are registered with
Windows. When we run one of these types of files, Windows starts Windows Script
Host, which invokes the associated script engine to interpret and run the file.
45
2.0 Comments
2.1 Syntax
o Select block of statement and use short cut key Ctrl + M (for comment)
o Select comment block and use short cut key Ctrl + Shift + M (for
uncomment)
46
3.0 VB Script Variables
A variable is a convenient placeholder that refers to a computer memory location
where we can store program information that may change during the time our script
is running.
We declare variables explicitly in our script using the Dim statement, the Public
statement, and the Private statement.
For example:
Dim city
Dim x
We declare multiple variables by separating each variable name with a comma. For
example:
We can also declare a variable implicitly by simply using its name in our script. That
is not generally a good practice because we could misspell the variable name in one
or more places, causing unexpected results when our script is run. For that reason,
the Option Explicit statement is available to require explicit declaration of all
variables.
The Option Explicit statement should be the first statement in our script.
47
Variable names follow the standard rules for naming anything in VBScript. A variable
name:
The variable is on the left side of the expression and the value you want to assign to
the variable is on the right.
For example:
B = 200
City = “Hyderabad”
Example:
Dim A(3)
48
Although the number shown in the parentheses is 3, all arrays in VBScript are zero-
based, so this array actually contains 4 elements.
We assign data to each of the elements of the array using an index into the array.
Beginning at zero and ending at 10, data can be assigned to the elements of an
array as follows:
A(0) = 256
A(1) = 324
A(2) = 100
A(3) = 55
Similarly, the data can be retrieved from any element using an index into the
particular array element you want.
For example:
SomeVariable = A(4)
Arrays aren't limited to a single dimension. You can have as many as 60 dimensions,
although most people can't comprehend more than three or four dimensions.
Arrays aren't limited to a single dimension. We can have as many as 60 dimensions,
although most people can't comprehend more than three or four dimensions.
In a two-dimensional array, the first number is always the number of rows; the
second number is the number of columns.
We can also declare an array whose size changes during the time our script is
running. This is called a dynamic array.
The array is initially declared within a procedure using either the Dim statement or
using the ReDim statement.
However, for a dynamic array, no size or number of dimensions is placed inside the
parentheses.
For example:
Dim MyArray()
49
ReDim AnotherArray()
To use a dynamic array, you must subsequently use ReDim to determine the
number of dimensions and the size of each dimension.
In the following example, ReDim sets the initial size of the dynamic array to 25. A
subsequent ReDim statement resizes the array to 30, but uses the Preserve
keyword to preserve the contents of the array as the resizing takes place.
ReDim MyArray(25)
There is no limit to the number of times we can resize a dynamic array, although if
we make an array smaller, we lose the data in the eliminated elements.
VBScript has only one data type called a Variant. A Variant is a special kind of data
type that can contain different kinds of information, depending on how it is used.
Because Variant is the only data type in VBScript, it is also the data type returned
by all functions in VBScript.
Beyond the simple numeric or string classifications, a Variant can make further
distinctions about the specific nature of numeric information. For example, we can
have numeric information that represents a date or a time. When used with other
date or time data, the result is always expressed as a date or a time. We can also
have a rich variety of numeric information ranging in size from Boolean values to
huge floating-point numbers. These different categories of information that can be
contained in a Variant are called subtypes. Most of the time, we can just put the
kind of data we want in a Variant, and the Variant behaves in a way that is most
appropriate for the data it contains.
The following table shows subtypes of data that a Variant can contain.
Subtype Description
Empty Variant is uninitialized. Value is 0 for numeric variables or a zero-
length string ("") for string variables.
Null Variant intentionally contains no valid data.
Boolean Contains either True or False.
Byte Contains integer in the range 0 to 255.
Integer Contains integer in the range -32,768 to 32,767.
Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Long Contains integer in the range -2,147,483,648 to 2,147,483,647.
50
Single Contains a single-precision, floating-point number in the range
-3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45
to 3.402823E38 for positive values.
Double Contains a double-precision, floating-point number in the range
-1.79769313486232E308 to -4.94065645841247E-324 for negative
values; 4.94065645841247E-324 to 1.79769313486232E308 for
positive values.
Date (Time) Contains a number that represents a date between January 1, 100
to December 31, 9999.
String Contains a variable-length string that can be up to approximately 2
billion characters in length.
Object Contains an object.
Error Contains an error number.
We can use conversion functions to convert data from one subtype to another. In
addition, the VarType function returns information about how your data is stored
within a Variant.
Operators are used for performing mathematical, comparison and logical operations.
When several operations occur in an expression, each part is evaluated and resolved
in a predetermined order called operator precedence.
We can use parentheses to override the order of precedence and force some parts of
an expression to be evaluated before others.
Operations within parentheses are always performed before those outside. Within
parentheses, however, standard operator precedence is maintained.
When expressions contain operators from more than one category, arithmetic
operators are evaluated first, comparison operators are evaluated next, and logical
operators are evaluated last.
Comparison operators all have equal precedence; that is, they are evaluated in the
left-to-right order in which they appear.
Arithmetic and logical operators are evaluated in the following order of precedence.
51
4.2 Arithmetic Operators:
Operator Description
1) Exponentiation Operator (^) Raises a number to the power of an exponent.
2) Multiplication Operator (*) Multiplies two numbers.
3) Division Operator (/) Divides two numbers and returns a floating-point result.
4) Integer Division Operator (\) Divides two numbers and returns an integer result.
5) Mod Operator Divides two numbers and returns only the remainder.
6) Addition Operator (+) Sums two numbers.
7) Subtraction Operator (-) Finds the difference between two numbers or indicates the
negative value of a numeric expression.
8) Concatenation Operator (&) Forces string concatenation of two expressions.
Operator Description
1) Addition Operator Sums two numbers.
(+)
If Then
1) Both expressions are numeric Add.
2) Both expressions are strings Concatenate.
3) One expression is numeric and Add.
the other is a string
2) Concatenation Forces string concatenation of two expressions.
Operator (&)
52
Operator Description Syntax
1) Not Performs logical negation on an result= Not expression
expression.
2) And Performs a logical conjunction on result= expression1 And
two expressions. expression2
3) Or Performs a logical disjunction on result= expression1 Or
two expressions. expression2
4) Xor Performs a logical exclusion on result= expression1 Xor
two expressions. expression2
5) Eqv result= expression1 Eqv
Performs a logical equivalence on
expression2
two expressions.
6) Imp result= expression1 Imp
Performs a logical implication on
expression2
two expressions.
6) Input/Output Operations
6.1 InputBox Function
Displays a prompt in a dialog box, waits for the user to input text or click a button,
and returns the contents of the text box.
Example:
Dim Input
Input = InputBox("Enter your name")
MsgBox ("You entered: " & Input)
Displays a message in a dialog box, waits for the user to click a button, and returns a
value indicating which button the user clicked.
Example:
Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
' MyVar contains either 1 or 2, depending on which button is clicked.
7) VB Script Constants
A constant is a meaningful name that takes the place of a number or string and
never changes.
We create user-defined constants in VBScript using the Const statement. Using the
Const statement, we can create string or numeric constants with meaningful names
and assign them literal values.
Const statement
53
Example:
Represent Date literals and time literals by enclosing them in number signs (#).
We declare multiple constants by separating each constant name and value with a
comma. For example:
8) Conditional Statements
We can control the flow of our script with conditional statements and looping
statements.
Using conditional statements, we can write VBScript code that makes decisions and
repeats actions. The following conditional statements are available in VBScript:
1) If…Then…Else Statement
Dim myDate
myDate = #2/13/98#
If myDate < Now Then myDate = Now
To run more than one line of code, we must use the multiple-line (or block) syntax.
This syntax includes the End If statement.
Dim x
x= 20
54
If x>10 Then
msgbox "Hello G.C.Reddy"
msgbox "x value is: "&x
msgbox "Bye Bye"
End If
Example:
Dim x
x= Inputbox (" Enter a value")
If x>100 Then
Msgbox "Hello G.C.Reddy"
Msgbox "X is a Big Number"
Msgbox "X value is: "&X
Else
Msgbox "GCR"
Msgbox "X is a Small Number"
Msgbox "X value is: "&X
End If
Example:
Dim x
x= Inputbox (" Enter a value")
55
Else
Msgbox "Hello Sir"
Msgbox "X is a Grand Number"
End If
End If
End If
Example:
End If
End If
End If
End If
Example:
Option explicit
Dim x,y, Operation, Result
x= Inputbox (" Enter x value")
y= Inputbox ("Enter y value")
Operation= Inputbox ("Enter an Operation")
Case "add"
Result= cdbl (x)+cdbl (y)
56
Msgbox "Hello G.C.Reddy"
Msgbox "Addition of x,y values is "&Result
Case "sub"
Result= x-y
Msgbox "Hello G.C.Reddy"
Msgbox "Substraction of x,y values is "&Result
Case "mul"
Result= x*y
Msgbox "Hello G.C.Reddy"
Msgbox "Multiplication of x,y values is "&Result
Case "div"
Result= x/y
Msgbox "Hello G.C.Reddy"
Msgbox "Division of x,y values is "&Result
Case "mod"
Result= x mod y
Msgbox "Hello G.C.Reddy"
Msgbox "Mod of x,y values is "&Result
Case "expo"
Result= x^y
Msgbox "Hello G.C.Reddy"
Msgbox"Exponentation of x,y values is "&Result
Case Else
Msgbox "Hello G.C.Reddy"
msgbox "Wrong Operation"
End Select
8.3.1 Write a program for finding out whether the given year is a leap year
or not?
Dim xyear
xyear=inputbox ("Enter Year")
8.3.2 Write a program for finding out whether the given number is, Even number or
Odd number?
Dim num
num=inputbox ("Enter a number")
57
If num mod 2=0 Then
msgbox "This is a Even Number"
Else
msgbox "This is a Odd Number"
End If
sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion
require
msgbox ("Sum is " &sum)
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)
8.3.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,rev
num= inputbox("Enter a number")
58
If len(num)=4 Then
8.3.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')
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"
59
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
Dim num,n
n=Inputbox ("Enter a Vaule")
For num= 1 to n step 2
msgbox num
Next
Dim num,n
n=Inputbox ("Enter a Vaule")
For num= 2 to n step 2
msgbox num
Next
Dim num,n
n=Inputbox ("Enter a Vaule")
For num=n to 1 step -1
msgbox num
Next
60
sum= sum+num
Next
msgbox sum
8.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")
61
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
8.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")
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
62
9) Looping Through Code
a) Do While condition
Statements
-----------
-----------
Loop
63
Example:
Dim x
Do While x<5 x=x+1
Msgbox "Hello G.C.Reddy"
Msgbox "Hello QTP"
Loop
b) Do
Statements
-----------
-----------
Loop While condition
Example:
Dim x
x=1
Do
Msgbox "Hello G.C.Reddy"
Msgbox "Hello QTP"
x=x+1
Loop While x<5
c) Do Until condition
Statements
-----------
-----------
Loop
Example:
Dim x
Do Until x=5 x=x+1
Msgbox "G.C.Reddy"
Msgbox "Hello QTP"
Loop
d) Do
Statements
-----------
-----------
Loop Until condition
64
Example:
Dim x
x=1
Do
Msgbox “Hello G.C.Reddy”
Msgbox "Hello QTP"
x=x+1
Loop Until x=5
Syntax:
While condition
Statements
-----------
-----------
Wend
Example:
Dim x
x=0
While x<5 x=x+1
msgbox "Hello G.C.Reddy"
msgbox "Hello QTP"
Wend
Syntax:
statements
Next
Example:
Dim x
For x= 1 to 5 step 1
Msgbox "Hello G.C.Reddy"
Next
65
9.4 For Each...Next Statement
Syntax:
Statements
Next
Example:
Dim a,b,x (3)
a=20
b=30
x(0)= "Addition is "& a+b
x(1)="Substraction is " & a-b
x(2)= "Multiplication is " & a*b
x(3)= "Division is " & a/b
Example:
MyArray = Array("one","two","three","four","five")
For Each element In MyArray
msgbox element
Next
In VBScript, there are two kinds of procedures; the Sub procedure and the
Function procedure.
A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub
statements) that perform actions but don't return a value.
A Sub procedure can take arguments (constants, variables, or expressions that are
passed by a calling procedure).
If a Sub procedure has no arguments, its Sub statement must include an empty set
of parentheses ().
Syntax:
66
Sub Procedure name ()
Statements
-----------
-----------
End Sub
Or
Statements
-----------
-----------
End Sub
Example: 1
Sub ConvertTemp()
MsgBox "The temperature is " & Celsius(temp) & " degrees C."
End Sub
Example: 2
A Function procedure is similar to a Sub procedure, but can also return a value.
67
Syntax:
Statements
-----------
-----------
End Function
Or
Statements
-----------
-----------
End Function
Example: 1
Function Celsius(fDegrees)
End Function
Example: 2
Function cal(a,b,c)
cal = (a+b+c)
End Function
11.3 Getting Data into and out of Procedures
68
11.4 Using Sub and Function Procedures in Code
A Function in our code must always be used on the right side of a variable
assignment or in an expression.
For example:
Temp = Celsius(fDegrees)
-Or-
MsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."
To call a Sub procedure from another procedure, type the name of the procedure
along with values for any required arguments, each separated by a comma.
The Call statement is not required, but if you do use it, you must enclose any
arguments in parentheses.
The following example shows two calls to the MyProc procedure. One uses the Call
statement in the code; the other doesn't. Both do exactly the same thing.
Notice that the parentheses are omitted in the call when the Call statement isn't
used.
69
11) VB Script Built in Functions
1) Asc Function
2) Chr Function
'Returns the character associated with the specified ANSI character code.
Dim val
val=65
val=Chr(val)
msgbox val 'Output: A
3) Date Function
It returns current system Date
Dim myDate
myDate=Date
msgbox myDate
70
4) Abs Function
It returns obsolute value of the given number.
Dim num
num=157.56
num=Abs(num)
msgbox num 'Output: 157.56
num=-157.56
num=Abs(num)
msgbox num 'Output: 157.56
5) Array Function
We can enter list of values using this function
Ex:
Dim var
'List of strings
var=Array("Hyderabad","Chennai", "Nellore")
msgbox var(0) 'output: Hyderabad
msgbox var(1) 'output: Chennai
msgbox var(2) 'output: Nellore
71
6) IsArray Function
x=isArray(var2)
msgbox x
7) IsDate
myDate="India"
x=IsDate(myDate)
msgbox x 'Output: False
myDate=#10/05/2010#
x=IsDate(myDate)
msgbox x 'Output: True
myDate=#10-05-2010#
x=IsDate(myDate)
msgbox x 'Output: True
myDate=#10-05-10#
x=IsDate(myDate)
72
msgbox x 'Output: True
myDate=10-05-2010
x=IsDate(myDate)
msgbox x 'Output: False
8) DateDiff Function
9) IsNumeric
It checks weather the given value is numeric or not and It provides True/False like
Result
Example:
Dim val,x
val="100"
x=Isnumeric(val)
msgbox x 'Output: True
val=100
x=Isnumeric(val)
msgbox x 'Output: True
73
x=Isnumeric(500)
msgbox x 'Output: True
x=Isnumeric("India")
msgbox x 'Output: False
val=100
x=Len(val)
msgbox x 'Output: 3
val="Hydera100"
x=Len(val)
msgbox x 'Output: 9
val="hy$@*de"
x=Len(val)
msgbox x 'Output: 7
val="100"
x=Len(val)
msgbox x 'Output: 3
val=#10-10-2010#
x=Len(val)
msgbox x 'Output: 10
x=Len("Krishna")
74
msgbox x 'Output: 7
x=Len(Krishna)
msgbox x 'Output: 0
x=Len()
msgbox x 'Output: Error
val="9247837478"
x=Left(val,1)
msgbox x ' Output: 9
val="H92yderabad"
x=Left(val,3)
msgbox x ' Output: H92
x=Left(9247837478,5)
msgbox x ' Output: 92478
val=#10-10-10#
x=Left(val,3)
msgbox x ' Output: 10/
75
12) Right Function
Returns a specified number of charectors of a given string from Right side
Example:
Dim val,x
val="Hyderabad"
x=Right(val,3)
msgbox x ' Output: bad
val="9247837478"
x=Right(val,1)
msgbox x ' Output: 8
val="H92yderabad"
x=Right(val,3)
msgbox x ' Output: bad
76
x=Right(9247837478,5)
msgbox x ' Output: 37478
val=#10-10-10#
x=Right(val,5)
msgbox x ' Output: /2010
val="Hyderabad"
x=Mid(Val,5)
msgbox x ' Output: rabad
val="9247837478"
x=Mid(val,6,5)
msgbox x ' Output: 37478
val="H92yderabad"
x=Mid(val,1)
msgbox x ' Output: H92yderabad
x=Mid(9247837478,5)
msgbox x ' Output: 837478
val=#10-10-10#
x=Mid(val,5)
msgbox x ' Output: 0/2010
14) StrReverse
77
retuns reverse value of a string
Example:
Dim val,x
val="Hyderabad"
x=StrReverse(val)
msgbox x 'Output dabaredyH
val="001"
x=StrReverse(val)
msgbox x 'Output: 100
val=1002
x=StrReverse(val)
msgbox x 'Output: 2001
val=#10-10-10#
x=StrReverse(val)
msgbox x 'Output: 0102/01/01
x=StrReverse("Hyderabad")
msgbox x 'Output: dabaredyH
x=StrReverse(100)
msgbox x 'Output: 001
78
Dim str1,str2,x
str1="India"
str2="India"
x=StrComp(str1,str2,1)
msgbox x 'Output 0
str1="india"
str2="INDIA"
x=StrComp(str1,str2,1)
msgbox x 'Output 0
str1="India"
str2="Indian"
x=StrComp(str1,str2,1)
msgbox x 'Output -1
str1="Indian"
str2="Ndia"
x=StrComp(str1,str2,1)
msgbox x 'Output -1
str1="Indian"
str2="India"
x=StrComp(str1,str2,1)
msgbox x 'Output 1
str1=100
str2=100
x=StrComp(str1,str2,1)
msgbox x 'Output 0
str1=100
str2=101
x=StrComp(str1,str2,1)
msgbox x 'Output -1
79
16) Lcase function
Coverts Upper case values into Lower case
Dim val,x
val="HYDERABAD"
x=Lcase(val)
msgbox x 'Output hyderabad
val="Hyderabad"
x=Lcase(val)
msgbox x 'Output hyderabad
val="HederabaD"
x=Lcase(val)
msgbox x 'Output hyderabad
val="hyderabad"
x=Lcase(val)
msgbox x 'Output hyderabad
x=Lcase("HYDERABAD")
msgbox x 'Output hyderabad
Dim val,x
val="HYDERABAD"
x=Ucase(val)
msgbox x 'Output HYDERABAD
val="Hyderabad"
x=Ucase(val)
msgbox x 'Output HYDERABAD
80
val="HyderabaD"
x=Ucase(val)
msgbox x 'Output HYDERABAD
val="hyderabad"
x=Ucase(val)
msgbox x 'Output HYDERABAD
x=Ucase("HYDERABAD")
msgbox x 'Output HYDERABAD
num=14.59
x=Round(num)
msgbox x 'Output: 15
num="14.49"
x=Round(num)
msgbox x 'Output: 14
num="Hyd"
x=Round(num)
msgbox x 'Output: Error
81
val=" VB Script"
x=Trim(val)
msgbox x
x=Len(x)
msgbox x
val=" 100"
x=Trim(val)
msgbox x
x=Len(x)
msgbox x
val=" 2#$%^"
x=Trim(val)
msgbox x
x=Len(x)
msgbox x
val="100 "
x=LTrim(val)
msgbox x
82
x=Len(x)
msgbox x
val= 100
x=LTrim(val)
msgbox x
x=Len(x)
msgbox x
21) Rtrim
It removes spaces from right side of a string
Dim val
val="VB Script "
x=RTrim(val)
msgbox x
x=Len(x)
msgbox x
83
val=" 2#$%^ "
x=RTrim(val)
msgbox x
x=Len(x)
msgbox x
val= 100
x=RTrim(val)
msgbox x
x=Len(x)
msgbox x
84
msgbox a(5) 'Output: Scripting
b="VB@Script@is@a@Powerful@scripting@Language"
a=Split(b,"@")
msgbox a(5) 'Output: Scripting
b="VBScriptisaPowerfulscriptingLanguage"
a=Split(b)
msgbox a(5) 'Output: Error
21.1 Case-sensitivity:
By default, VBScript is not case sensitive and does not differentiate between upper-
case and lower-case spelling of words, for example, in variables, object and method
names, or constants.
When we enter a value as a text string, we must add quotation marks before and
after the string. For example, in the above segment of script, the names of the Web
site, Web page, and edit box are all text strings surrounded by quotation marks.
Note that the value 31 is also surrounded by quotation marks, because it is a text
string that represents a number and not a numeric value.
In the following example, only the property name (first argument) is a text string
and is in quotation marks. The second argument (the value of the property) is a
variable and therefore does not have quotation marks. The third argument
(specifying the timeout) is a numeric value, which also does not need quotation
marks.
21.3 Variables:
We can specify variables to store strings, integers, arrays and objects. Using
variables helps to make our script more readable and flexible
21.4 Parentheses:
To achieve the desired result and to avoid errors, it is important that we use
parentheses () correctly in our statements.
21.5 Indentation:
85
We can indent or outdent our script to reflect the logical structure and nesting of the
statements.
21.6 Comments:
We can add comments to our statements using an apostrophe ('), either at the
beginning of a separate line, or at the end of a statement. It is recommended that
we add comments wherever possible, to make our scripts easier to understand and
maintain.
21.7 Spaces:
We can add extra blank spaces to our script to improve clarity. These spaces are
ignored by VBScript.
13) Errors
We have two types Errors in VB Script; they are VBScript Run-time Errors and
VBScript Syntax Errors
VBScript run-time errors are errors that result when our VBScript script attempts to
perform an action that the system cannot execute. VBScript run-time errors occur
while our script is being executed; when variable expressions are being evaluated,
and memory is being dynamic allocated.
The File System Object (FSO) model provides an object-based tool for working with
folders and files. It allows us to use the familiar object. method syntax with a rich set
of properties, methods, and events to process folders and files. We can also employ
the traditional Visual Basic statements and commands.
The FSO model gives our application the ability to create, alter, move, and delete
folders, or to determine if and where particular folders exist. It also enables us to get
information about folders, such as their names and the date they were created or
last modified.
The FSO model makes processing files much easier as well. When processing files,
our primary goal is to store data in an efficient, easy-to-access format. We need to
be able to create files, insert and change the data, and output (read) the data.
Although we can store data in a database, doing so adds a significant amount of
overhead to our application. We may not want to have such overhead, or our data
access requirements may not call for the extra functionality associated with a full-
featured database. In this case, storing our data in a text file or binary file is the
most efficient solution.
The FSO model, contained in the Scripting type library (Scrrun.dll), supports the
creation and manipulation of text files through the TextStream object; however, the
FSO model does not support binary files. To manipulate binary files, use the FileOpen
Function with the Binary keyword.
Examples
1) Create a Folder
Option Explicit
Dim objFSO, objFolder, strDirectory
strDirectory = "D:\Pavan"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.CreateFolder(strDirectory)
2) Delete a Folder
3) Copying Folders
Set oFSO=createobject("Scripting.Filesystemobject")
oFSO.CopyFolder "E:\gcr", "C:\jvr", True
4) Checking weather the folder available or not, if not creating the folder
Option Explicit
Dim objFSO, objFolder, strDirectory
87
strDirectory = "D:\Pavan"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
msgbox strDirectory & " already created "
else
Set objFolder = objFSO.CreateFolder(strDirectory)
end if
8) Checking weather the File is available or not, if not creating the File
strDirectory="E:\"
strFile="Pavan.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile("E:\Pavan.txt")
End if
88
10) Reading Data line by line from a Flat File
11) Reading data from a flat file and using in data driven testing
Dim fso,myfile
Set fso=createobject("scripting.filesystemobject")
Set myfile= fso.opentextfile ("F:\Pavan.txt",1)
myfile.skipline
While myfile.atendofline <> True
x=myfile.readline
s=split (x, ",")
Set objFSO=createobject("Scripting.filesystemobject")
Set txtFilepath = objFSO.GetFile("E:\gcr.txt")
txtFilepath.Delete()
14) Checking weather the File is available or not, if available delete the File
strDirectory="E:\"
strFile="gcr.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strDirectory & strFile) Then
89
Set objFile = objFSO.Getfile(strDirectory & strFile)
objFile.delete ()
End if
Dim f1, f2
f1="e:\Pavan1.txt"
f2="e:\Pavan2.txt"
Public Function CompareFiles (FilePath1, FilePath2)
Dim FS, File1, File2
Set FS = CreateObject("Scripting.FileSystemObject")
If FS.GetFile(FilePath1).Size <> FS.GetFile(FilePath2).Size Then
CompareFiles = True
Exit Function
End If
Set File1 = FS.GetFile(FilePath1).OpenAsTextStream(1, 0)
Set File2 = FS.GetFile(FilePath2).OpenAsTextStream(1, 0)
CompareFiles = False
Do While File1.AtEndOfStream = False
Str1 = File1.Read
Str2 = File2.Read
CompareFiles = StrComp(Str1, Str2, 0)
If CompareFiles <> 0 Then
CompareFiles = True
Exit Do
End If
Loop
File1.Close()
File2.Close()
End Function
Call Comparefiles(f1,f2)
If CompareFiles(f1, f2) = False Then
MsgBox "Files are identical."
Else
MsgBox "Files are different."
End If
sFileName="E:\gcr.txt"
sString="pavan"
Const FOR_READING = 1
Dim oFso, oTxtFile, sReadTxt, oRegEx, oMatches
Set oFso = CreateObject("Scripting.FileSystemObject")
Set oTxtFile = oFso.OpenTextFile(sFileName, FOR_READING)
sReadTxt = oTxtFile.ReadAll
Set oRegEx = New RegExp
oRegEx.Pattern = sString
oRegEx.IgnoreCase = bIgnoreCase
oRegEx.Global = True
Set oMatches = oRegEx.Execute(sReadTxt)
MatchesFound = oMatches.Count
90
Set oTxtFile = Nothing : Set oFso = Nothing : Set oRegEx = Nothing
msgbox MatchesFound
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001
strPathtoTextFile = "C:\Databases\"
Do Until objRecordset.EOF
Wscript.Echo "Name: " & objRecordset.Fields.Item("Name")
Wscript.Echo "Department: " & _
objRecordset.Fields.Item("Department")
Wscript.Echo "Extension: " & objRecordset.Fields.Item("Extension")
objRecordset.MoveNext
Loop
Const ForReading = 1
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
arrServiceList = Split(strNextLine , ",")
Wscript.Echo "Server name: " & arrServiceList(0)
For i = 1 to Ubound(arrServiceList)
Wscript.Echo "Service: " & arrServiceList(i)
Next
Loop
91
Excel File Operations
1) Create an Excel file, enter some data and save the file through VB
scripting?
1) Dim objexcel
2) Set objExcel = createobject("Excel.application")
3) objexcel.Visible = True
4) objexcel.Workbooks.add
5) objexcel.Cells(1, 1).Value = "Testing"
6) objexcel.ActiveWorkbook.SaveAs("f:\exceltest.xls")
7) objexcel.Quit
1) Set myExcel=Createobject("Excel.Application")
2) Set myFile=myExcel.workbooks.open ("C:\Documents and Settings\admin\My
Documents\pavan.xls")
3) Set mySheet=myFile.worksheets("Sheet1")
4) Rows_Count=mySheet.usedrange.rows.count
5) For i= 1 to Rows_Count
6) Agent=mySheet.cells(i,"A")
7) pwd=mySheet.Cells(i,"B")
8) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest
Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury
Interactive\QuickTest Professional\samples\flight\app\","open"
9) Dialog("Login").Activate
10) Dialog("Login").WinEdit("Agent Name:").Set Agent
11) Dialog("Login").WinEdit("Password:").SetSecure pwd
12) Dialog("Login").WinEdit("Password:").Type micReturn
13) Window("Flight Reservation").Close
14) Next
92
objExcel.quit
set objExcel=nothing
Datatable.AddSheet "pavan"
Datatable.ImportSheet "C:\Documents and
Settings\Administrator\Desktop\pavan.xls",1,3
n=datatable.GetSheet (3).GetRowCount
For i= 1 to n
Datatable.SetCurrentRow(i)
Invokeapplication "C:\Program Files\HP\QuickTest
Professional\samples\flight\app\flight4a.exe"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set datatable("agent",3)
Dialog("Login").WinEdit("Password:").Set datatable("pwd",3)
Dialog("Login").WinButton("OK").Click
Window("Flight Reservation").Close
Next
Example 2):
Datatable.AddSheet "pavan"
Datatable.ImportSheet "C:\Documents and
Settings\Administrator\Desktop\pavan.xls",1,3
n=datatable.GetSheet (3).GetRowCount
For i= 1 to n
Datatable.SetCurrentRow(i)
VbWindow("Form1").Activate
VbWindow("Form1").VbEdit("val1").Set datatable("V1",3)
VbWindow("Form1").VbEdit("val2").Set datatable("V2",3)
VbWindow("Form1").VbButton("ADD").Click
eres= Datatable.Value ("res",3)
ares=VbWindow("Form1").VbEdit("res").GetROProperty ("text")
If eres=ares Then
datatable("res",3)=pass
else
datatable("res",3)=fail
End If
Next
93
("C:\Scripts\New_users.xls")
intRow = 2
objExcel.Quit
objExcel.Visible = True
objExcel.Workbooks.Add
objExcel.Cells(1, 1).Value = "Test value"
objExcel.Cells(1, 1).Font.Bold = TRUE
objExcel.Cells(1, 1).Font.Size = 24
objExcel.Cells(1, 1).Font.ColorIndex = 3
Const xlAscending = 1
Const xlDescending = 2
Const xlYes = 1
objRange.Sort objRange2,xlAscending,objRange3,,xlDescending, _
objRange4,xlDescending,xlYes
94
Database Operations
ADO (Active Data Objects), this technology allows users to access data easily from
many existing databases (such as Access or Paradox) or from ODBC compliant
databases like Oracle or MS SQL Server. Using ADO is quite simple and allows
programmers to provide flexible database front ends to users that are reliable and
include many features.
Following are some of the key objects found in the ADO object model and some of
their key methods and properties.
Connection Object
This object represents an open connection to the data source. This connection can be
a local connection (say App.Path) or can be across a network in a client server
application. Some of the methods and properties of this object are not available
depending on the type of data source connected to.
Command Object
A command object specifies a specific method we intend to execute on or against the
data source accessed by an open connection.
RecordSet Object
Examples
1) Get Test Data from a Database and use in Data Driven Testing (through
Scripting)
1) Dim con,rs
2) Set con=createobject("Adodb.connection")
3) Set rs=createobject("Adodb.recordset")
4) con.provider=("microsoft.jet.oledb.4.0")
5) con.open "C:\Documents and Settings\Administrator\My Documents\Pavan.mdb"
6) rs.open "Select * From Login",con
7) While rs.eof <>True
8) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest
Professional\samples\flight\app\flight4a.exe"
9) Dialog("Login").Activate
10) Dialog("Login").WinEdit("Agent Name:").Set rs.fields ("Agent")
11) Dialog("Login").WinEdit("Password:").Set rs.fields ("Password")
12) Dialog("Login").WinButton("OK").Click
13) Window("Flight Reservation").Close
14) rs.movenext
15) Wend
95
2) Exporting Data from a Database to an Excel Sheet
1) Dim con,rs
2) Set con=createobject("adodb.connection")
3) Set rs=createobject("adodb.recordset")
4) con.provider="microsoft.jet.oledb.4.0"
5) con.open"C:\Documents and Settings\admin\My Documents\Pavan.mdb"
6) rs.open"select*from Login",con
7) Set ex=createobject("Excel.Application")
8) Set a=ex.workbooks.open("C:\Documents and Settings\admin\My
Documents\Pavan.xls")
9) Set b=a.worksheets("sheet1")
10) i=1
11) Do While Not rs.EOF
12) b.cells (i,1).value=rs.fields("agent")
13) b.cells(i,2).value=rs.fields("password")
14) rs.movenext
15) i=i+1
16) Loop
17) a.save
18) a.close
Const adOpenStatic = 3
Const adLockOptimistic = 3
96
objConnection.Open _
"Provider=SQLOLEDB;Data Source=atl-sql-01;" & _
"Trusted_Connection=Yes;Initial Catalog=Northwind;" & _
"User ID=fabrikam\kenmyer;Password=34DE6t4G!;"
objRecordSet.MoveFirst
Wscript.Echo objRecordSet.RecordCount
Const adOpenStatic = 3
Const adLockOptimistic = 3
objConnection.Open _
"Northwind;fabrikam\kenmyer;34ghfn&!j"
objRecordSet.MoveFirst
Wscript.Echo objRecordSet.RecordCount
Const adOpenStatic = 3
Const adLockOptimistic = 3
objConnection.Open _
"Provider= Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=inventory.mdb"
objRecordSet.MoveFirst
97
objRecordSet2.Open "SELECT * FROM Storage Where ComputerName =
'Computer1'", _
objConnection, adOpenStatic, adLockOptimistic
objRecordSet2.MoveFirst
Do Until objRecordset.EOF
Wscript.Echo objRecordset.Fields.Item("ComputerName")
Wscript.Echo objRecordset.Fields.Item("OSName")
objRecordSet.MoveNext
Loop
Do Until objRecordset2.EOF
Wscript.Echo objRecordset2.Fields.Item("DriveName"), _
objRecordset2.Fields.Item("DriveDescription")
objRecordSet2.MoveNext
Loop
objRecordSet.Close
objRecordSet2.Close
objConnection.Close
Const adOpenStatic = 3
Const adLockOptimistic = 3
objConnection.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source = eventlogs.mdb"
objRecordSet.MoveFirst
objRecordSet.Close
objConnection.Close
Dim objCon,objCom
Set objCon=Createobject("ADODB.connection")
objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\pavan.mdb;"
98
Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon
objCon.Close
Set objCom=Nothing
Set objCon=Nothing
9) Insert multiple sets of Data (using Excel sheet) into a database table
using Database Command Object
Dim objCon,objCom,strEmpName,intEmpNo,intEmpSal,intRowcount,i
Set objCon=Createobject("ADODB.connection")
objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\pavan.mdb;"
Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon
Datatable.AddSheet("input")
Datatable.ImportSheet "C:\pavan.xls",1,"input"
intRowcount=Datatable.GetSheet("input").GetRowCount
Msgbox intRowcount
For i=1 to intRowcount step 1
DataTable.SetCurrentRow(i)
strEmpName= DataTable.Value(1,"input")
intEmpNo= DataTable.Value(2,"input")
intEmpSal= DataTable.Value(3,"input")
objCom.CommandText="insert into Emp values( '"&strEmpName&"
',"&intEmpNo&","&intEmpSal&")"
objCom.Execute
Next
objCon.Close
Set objCom=Nothing
Set objCon=Nothing
99
Overview:
Generally for every object 20-25 properties information available, qtp recognizes
object using 2 0r 3 important properties.
Qtp has default object identification configuration for every environment, if we feel
that configuration is not sufficient for recognizing objects in our application, we can
configure some more
a) Normal identification
1) Mandatory properties
2) Assistive properties
b) Smart identification
c) Ordinal identifier
1) location
2) index
3) creation time(only for web)
First of all the qtp learns all the mandatory properties at a time and thinks whether
these properties sufficient to identify the object uniquely. if it feels sufficient then it
stops learning otherwise,
It learns first assistive property and once again stops and thinks, like this qtp learns
one by one. At the end of assistive properties list also if it feels not satisfied and it
finally goes to Ordinal Identifier.
After normal identification if qtp feels not satisfied then it goes to smart
identification. in smart identification 2 types of properties available, first qtp learns
all base filter properties at a time and thinks whether these properties are sufficient
for identifying the object uniquely. If it feels sufficient, then it stops learning
otherwise it goes Optional Filter Properties and learns one by one. Still it feels not
satisfied finally it goes to Ordinal Identifier.
Ordinal identifiers:
10
There are 3 types of ordinal identifiers available
1) Location: is based on object location in the AUT ,location starts from zero.
3) Creation time: it is based on loading time of the web objects. qtp generates 0,1,2
like numbers.
For making tool settings global, QTP is providing a special feature called "Generate
Script".
STEPS:
a) File->Settings
b) Tools->Options
c) Tools->Object Identification
3) Share Script files to team members and ask them to execute those scripts.
NOTE: After executing these scripts all team members can get same settings.
10
What is Regular Expression?
It is a way of representing data using symbols. They are often used within
matching, searching or replacing algorithms.
Regular expressions can be used in QTP for identifying objects and text strings with
varying values.
Where we use:
We can define a regular expression for a constant value, a Data Table parameter
value, an Environment parameter value, or a property value in Descriptive
programming.
We can define the text string as a regular expression, when creating a text
checkpoint to check that a varying text string is displayed on our application,
For XML checkpoints we can set attribute or element values as regular expressions.
a) Backslash Character:
A backslash (\) can serve two purposes. It can be used in conjunction with a special
character to indicate that the next character be treated as a literal character.
Alternatively, if the backslash (\) is used in conjunction with some characters that
would otherwise be treated as literal characters, such as the letters n, t, w, or d, the
combination indicates a special character.
A period (.) instructs QTP to search for any single character (except for \n).
10
Ex:
welcome.
Matches welcomes, welcomed, or welcome followed by a space or any other single
character.
Square brackets instruct QTP to search for any single character within a list of
characters.
Ex:
To search for the date 1867, 1868, or 1869, enter:
186[789]
When a caret (^) is the first character inside square brackets, it instructs QTP to
match any character in the list except for the ones specified in the string.
Example:
[^ab]
Matches any character except a or b.
To match a single character within a range, we can use square brackets ([ ]) with
the hyphen (-) character.
Example:
For matching any year in the 2010s, enter:
201[0-9]
An asterisk (*) instructs QTP to match zero or more occurrences of the preceding
character.
For example:
ca*r
10
A plus sign (+) instructs QTP to match one or more occurrences of the preceding
character.
For example:
ca+r
Matches car and caaaaaar, but not cr.
A question mark (?) instructs QTP to match zero or one occurrences of the preceding
character.
For example:
ca?r
Matches car and cr, but nothing else.
Parentheses (()) instruct QTP to treat the contained sequence as a unit, just as in
mathematics and programming languages. Using groups is especially useful for
delimiting the argument(s) to an alternation operator ( | ) or a repetition operator
( * , + , ? , { } ).
A caret (^) instructs QTP to match the expression only at the start of a line, or after
a newline character.
A dollar sign ($) instructs QTP to match the expression only at the end of a line, or
before a newline character.
\w instructs QTP to match any alphanumeric character and the underscore (A-Z, a-
z, 0-9, _).
10
\W instructs QTP to match any character other than alphanumeric characters and
underscores.
RegExp object
Properties:
a) Global Property
b) IgnoreCase Property
c) Pattern Property
Methods:
a) Execute Method
b) Replace Method
c) Test Method
10
Regular Expressions Examples:
--------------------------------------------------
Batch Testing
10
Batch Execution.
For performing Batch Testing, QTP has provided a separate Tool called 'Test Batch
Runner'.
Note: Test Batch Runner launches QTP Tool, QTP runs Tests one by one.
Open Test Batch Runner >open Test Batch>Select or deselect tests>run test batch.
10
1) Dictionary Object
Add Method
Exists Method
Returns true if a specified key exists in the Dictionary object, false if it does not.
Items Method
Keys Method
Remove Method
RemoveAll Method
The RemoveAll method removes all key, item pairs from a Dictionary object.
Example:
Dim cities
Set cities = CreateObject("Scripting.Dictionary")
cities.Add "h", "Hyderabad"
cities.Add "b", "Bangalore"
cities.Add "c", "Chennai"
10
Returns the number of items in a collection or Dictionary object. Read-only.
CompareMode Property
Sets and returns the comparison mode for comparing string keys in a Dictionary
object.
Key Property
Item Property
Sets or returns an item for a specified key in a Dictionary object. For collections,
returns an item based on the specified key. Read/write.
Examples:
Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.Add "Printer 1", "Printing"
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.Add "Printer 1", "Printing"
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
colKeys = objDictionary.Keys
Wscript.Echo "First run: "
For Each strKey in colKeys
Wscript.Echo strKey
Next
objDictionary.RemoveAll
colKeys = objDictionary.Keys
Wscript.Echo VbCrLf & "Second run: "
For Each strKey in colKeys
Wscript.Echo strKey
Next
10
3) Delete One Element from a Dictionary
colKeys = objDictionary.Keys
Wscript.Echo strKey
Next
objDictionary.Remove("Printer 2")
colKeys = objDictionary.Keys
Wscript.Echo strKey
Next
Set objDictionary = CreateObject("Scripting.Dictionary")
11
objDictionary.Add "Printer 1", "Printing"
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
Wscript.Echo objDictionary.Count
Else
End If
2) RegExp object
Properties:
a) Global Property
b) IgnoreCase Property
c) Pattern Property
Methods:
a) Execute Method
b) Replace Method
c) Test Method
11
1) Match File Names in a Directory against Regular Expression
strCurrentDirectory = objShell.CurrentDirectory
objRE.Global = True
objRE.IgnoreCase = False
objRE.Pattern = WScript.Arguments(0)
bMatch = objRE.Test(objFile.Name)
If bMatch Then
WScript.Echo objFile.Name
End If
Next
strFileName = "E:\pavan.txt"
11
Set objTS = objFS.OpenTextFile(strFileName)
strFileContents = objTS.ReadAll
WScript.Echo strFileContents
objTS.Close
objRE.Global = True
objRE.IgnoreCase = False
objRE.Pattern = WScript.Arguments(0)
WScript.Echo "At position " & objMatch.FirstIndex & " matched " & objMatch.Value
Next
Dim objCon,objCom
Set objCon=Createobject("ADODB.connection")
objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\pavan.mdb;"
Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon
objCon.Close
11
Set objCom=Nothing
Set objCon=Nothing
2) Insert multiple sets of Data (using Excel sheet) into a database table
using Database Command Object
Dim objCon,objCom,strEmpName,intEmpNo,intEmpSal,intRowcount,i
Set objCon=Createobject("ADODB.connection")
objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\pavan.mdb;"
Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon
Datatable.AddSheet("input")
Datatable.ImportSheet "C:\pavan.xls",1,"input"
intRowcount=Datatable.GetSheet("input").GetRowCount
Msgbox intRowcount
For i=1 to intRowcount step 1
DataTable.SetCurrentRow(i)
strEmpName= DataTable.Value(1,"input")
intEmpNo= DataTable.Value(2,"input")
intEmpSal= DataTable.Value(3,"input")
objCom.CommandText="insert into Emp values( '"&strEmpName&"
',"&intEmpNo&","&intEmpSal&")"
objCom.Execute
Next
objCon.Close
Set objCom=Nothing
Set objCon=Nothing
4) Word Object
dim mw
set mw=CreateObject("Word.Application")
mw.Documents.Add
mw.selection.typetext "hello"
mw.ActiveDocument.SaveAs "e:\pavan.doc"
mw.quit
set mw=nothing
2) Create Script to get the list of links in Google and do spell check
Dim d
set mw=CreateObject("Word.Application")
11
set d=Description.Create
d("micclass").value="Link"
set a=Browser("Google").page("Google").childobjects(d)
mw.WordBasic.filenew
s=a(i).getROProperty("innertext")
mw.WordBasic.insert s
if mw.ActiveDocument.Spellingerrors.count>0 then
end if
mw.ActiveDocument.Close(False)
next
mw.quit
set mw=nothing
3) Script to display all the doc files in all the drives in the system
Dim mw
Set mw=CreateObject("Word.Application")
Set fs=createobject("Scripting.FileSystemObject")
Set d=fs.Drives
mw.FileSearch.FileName="*.doc"
For each dr in d
msgbox dr
mw.FileSearch.LookIn=dr
mw.FileSearch.SearchSubFolders=True
mw.FileSearch.Execute
For each i in mw.FileSearch.FoundFiles
print i
Set f=fs.GetFile(i)
print f.Name&" "&f.Size&" "&f.DateCreated
print "-------------------------------------------------------------------"
Next
Next
mw.Quit
11
5) IE Object
Dim ie
Set ie=CreateObject("InternetExplorer.Application")
ie.Visible=True
ie.Navigate "www.yahoomail.com"
x=Browser("CreationTime:=0").GetROProperty("title")
msgbox x
Automation Framework
Automation:
Automation Framework:
Or
In one project test automation we use various files, we perform various tasks, in
order to organize and manage them all, a systematic approach (Automation
Framework) required.
Files to be used:
11
e) Library files (.vbs/.qfl)
Tasks to be performed:
j) Analyzing results
k) Test reporting
m) Modifying tests
Automation Framework is not a qtp feature, it’s a 3rd party concept. And this is
purely local concept.(framework may vary from one company to another)
11
batches and executing tests.
Advantages:
Drawbacks:
Advantages:
Drawbacks:
5. Hybrid Framework
In the above frameworks Keyword Driven framework is very famous in the industry.
It is a mixing of more than one approach.
In this approach,we mix Data driven and Modular approaches OR Data Driven and
Keyword Driven approaches---etc
Advantages:
Scope is very high as we mix different approaches,Flexible for performing any tasks.
Drawbacks:
11
NOTE: Now a days Mix of Data driven and Keyword driven approaches is a famous
Hybrid Framework in the industry.
Keyword:
c) Methods (Ex:Set,Select,Activate,Navigate---etc)
d) Statements (EX:Dim,If,For---etc)
In this approach we use keywords for preparing tests. First we create tests and make
them as functions, through framework we execute them and generate results.
In order to create, store, organize and manage files a well defined folder structure
required. Folder structure is a mandatory element of any framework, but folder
names may vary from one framework to another and company to another .
Folder Structure:
1. Object Repository
2. Environment
3. Library
11
a) Company
b) Project Specific
4. Test data
5. Test log
6. Recovery scenarios
7. Miscellaneous
And
1) Object Repository: In this folder we store object repository files(.tsr), all team
members can use this repositories.
3) Function Library:this folder contains two sub folders one is for storing common
functions of our company, another folder for storing our project specific
functions(.vbs).
4) Test Data: in this folder we store test data required for data driven testing, for
that we use either .xls files or .txt files or .mdb files.
7) Miscellaneous: in this folder we store the files other than above files(ex-process
guideline doc and messages among team members and instructions by team lead
etc).
And
1) Initialization script (.vbs file): It launches qtp tool and calls driver script, at end
it closes qtp tool.
2) Driver script (QTP Script file): It is only the qtp script, we can associate all
resources to this script
QTP Add-Ins Information
Object Description
Desktop An object that enables you to access top-level
12
items on your desktop.
Dialog A Windows dialog box.
Static A static text object.
An object used to control applications and
SystemUtil
processes during a run session.
WinButton A Windows button.
WinCalendar A Windows calendar.
WinCheckBox A Windows check box.
WinComboBox A Windows combo box.
Window A standard window.
WinEdit A Windows edit box.
WinEditor A Windows multi-line editor.
WinList A Windows list.
WinListView A Windows list-view control.
WinMenu A Windows menu.
WinObject A standard (Windows) object.
WinRadioButton A Windows radio button.
WinScrollBar A Windows scroll bar.
WinSpin A Windows spin box.
WinStatusBar A Windows status bar.
WinTab A Windows tab strip in a dialog box.
WinToolbar A Windows toolbar.
WinTreeView A Windows tree-view control.
Stingray Environment
Object Description
WinTab A Windows tab strip in a dialog box.
WinTable A Stingray grid.
WinToolbar A Windows toolbar.
WinTreeView A Stingray tree control.
Web Environment
Object Description
Browser A Web browser (or browser tab).
Frame An HTML frame.
Image An image with or without a target URL link.
12
Link A hypertext link.
Page An HTML page.
ViewLink A Viewlink object.
A section of an image (usually a section of a
WebArea
client-side image map).
WebButton An HTML button.
WebCheckBox A check box with an ON and OFF state.
WebEdit An edit box, usually contained inside a form.
A general Web object that can represent any Web
WebElement
object.
An edit box with a browse button attached, used
WebFile
to select a file from the File dialog box.
WebList A drop-down box or multiple selection list.
A set of radio buttons belonging to the same
WebRadioGroup
group.
A table containing a variable number of rows and
WebTable
columns.
WebXML An XML document contained in a Web page.
Object Description
An object that supports attachment-related test
Attachments
object operations.
An object that supports configuration-related test
Configuration
object operations.
An object that supports header-related test
headers
object operations.
An object that supports security-related test
Security
object operations.
WebService A test object representing a Web service.
WSUtil A utility object used to check WSDL files.
VBScript Glossary
ActiveX control
12
An object that you place on a form to enable or enhance a user's interaction
with an application. ActiveX controls have events and can be incorporated into
other controls. The controls have an .ocx file name extension.
ActiveX object
An object that is exposed to other applications or programming tools through
Automation interfaces.
Argument
A constant, variable, or expression passed to a procedure.
Array
A set of sequentially indexed elements having the same type of data. Each
element of an array has a unique identifying index number. Changes made to
one element of an array do not affect the other elements.
Automation object
An object that is exposed to other applications or programming tools through
Automation interfaces.
Bitwise comparison
A bit-by-bit comparison of identically positioned bits in two numeric
expressions.
Boolean expression
An expression that evaluates to either True or False.
By reference
A way of passing the address, rather than the value, of an argument to a
procedure. This allows the procedure to access the actual variable. As a
result, the variable's actual value can be changed by the procedure to which it
is passed.
By value
A way of passing the value, rather than the address, of an argument to a
procedure. This allows the procedure to access a copy of the variable. As a
result, the variable's actual value can't be changed by the procedure to which
it is passed.
12
character code
A number that represents a particular character in a set, such as the ASCII
character set.
Class
The formal definition of an object. The class acts as the template from which
an instance of an object is created at run time. The class defines the
properties of the object and the methods used to control the object's
behavior.
Class module
A module containing the definition of a class (its property and method
definitions).
Collection
An object that contains a set of related objects. An object's position in the
collection can change whenever a change occurs in the collection; therefore,
the position of any specific object in the collection may vary.
Comment
Text added to code by a programmer that explains how the code works. In
Visual Basic Scripting Edition, a comment line generally starts with an
apostrophe ('), or you can use the keyword Rem followed by a space.
Comparison operator
A character or symbol indicating a relationship between two or more values or
expressions. These operators include less than (<), less than or equal to
(<=), greater than (>), greater than or equal to (>=), not equal (<>), and
equal (=).
Constant
A named item that retains a constant value throughout the execution of a
program. Constants can be used anywhere in your code in place of actual
values. A constant can be a string or numeric literal, another constant, or any
combination that includes arithmetic or logical operators except Is and
exponentiation. For example:
Const A = "MyString"
Data ranges
Each Variant subtype has a specific range of allowed values:
12
Sub Range
typ
e
Byt 0 to 255.
e
Date expression
Any expression that can be interpreted as a date. This includes any
combination of date literals, numbers that look like dates, strings that look
like dates, and dates returned from functions. A date expression is limited to
numbers or strings, in any combination, that can represent a date from
January 1, 100 through December 31, 9999.
Dates are stored as part of a real number. Values to the left of the decimal
represent the date; values to the right of the decimal represent the time.
Negative numbers represent dates prior to December 30, 1899.
Date literal
Any sequence of characters with a valid format that is surrounded by number
signs (#). Valid formats include the date format specified by the locale
12
settings for your code or the universal date format. For example, #12/31/99#
is the date literal that represents December 31, 1999, where English-U.S. is
the locale setting for your application.
Date separators
Characters used to separate the day, month, and year when date values are
formatted.
Empty
A value that indicates that no beginning value has been assigned to a
variable. Empty variables are 0 in a numeric context, or zero-length in a
string context.
Error number
A whole number in the range 0 to 65,535, inclusive, that corresponds to the
Number property of the Err object. When combined with the Name property
of the Err object, this number represents a particular error message.
Expression
A combination of keywords, operators, variables, and constants that yield a
string, number, or object. An expression can perform a calculation,
manipulate characters, or test data.
Intrinsic constant
A constant provided by an application. Because you can't disable intrinsic
constants, you can't create a user-defined constant with the same name.
Keyword
A word or symbol recognized as part of the VBScript language; for example, a
statement, function name, or operator.
Locale
The set of information that corresponds to a given language and country. A
locale affects the language of predefined programming terms and locale-
specific settings. There are two contexts where locale information is
important:
12
3. The system locale affects the way locale-aware functionality
behaves, for example, when you display numbers or convert strings to
dates. You set the system locale using the Control Panel utilities
provided by the operating system.
Nothing
The special value that indicates that an object variable is no longer associated
with any actual object.
Null
A value indicating that a variable contains no valid data. Null is the result of:
Numeric expression
Any expression that can be evaluated as a number. Elements of the
expression can include any combination of keywords, variables, constants,
and operators that result in a number.
Object type
A type of object exposed by an application, for example, Application, File,
Range, and Sheet. Refer to the application's documentation (Microsoft Excel,
Microsoft Project, Microsoft Word, and so on) for a complete listing of
available objects.
pi
Pi is a mathematical constant equal to approximately 3.1415926535897932.
Private
Variables that are visible only to the script in which they are declared.
Procedure
A named sequence of statements executed as a unit. For example, Function
and Sub are types of procedures.
Procedure level
Describes statements located within a Function or Sub procedure.
Declarations are usually listed first, followed by assignments and other
executable code. For example:
12
Debug.Print A ' Procedure-level code.
End Sub ' This statement ends a sub procedure block.
Note that script-level code resides outside any procedure blocks.
Property
A named attribute of an object. Properties define object characteristics such
as size, color, and screen location, or the state of an object, such as enabled
or disabled.
Public
Variables declared using the Public Statement are visible to all procedures in
all modules in all applications.
Run time
The time when code is running. During run time, you can't edit the code.
Run-time error
An error that occurs when code is running. A run-time error results when a
statement attempts an invalid operation.
Scope
Defines the visibility of a variable, procedure, or object. For example, a
variable declared as Public is visible to all procedures in all modules.
Variables declared in procedures are visible only within the procedure and
lose their value between calls.
SCODE
A long integer value that is used to pass detailed information to the caller of
an interface member or API function. The status codes for OLE interfaces and
APIs are defined in FACILITY_ITF.
Script level
Any code outside a procedure is referred to as script-level code.
Seed
An initial value used to generate pseudorandom numbers. For example, the
Randomize statement creates a seed number used by the Rnd function to
create unique pseudorandom number sequences.
String comparison
A comparison of two sequences of characters. Unless specified in the function
making the comparison, all string comparisons are binary. In English, binary
comparisons are case-sensitive; text comparisons are not.
12
String expression
Any expression that evaluates to a sequence of contiguous characters.
Elements of a string expression can include a function that returns a string, a
string literal, a string constant, or a string variable.
Type library
A file or component within another file that contains standard descriptions of
exposed objects, properties, and methods.
Variable
A named storage location that can contain data that can be modified during
program execution. Each variable has a name that uniquely identifies it within
its level of scope.
Variable names:
12
Some Useful Tips with QTP
1) How to add a constant number in a data table?
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
4) My test fails due to checkpoint failing, Can i validate a checkpoint without my test failing
due to checpoint failure?
Reporter.Filter = rfDisableAll 'Disables all the reporting stuff
chk_PassFail = Browser(...).Page(...).WebEdit(...).Check (Checkpoint("Check1"))
Reporter.Filter = rfEnableAll 'Enable all the reporting stuff
if chk_PassFail then
MsgBox "Check Point passed"
else
MsgBox "Check Point failed"
end if
13
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.
Example
The following example creates a new internal user-defined variable named MyVariable with a
value of 10, and then retrieves the variable value and stores it in the MyValue variable.
Environment.Value("MyVariable")=10
MyValue=Environment.Value("MyVariable")
Excel
Default.xls Data table parameters Can be edited using Excel
similar
Parameterization
Parameters.mtr Binary Do not edit
information
13
Default.prm Load test configuration file Text Do not edit
Script.mts Action script Text Edit text preceding the @@ sign only
13
QuickTest Professional 8.2 and below
QuickTest Professional 8.2 and below do not include support for Internet Explorer 7.0.
Does QuickTest Professional support Firefox?
QuickTest Professional 9.1 and 9.2
QuickTest Professional 9.1 provides replay support for Mozilla Firefox 1.5 and Mozilla Firefox 2.0
Alpha 3 (Alpha-level support for Bon Echo 2.0a3).
Notes:
QuickTest Professional 9.1 will not record on FireFox. You can record a test on Microsoft Internet
Explorer and run it on any other supported browser, such as FireFox.
The .Object property for web objects is not supported in FireFox.
QuickTest Professional 9.0
QuickTest Professional 9.0 provides replay support for Mozilla FireFox 1.5.
Notes:
QuickTest Professional 9.0 will not record on FireFox. You can record a test on Microsoft Internet
Explorer and run it on any other supported browser, such as FireFox.
The .Object property for web objects is not supported in FireFox.
QuickTest Professional 8.2 and below
QuickTest Professional 8.2 and below do not have support for Firefox.
12) Problem
After Quick Test Professional is started, Windows Media will not start. It returns the error
message "wmplayer.exe has generated errors and will be closed by Windows. You will need to
restart the program. An error log is being created."
If you start Window's Media Player first, it will continue to work normally after starting QuickTest
Professional.
Solution:
Include the Windows Media Player's executable in the NoBBTApps section of the mic.ini
file
1. Close QuickTest Professional.
2. Go to \bin\mic.ini.
3. Include wmplayer.exe in the NoBBTApps section of mic.ini file.
Example:
[NoBBTApps]
wmplayer.exe=rek
4. Save the mic.ini file and restart QuickTest Professional.
13) What is the lservrc file in QTP?
The lservrc file contains the license codes that have been installed
The lservrc file contains the license codes that have been installed. Whenever a new license is
created, the license code is automatically added to this file. The lservrc file is a text file, with no
extension.
File Location:
13
15) Does QuickTest Professional support Macintosh operating systems?
No, QTP is not expected to run on this OS.
13