SlideShare ist ein Scribd-Unternehmen logo
1 von 77
Downloaden Sie, um offline zu lesen
gcrindia@gmail.com




             Advanced QTP
                  (In VBScript Orientation)

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) General Examples

10) Loop Through Code

11) Procedures

12) Built-In Functions

13) VBScript syntax rules and guidelines

14) Errors

15) File System Operations

16) Test Requirements

17) Solutions

18) QTP Add-Ins Information

19) VBScript Glossary




             G.C.Reddy, QTP Trainer (Mobile: 9247837478)          1
gcrindia@gmail.com


                                   Introduction

   o   VBScript is a scripting language.
   o   A scripting language is a lightweight programming language.
   o   VBScript is a light version of Microsoft's programming language Visual Basic.


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.

1.1 Windows Script Host (WSH)

It is a Windows administration tool. WSH creates an environment for hosting scripts.

That is, when a script arrives at your computer, WSH plays the part of the host — it
makes objects and services available for the script and provides a set of guidelines
within which the script is executed. Among other things, Windows Script Host
manages security and invokes the appropriate script engine

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.2 Creating a script with Notepad

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"

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).


               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                                 2
gcrindia@gmail.com

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.

1.4 Available Script Engines

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.




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                            3
gcrindia@gmail.com


                                  Comments

The comment argument is the text of any comment we want to include.

2.0 Purpose of comments:

   o   We can use comments for making the script understandable.
   o   We can use comments for making one or more statements disable from
       execution.


2.1 Syntax

Rem comment (After the Rem keyword, a space is required before comment.)

                                        Or

Apostrophe (') symbol before the comment

2.2 Comment/Uncomment a block of statements

Select block of statement and use short cut key Ctrl + M (for comment)
Select comment block and use short cut key Ctrl + Shift + M (for uncomment)


2.3 Example




              G.C.Reddy, QTP Trainer (Mobile: 9247837478)                     4
gcrindia@gmail.com


                               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.

3.1 Declaring Variables

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:

Dim x, Top, Bottom, Left, Right

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.

3.2 Option Explicit

Forces explicit declaration of all variables in a script.

Option Explicit ' Force explicit variable declaration.
Dim MyVar ' Declare variable.
MyInt = 10 ' Undeclared variable generates error.
MyVar = 10 ' Declared variable does not generate error.

3.3 Naming Restrictions for Variables

Variable names follow the standard rules for naming anything in VBScript. A variable
name:
   o   Must begin with an alphabetic character.
   o   Cannot contain an embedded period.
   o   Must not exceed 255 characters.
   o   Must be unique in the scope in which it is declared.




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                               5
gcrindia@gmail.com


3.4 Scope of Variables

A variable's scope is determined by where we declare it.

When we declare a variable within a procedure, only code within that procedure can
access or change the value of that variable.

If we declare a variable outside a procedure, we make it recognizable to all the
procedures in our script. This is a script-level variable, and it has script-level scope.

3.5 Life Time of Variables

The lifetime of a variable depends on how long it exists.

The lifetime of a script-level variable extends from the time it is declared until the
time the script is finished running.

At procedure level, a variable exists only as long as you are in the procedure.

3.6 Assigning Values to Variables

Values are assigned to variables creating an expression as follows:

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:
A = 200
City = “Hyderabad”

X=100: Y=200

3.7 Scalar Variables and Array Variables

A variable containing a single value is a scalar variable.

A variable containing a series of values, is called an array variable.

Array variables and scalar variables are declared in the same way, except that the
declaration of an array variable uses parentheses () following the variable name.

Example:
Dim A(3)

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 4, data can be assigned to the elements of an array
as follows:




                G.C.Reddy, QTP Trainer (Mobile: 9247837478)                                 6
gcrindia@gmail.com

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. We can have as many as 60 dimensions,
although most people can't comprehend more than three or four dimensions.

In the following example, the MyTable variable is a two-dimensional array consisting
of 6 rows and 11 columns:

Dim MyTable(5, 10)

In a two-dimensional array, the first number is always the number of rows; the
second number is the number of columns.

3.8 Dynamic Arrays

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()
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)

ReDim Preserve MyArray(30)

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.




                 G.C.Reddy, QTP Trainer (Mobile: 9247837478)                           7
gcrindia@gmail.com


                             VB Script Data Types

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.

4.1 Variant Subtypes

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.
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.




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                              8
gcrindia@gmail.com


                               VB Script Operators

Operators are used for performing mathematical, comparison and logical operations.
VBScript has a full range of operators, including arithmetic operators, comparison
operators, concatenation operators, and logical operators.

4.1 Operator Precedence

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.

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.

4.3 Comparison Operators

Used to compare expressions.

Operator                                               Description
1) = (Equal to)                       Used to compare expressions.
2) <> (Not equal to)                  Used to compare expressions.
3) < Less than
4) > Grater than
5) <= Less than or equal to



                 G.C.Reddy, QTP Trainer (Mobile: 9247837478)                           9
gcrindia@gmail.com

6) >= Greater than or equal to
7) Is                               Object equivalence


4.4 Concatenation Operators

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 the     Add.
                            other is a string
2) Concatenation           Forces string concatenation of two expressions.
Operator (&)



4.5 Logical Operators

Operator           Description                             Syntax
1) Not             Performs logical negation on an         result= Not expression
                   expression
2) And             Performs a logical conjunction on two   result= expression1   And
                   expressions.                            expression2
3) Or              Performs a logical disjunction on two   result= expression1   Or
                   expressions.                            expression2
4) Xor             Performs a logical exclusion on two     result= expression1   Xor
                   expressions.                            expression2
5) Eqv             Performs a logical equivalence on       result= expression1   Eqv
                   two expressions.                        expression2

6) Imp             Performs a logical implication on two   result= expression1 Imp
                   expressions.                            expression2




              G.C.Reddy, QTP Trainer (Mobile: 9247837478)                              10
gcrindia@gmail.com




                          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)

6.2 MsgBox Function

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.




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                               11
gcrindia@gmail.com


                               VB Script Constants

A constant is a meaningful name that takes the place of a number or string and
never changes.

7.1 Creating Constants

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

Declares constants for use in place of literal values.

Example:

Const MyString = "This is my string."
Const MyAge = 49
Const CutoffDate = #6-1-97#

Note that String literal is enclosed in quotation marks (" ").

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:
Const price= 100, city= “Hyderabad”, x= 27




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                         12
gcrindia@gmail.com


                            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
2) Select Case Statement

8.1 Making Decisions Using If...Then...Else

The If...Then...Else statement is used to evaluate whether a condition is True or
False and, depending on the result, to specify one or more statements to run.

Usually the condition is an expression that uses a comparison operator to compare
one value or variable with another.

If...Then...Else statements can be nested to as many levels as you need.

8.1.1 Running a Statement if a Condition is True (single statement)

To run only one statement when a condition is True, use the single-line syntax for
the If...Then...Else statement.

Dim myDate
  myDate = #2/13/98#
  If myDate < Now Then myDate = Now

8.1.2 Running Statements if a Condition is True (multiple statements)

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
If x>10 Then
       msgbox "Hello G.C.Reddy"
       msgbox "x value is: "&x
       msgbox "Bye Bye"
End If

8.1.3 Running Certain Statements if a Condition is True and Running Others
if a Condition is False

We can use an If...Then...Else statement to define two blocks of executable
statements: one block to run if the condition is True, the other block to run if the
condition is False.
Example:




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                             13
gcrindia@gmail.com

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

8.1.4 Deciding Between Several Alternatives

A variation on the If...Then...Else statement allows us to choose from several
alternatives. Adding ElseIf clauses expands the functionality of the If...Then...Else
statement so we can control program flow based on different possibilities.
Example:
Dim x
x= Inputbox (" Enter a value")

If x>0 and x<=100 Then
       Msgbox "Hello G.C.Reddy"
       Msgbox "X is a Small Number"
       Msgbox "X value is "&x

Else IF x>100 and x<=500 Then
        Msgbox "Hello GCR"
        Msgbox "X is a Medium Number"

Else IF x>500 and x<=1000 Then
        Msgbox "Hello Chandra Mohan Reddy"
        Msgbox "X is a Large Number"

Else
         Msgbox "Hello Sir"
         Msgbox "X is a Grand Number"
End If
End If
End If

8.1.5 Executing a certain block of statements when two / more conditions
are True (Nested If...)

Example:

Dim State, Region
State=Inputbox ("Enter a State")
Region=Inputbox ("Enter a Region")

If state= "AP" Then
        If Region= "Telangana" Then


                G.C.Reddy, QTP Trainer (Mobile: 9247837478)                             14
gcrindia@gmail.com

                 msgbox "Hello G.C.Reddy"
                 msgbox "Dist count is 10"

Else if Region= "Rayalasema" Then
               msgbox "Hello GCR"
               msgbox "Dist count is 4"

Else If Region= "Costal" Then
              msgbox "Hello Chandra mohan Reddy"
              msgbox "Dist count is 9"

End   If
End   If
End   If
End   If

8.2 Making Decisions with Select Case

The Select Case structure provides an alternative to If...Then...ElseIf for selectively
executing one block of statements from among multiple blocks of statements. A
Select Case statement provides capability similar to the If...Then...Else statement,
but it makes code more efficient and readable.
Example:

Option explicit
Dim x,y, Operation, Result
x= Inputbox (" Enter x value")
y= Inputbox ("Enter y value")
Operation= Inputbox ("Enter an Operation")

Select Case Operation

           Case "add"
                        Result= cdbl (x)+cdbl (y)
                        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



                  G.C.Reddy, QTP Trainer (Mobile: 9247837478)                         15
gcrindia@gmail.com

          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 Other Examples

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")

If xyear mod 4=0 Then
       msgbox "This is a Leap year"
Else
       msgbox "This is NOT"
End If

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")

If num mod 2=0 Then
       msgbox "This is a Even Number"
Else
       msgbox "This is a Odd Number"
End If

8.3.3 Read two numbers and display the sum?

Dim num1,num2, sum
num1=inputbox ("Enter num1")
num2=inputbox ("Enter num2")

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



                 G.C.Reddy, QTP Trainer (Mobile: 9247837478)                      16
gcrindia@gmail.com

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

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

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

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

Dim num,rev
num= inputbox("Enter a number")
If len(num)=4 Then

rev=rev*10 + num mod 10
num=num/10
num= left(num,3)

rev=rev*10 + num mod 10
num=num/10
num= left(num,2)

rev=rev*10 + num mod 10
num=num/10
num= left(num,1)

rev=rev*10 + num mod 10

       msgbox "Reverse Order of the number is "&rev


               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                           17
gcrindia@gmail.com

Else
            msgbox "Number, you entered is not a 4 digit number"
End If

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')

Dim e,m,p,c, tot
e=inputbox ("Enter english Marks")
m=inputbox ("Enter maths Marks")
p=inputbox ("Enter physics Marks")
c=inputbox ("Enter chemistry Marks")

tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c)
msgbox tot


If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot
>=300 Then
        msgbox "Grade is Distinction"

else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot
>=240 and tot<300 Then
        msgbox "Grade is First"

else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot
>=200 and tot<240 Then
        msgbox "Grade is Second"

else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot
>=160 and tot<200 Then
        msgbox "Grade is Third"
else
msgbox "No Grade, Fail"

End    If
End    If
End    If
End    If

8.3.8 Display Odd numbers up to n?

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


                   G.C.Reddy, QTP Trainer (Mobile: 9247837478)                     18
gcrindia@gmail.com

msgbox num
Next

8.3.9 Display Even numbers up to n?

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

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

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

8.11 Display Natural numbers in reverse order up to n?

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

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

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

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

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




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)             19
gcrindia@gmail.com

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

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

8.15 Write a Function for Natural Numbers sum up to n?

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

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")

d1= left (num,1)
d10=Right (num,1)
d2=mid (num, 2, len   (1))
d3=mid (num, 3, len   (1))
d4=mid (num, 4, len   (1))
d5=mid (num, 5, len   (1))
d6=mid (num, 6, len   (1))
d7=mid (num, 7, len   (1))
d8=mid (num, 8, len   (1))
d9=mid (num, 9, len   (1))


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




              G.C.Reddy, QTP Trainer (Mobile: 9247837478)                       20
gcrindia@gmail.com

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")

d1= left (num,1)
d10=Right (num,1)
d2=mid (num, 2, len   (1))
d3=mid (num, 3, len   (1))
d4=mid (num, 4, len   (1))
d5=mid (num, 5, len   (1))
d6=mid (num, 6, len   (1))
d7=mid (num, 7, len   (1))
d8=mid (num, 8, len   (1))
d9=mid (num, 9, len   (1))

If len (num) =10 Then

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

If len (num) <> 10 Then
 Msgbox "It is NOT valid Number "
End If




              G.C.Reddy, QTP Trainer (Mobile: 9247837478)                       21
gcrindia@gmail.com


                            Looping Through Code

   o   Looping allows us to run a group of statements repeatedly.
   o   Some loops repeat statements until a condition is False;
   o   Others repeat statements until a condition is True.
   o   There are also loops that repeat statements a specific number of times.
The following looping statements are available in VBScript:
   o   Do...Loop: Loops while or until a condition is True.
   o   While...Wend: Loops while a condition is True.
   o   For...Next: Uses a counter to run statements a specified number of times.
   o   For Each...Next: Repeats a group of statements for each item in a collection
       or each element of an array.


9.1 Using Do Loops

We can use Do...Loop statements to run a block of statements an indefinite number
of times.

The statements are repeated either while a condition is True or until a condition
becomes True.

9.1.1 Repeating Statements While a Condition is True

Repeats a block of statements while a condition is True or until a condition becomes
True

a) Do While condition
   Statements
   -----------
   -----------
   Loop
Or, we can use this below syntax:

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




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                          22
gcrindia@gmail.com


Example:

Dim x
x=1
Do
 Msgbox "Hello G.C.Reddy"
 Msgbox "Hello QTP"
 x=x+1
Loop While x<5

9.1.2 Repeating a Statement Until a Condition Becomes True

c) Do Until condition
   Statements
   -----------
   -----------
   Loop
Or, we can use this below syntax:
Example:

Dim x
Do Until x=5 x=x+1
 Msgbox "G.C.Reddy"
 Msgbox "Hello QTP"
Loop
Or, we can use this below syntax:
d) Do
   Statements
   -----------
   -----------
   Loop Until condition
Or, we can use this below syntax:

Example:

Dim x
x=1
Do
Msgbox “Hello G.C.Reddy”
Msgbox "Hello QTP"
 x=x+1
Loop Until x=5

9.2 While...Wend Statement

Executes a series of statements as long as a given condition is True.

Syntax:
While condition
  Statements
  -----------


               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                 23
gcrindia@gmail.com

  -----------
Wend
Example:
Dim x
x=0
While x<5 x=x+1
       msgbox "Hello G.C.Reddy"
       msgbox "Hello QTP"
Wend

9.3 For...Next Statement

Repeats a group of statements a specified number of times.
Syntax:
For counter = start to end [Step step]
     statements
Next

Example:
Dim x
For x= 1 to 5 step 1
Msgbox "Hello G.C.Reddy"
Next

9.4 For Each...Next Statement

Repeats a group of statements for each element in an array or collection.

Syntax:

For Each item In array
     Statements
Next

Example: (1

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

For Each element In x
     msgbox element
Next

Example: (2

MyArray = Array("one","two","three","four","five")
For Each element In MyArray


               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                  24
gcrindia@gmail.com

       msgbox element
Next

    Control Flow Examples (Using Conditional and Loop Statements)

11.1 read a number and verify that number Range weather in between 1 to
100 or 101 to 1000?

Option explicit
Dim a,x
a=Inputbox ("Enter a Vaule")
a=cdbl(a)
If a<= 100 Then
For x= 1 to 100
If a=x Then
       msgbox "a is in between 1 to 100 range"
End If
Next
else
For x= 101 to 1000
If a=x Then
msgbox "a is in between 101 to 1000 range"
End If
Next
End If

11.1 read Data and find that data size, If size <>4 then display invalid data
message, if data size = 4 then verify “a” is there or not in that data?

Dim x
x=Inputbox ("Enter 4 digit value")
x1=Right(x,1)
x2=Left (x,1)
x3=mid (x,2,Len(1))
x4=mid (x,3,Len(1))
y=len(x)
If y=4 Then
If x1="a" or x2="a" or x3="a" or x4="a" Then
msgbox "a is there"
else
msgbox "a is Not there"
End If
else
msgbox "Invalid Data"
End If




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                  25
gcrindia@gmail.com


                            VB Script Procedures

In VBScript, there are two kinds of procedures available; the Sub procedure and the
Function procedure.

11.1 Sub Procedures

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:
Sub Procedure name ()
Statements
-----------
-----------
End Sub
Or
Sub Procedure name (argument1, argument2)
Statements
-----------
-----------
End Sub

Example: 1

Sub ConvertTemp()
  temp = InputBox("Please enter the temperature in degrees F.", 1)
  MsgBox "The temperature is " & Celsius(temp) & " degrees C."
End Sub

Example: 2

11.2 Function Procedures

A Function procedure is a series of VBScript statements enclosed by the Function and
End Function statements.

A Function procedure is similar to a Sub procedure, but can also return a value.

A Function procedure can take arguments (constants, variables, or expressions that
are passed to it by a calling procedure).

If a Function procedure has no arguments, its Function statement must include an
empty set of parentheses.




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                          26
gcrindia@gmail.com

A Function returns a value by assigning a value to its name in one or more
statements of the procedure. The return type of a Function is always a Variant.
Syntax:
Function Procedure name ()
Statements
-----------
-----------
End Function
Or
Function Procedure name (argument1, argument2)
Statements
-----------
-----------
End Function

Example: 1

Function Celsius(fDegrees)
  Celsius = (fDegrees - 32) * 5 / 9
End Function

Example: 2

Function cal(a,b,c)
  cal = (a+b+c)
End Function

11.3 Getting Data into and out of Procedures
   o   Each piece of data is passed into our procedures using an argument.
   o   Arguments serve as placeholders for the data we want to pass into our
       procedure. We can name our arguments any valid variable name.
   o   When we create a procedure using either the Sub statement or the Function
       statement, parentheses must be included after the name of the procedure.
   o   Any arguments are placed inside these parentheses, separated by commas.


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.


               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                        27
gcrindia@gmail.com


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.

Call MyProc(firstarg, secondarg)

MyProc firstarg, secondarg

Notice that the parentheses are omitted in the call when the Call statement isn't
used.




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                          28
gcrindia@gmail.com


                           VB Script Built in Functions

Types of Functions
   o   Conversions (25)
   o   Dates/Times (19)
   o   Formatting Strings (4)
   o   Input/Output (3)
   o   Math (9)
   o   Miscellaneous (3)
   o   Rounding (5)
   o   Strings (30)
   o   Variants (8)


                                Important Functions

1) Abs Function
Returns the absolute value of a number.
Dim num
num=abs(-50.33)
msgbox num

2) Array Function
Returns a variant containing an Array
Dim A
A=Array("hyderabad","chennai","mumbai")
msgbox A(0)
ReDim A(5)
A(4)="nellore"
msgbox A(4)

3) Asc Function
Returns the ANSI character code corresponding to the first letter in a string.
Dim num
num=Asc("A")
msgbox num

* It returns the value 65 *

4) Chr Function
Returns the character associated with the specified ANSI character code.
Dim char
Char=Chr(65)
msgbox char

* It returns A *




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                       29
gcrindia@gmail.com

5) CInt Function
Returns an expression that has been converted to a Variant of subtype Integer.
Dim num
num=123.45
myInt=CInt(num)
msgbox MyInt

6) Date Function

Returns the Current System Date.

Dim mydate
mydate=Date
msgbox mydate

7) Day Function

Ex1)   Dim myday
       myday=Day("17,December,2009")
       msgbox myday

Ex2)   Dim myday
       mydate=date
       myday=Day(Mydate)
       msgbox myday

8) DateDiff Function
Returns the number of intervals between two dates.
Dim myday
mydate=#02-17-2009#
x=Datediff("d",mydate,Now)
msgbox x

9) Hour Function
Returns a whole number between 0 and 23, inclusive, representing the hour of the
day.
Dim mytime, Myhour
mytime=Now
myhour=hour (mytime)
msgbox myhour

10) Join Function
Returns a string created by joining a number of substrings contained in an array.
Dim mystring, myarray(3)
myarray(0)="Chandra "
myarray(1)="Mohan "
myarray(2)="Reddy"
mystring=Join(MyArray)
msgbox mystring




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                          30
gcrindia@gmail.com

11) Eval Function

Evaluates an expression and returns the result.

12) Time Function
Returns a Variant of subtype Date indicating the current system time.
Dim mytime
mytime=Time
msgbox mytime

13) VarType Function
Returns a value indicating the subtype of a variable.

Dim MyCheck
MyCheck = VarType(300)           ' Returns 2.
Msgbox Mycheck

MyCheck = VarType(#10/19/62#)        ' Returns 7.
Msgbox Mycheck

MyCheck = VarType("VBScript")     ' Returns 8.
Msgbox Mycheck

14) Left Function

Dim MyString, LeftString
MyString = "VBSCript"
LeftString = Left(MyString, 3) ' LeftString contains "VBS".


14) Right Function

Dim AnyString, MyStr
AnyString = "Hello World"   ' Define string.
MyStr = Right(AnyString, 1) ' Returns "d".
MyStr = Right(AnyString, 6) ' Returns " World".
MyStr = Right(AnyString, 20) ' Returns "Hello World".

15) Len Function

Returns the number of characters in a string or the number of bytes required to
store a variable.

Ex 1): Dim Mystring
       mystring=Len("G.C.Reddy")
       msgbox mystring

Ex 2): Dim Mystring
       Mystring=Inputbox("Enter a Value")
       Mystring=Len(Mystring)
       Msgbox Mystring




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                        31
gcrindia@gmail.com

16) Mid Function
Returns a specified number of characters from a string.
Dim MyVar
MyVar = Mid("VB Script is fun!", 4, 6)
Msgbox MyVar

* It Returns ‘Script’ *

17) Timer Function
Returns the number of seconds that have elapsed since 12:00 AM (midnight).

Function myTime(N)
  Dim StartTime, EndTime
  StartTime = Timer
  For I = 1 To N
  Next
  EndTime = Timer
  myTime= EndTime - StartTime
  msgbox myTime
End Function
Call myTime(2000)

17) isNumeric Function

Dim MyVar, MyCheck
MyVar = 53
MyCheck = IsNumeric(MyVar)
msgbox MyCheck

MyVar = "459.95"
MyCheck = IsNumeric(MyVar)
msgbox MyCheck

MyVar = "45 Help"
MyCheck = IsNumeric(MyVar)
msgbox MyCheck

* It Returns True/False like Result *

18) 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.

Dim Input
Input = InputBox("Enter your name")
MsgBox ("You entered: " & Input)

19) Msgbox Function
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.
Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")


                G.C.Reddy, QTP Trainer (Mobile: 9247837478)                              32
gcrindia@gmail.com


                  VBScript syntax rules and guidelines

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.

For example, the two statements below are identical in VBScript:

Browser("Mercury").Page("Find a Flight:").WebList("toDay").Select "31"
browser("mercury").page("find a flight:").weblist("today").select "31"

21.2 Text strings:

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.

Browser("Mercury").Page("Find a Flight:").WaitProperty("items count", Total_Items,
2000)

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:

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.


               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                           33
gcrindia@gmail.com


21.7 Spaces:

We can add extra blank spaces to our script to improve clarity. These spaces are
ignored by VBScript.




                                      Errors

We have two types Errors in VB Script; they are VBScript Run-time Errors and
VBScript Syntax Errors

13.1 VBScript Run-time 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.


13.2 VBScript Syntax Errors

VBScript syntax errors are errors that result when the structure of one of our
VBScript statements violates one or more of the grammatical rules of the VBScript
scripting language. VBScript syntax errors occur during the program compilation
stage, before the program has begun to be executed.




               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                          34
gcrindia@gmail.com


                 File System Operations
I) Working with Drives and Folders

a) Creating a Folder

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

b) Deleting a Folder

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

c) Copying Folders

Set oFSO=createobject("Scripting.Filesystemobject")
oFSO.CopyFolder "E:gcr6", "C:jvr", True
d) Checking weather the folder available or not, if not creating the folder
Option Explicit
Dim objFSO, objFolder, strDirectory
strDirectory = "D:logs"
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

e) Returning a collection of Disk Drives

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

f) Getting available space on a Disk Drive

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




           G.C.Reddy, QTP Trainer (Mobile: 9247837478)                   35
gcrindia@gmail.com



II) Working with Flat Files
a) Creating a Flat File
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("E:ScriptLog.txt")

b) Checking weather the File is available or not, if not creating the File
strDirectory="E:"
strFile="Scripting.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile("E:ScriptLog.txt")
End if


c) Reading Data character by character from a Flat File




           G.C.Reddy, QTP Trainer (Mobile: 9247837478)                       36
gcrindia@gmail.com

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

d) Reading Data line by line from a Flat File

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

e) 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:gcr.txt",1)
myfile.skipline
While myfile.atendofline <> True
x=myfile.readline
s=split (x, ",")
SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest
Professionalsamplesflightappflight4a.exe","","C:Program FilesMercury
InteractiveQuickTest Professionalsamplesflightapp","open"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set s(0)
Dialog("Login").WinEdit("Password:").SetSecure s(1)
Dialog("Login").WinButton("OK").Click
Window("Flight Reservation").Close
Wend

f) Writing data to a text file

Dim Stuff, myFSO, WriteStuff, dateStamp
dateStamp = Date()
Stuff = "I am Preparing this script: " &dateStamp

Set myFSO = CreateObject("Scripting.FileSystemObject")
Set WriteStuff = myFSO.OpenTextFile("e:gcr.txt", 8, True)
WriteStuff.WriteLine(Stuff)
WriteStuff.Close
SET WriteStuff = NOTHING
SET myFSO = NOTHING

g) Delete a text file

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


           G.C.Reddy, QTP Trainer (Mobile: 9247837478)                       37
gcrindia@gmail.com

txtFilepath.Delete()

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

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

i) Comparing two text files

Dim f1, f2
f1="e:gcr1.txt"
f2="e:gcr2.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."


           G.C.Reddy, QTP Trainer (Mobile: 9247837478)                      38
gcrindia@gmail.com

End If

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

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

III) Working with Word Docs

a) Create a word document and enter some data & save

Dim objWD
Set objWD = CreateObject("Word.Application")
objWD.Documents.Add

objWD.Selection.TypeText "This is some text." & Chr(13) & "This is some more
text"
objWD.ActiveDocument.SaveAs "e:gcreddy.doc"
objWD.Quit

IV) Working with Excel Sheets

a) Create an excel sheet and enter a value into first cell

Dim objexcel
Set objExcel = createobject("Excel.application")
objexcel.Visible = True
objexcel.Workbooks.add
objexcel.Cells(1, 1).Value = "Testing"
objexcel.ActiveWorkbook.SaveAs("f:gcreddy1.xls")
objexcel.Quit

b) Compare two excel files

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook1= objExcel.Workbooks.Open("E:gcr1.xls")
Set objWorkbook2= objExcel.Workbooks.Open("E:gcr2.xls")



           G.C.Reddy, QTP Trainer (Mobile: 9247837478)                     39
gcrindia@gmail.com

Set objWorksheet1= objWorkbook1.Worksheets(1)

Set objWorksheet2= objWorkbook2.Worksheets(1)

  For Each cell In objWorksheet1.UsedRange
     If cell.Value <> objWorksheet2.Range(cell.Address).Value Then
         msgbox "value is different"
     Else
         msgbox "value is same"
     End If
    Next
objWorkbook1.close
objWorkbook2.close
objExcel.quit
set objExcel=nothing




           G.C.Reddy, QTP Trainer (Mobile: 9247837478)               40
gcrindia@gmail.com


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


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


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


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


5) Price Consistency, In Flight Reservation (In Flight Reservation, First class
   price=3*Economy class price and Business class price=2*Economy class
   price)


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


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


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


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


10)      Get Test Data From a Database and use in Data Driven Testing
   (through Scripting)


11)       Count, how many links available in Mercury Tours Home Page?


12)      Count how many Buttons and Edit boxes available in Flight
   Reservation window?


           G.C.Reddy, QTP Trainer (Mobile: 9247837478)                          41
gcrindia@gmail.com



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


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


15) Count all opened Browsers on desktop and close all?

16) Create an Excel file, enter some data and save the file through VB
scripting?

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


          1) ApplicationDir = Environment("ProductDir")
          2) ApplicationPath = "samplesflightappflight4a.exe"
          3) If Window("Flight Reservation").Exist(2) Then
          4) Window("Flight Reservation").Close
          5) SystemUtil.Run ApplicationDir & ApplicationPath
          6) Elseif Not Dialog("Login").Exist(1) Then
          7) SystemUtil.Run ApplicationDir & ApplicationPath
          8) End If
          9) Dialog("Login").WinEdit("Agent Name:").Set Datatable.Value
             ("AgentName",dtGlobalSheet)
          10) Dialog("Login").WinEdit("Password:").Set Datatable.Value
              ("Password",dtGlobalSheet)
          11) Dialog("Login").WinButton("OK").Click
          12) If Dialog("Login").Dialog("Flight Reservations").Exist(1) and
              Datatable.Value ("Status",dtGlobalSheet)="Fail" Then
          13) Dialog("Login").Dialog("Flight Reservations").Static("Agent name must
              be at").Check CheckPoint("Agent name must be at least 4 characters
              long.")
          14) Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click



               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                          42
gcrindia@gmail.com

      15) Elseif Window("Flight Reservation").Exist(10) and Datatable.Value
          ("Status",dtGlobalSheet)="Pass" Then
      16) Reporter.ReportEvent PASS,"Login: ","Succeeded"
      17) Else
      18) Reporter.ReportEvent Fail,"Login: ","Combination #" &
          Datatable.GetCurrentRow & " was not according to Excel file"
      19) End If


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


   1) Invokeapplication "C:Program FilesMercury InteractiveQuickTest
      Professionalsamplesflightappflight4a.exe"
   2) Dialog("Login").Activate
   3) Dialog("Login").WinButton("Cancel").Click
   4) If Dialog("Login").Exist (2) =True Then
   5) Reporter.ReportEvent 1,"sd","Fail"
   6) Else
   7) Reporter.ReportEvent 0,"sd","Pass"
   8) Invokeapplication "C:Program FilesMercury InteractiveQuickTest
      Professionalsamplesflightappflight4a.exe"
   9) End If
   10) Dialog("Login").Activate
   11) Dialog("Login").WinEdit("Agent Name:").Set "asdf"
   12) Dialog("Login").WinButton("Cancel").Click
   13) If Dialog("Login").Exist (2) =True Then
   14) Reporter.ReportEvent 1,"sd","Fail"
   15) Else
   16) Reporter.ReportEvent 0,"sd","Pass"
   17) Invokeapplication "C:Program FilesMercury InteractiveQuickTest
       Professionalsamplesflightappflight4a.exe"
   18) End If
   19) Dialog("Login").Activate
   20) Dialog("Login").WinEdit("Agent Name:").Set "asdf"
   21) Dialog("Login").WinEdit("Password:").SetSecure
       "4a993af45dcbd506c8451b274d2da07b38ff5531"
   22) Dialog("Login").WinButton("Cancel").Click



              G.C.Reddy, QTP Trainer (Mobile: 9247837478)                     43
gcrindia@gmail.com

   23) If Dialog("Login").Exist (2)=True Then
   24) Reporter.ReportEvent 1,"sd","Fail"
   25) Else
   26) Reporter.ReportEvent 0,"sd","Pass"
   27) Invokeapplication "C:Program FilesMercury InteractiveQuickTest
       Professionalsamplesflightappflight4a.exe"
   28) End If
   29) Dialog("Login").Activate
   30) Dialog("Login").WinEdit("Agent Name:").Set "asdf"
   31) Dialog("Login").WinEdit("Password:").SetSecure
       "4a993af45dcbd506c8451b274d2da07b38ff5531"
   32) Dialog("Login").WinButton("OK").Click


3) Verify Addition, Subtraction, Multiplication and Division Operations in
   Calculator Application.
1) Dim aRes,sRes,dRes,mRes
2) VbWindow("VbWindow").Activate
3) VbWindow("VbWindow").VbEdit("VbEdit").Set "10"
4) VbWindow("VbWindow").VbEdit("VbEdit_2").Set "20"
5) v1=VbWindow("VbWindow").VbEdit("VbEdit").GetROProperty ("text")
6) v2=VbWindow("VbWindow").VbEdit("VbEdit_2").GetROProperty ("text")
7) VbWindow("VbWindow").VbButton("ADD").Click
8) aRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText
9) VbWindow("VbWindow").VbButton("SUB").Click
10) sRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText
11) VbWindow("VbWindow").VbButton("MUL").Click
12) mRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText
13) VbWindow("VbWindow").VbButton("DIV").Click
14) dRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText
15) v1=cdbl(v1)
16) v2=cdbl(v2)
17) aRes=cdbl (aRes)
18) sRes=cdbl (sRes)
19) mRes=cdbl (mRes)
20) dRes=cdbl (dRes)
21) If aRes=v1+v2 Then



              G.C.Reddy, QTP Trainer (Mobile: 9247837478)                  44
gcrindia@gmail.com

   22) Reporter.ReportEvent 0,"Res","Addition Passed"
   23) else
   24) Reporter.ReportEvent 1,"Res","Addition Failed"
   25) End If
   26) If sRes=v1-v2 Then
   27) Reporter.ReportEvent 0,"Res","Subtraction Passed"
   28) else
   29) Reporter.ReportEvent 1,"Res","Subtraction Failed"
   30) End If
   31) If mRes=v1*v2 Then
   32) Reporter.ReportEvent 0,"Res","Multiplecation Passed"
   33) else
   34) Reporter.ReportEvent 1,"Res","Multiplecation Failed"
   35) End If
   36) If dRes=v1/v2 Then
   37) Reporter.ReportEvent 0,"Res","Division Passed"
   38) else
   39) Reporter.ReportEvent 1,"Res","Division Failed"
   40) End If


4) Verify state of Update Order Button, before open an Order and after open
an Order (in Flight Reservation before opening an order Update Order button should
be disabled after opening an order enabled.)
   1) Option explicit
   2) Dim bo,ao
   3) If Not window("Flight Reservation").Exist (2) Then
   4) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest
      Professionalsamplesflightappflight4a.exe"
   5) Dialog("Login").Activate
   6) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy"
   7) Dialog("Login").WinEdit("Password:").SetSecure
      "4aa8bce9984f1a15ea187a2da5b18c545abb01cf"
   8) Dialog("Login").WinButton("OK").Click
   9) End If
   10) Window("Flight Reservation").Activate
   11) bo=Window("Flight Reservation").WinButton("Update Order").GetROProperty
       ("Enabled")


                G.C.Reddy, QTP Trainer (Mobile: 9247837478)                     45
gcrindia@gmail.com

   12) Window("Flight Reservation").WinButton("Button").Click
   13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order
       No.").Set "ON"
   14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "1"
   15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
   16) ao=Window("Flight Reservation").WinButton("Update Order").GetROProperty
       ("Enabled")
   17) If bo=False Then
   18) Reporter.ReportEvent 0,"Res","Update Order Button Disabled"
   19) else
   20) Reporter.ReportEvent 1,"Res","Update Order Button Enabled"
   21) End If
   22) If ao=True Then
   23) Reporter.ReportEvent 0,"Res","Update Order Button Enabled"
   24) else
   25) Reporter.ReportEvent 1,"Res","Update Order Button Disabled"
   26) End If


5) Price Consistency, In Flight Reservation (In Flight Reservation, First class
price=3*Economy class price and Business class price=2*Economy class price)


   1) Option explicit
   2) Dim n,f,b,e
   3) If Not window("Flight Reservation").Exist (2) Then
   4) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest
      Professionalsamplesflightappflight4a.exe"
   5) Dialog("Login").Activate
   6) Dialog("Login").WinEdit("Agent Name:").Set "asdf"
   7) Dialog("Login").WinEdit("Password:").SetSecure
      "4aa8b7b7c5823680cfcb24d30714c9bbf0dff1eb"
   8) Dialog("Login").WinButton("OK").Click
   9) End If
   10) For n= 1 to 10 step 1
   11) Window("Flight Reservation").Activate
   12) Window("Flight Reservation").WinButton("Button").Click
   13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order
       No.").Set "ON"



                G.C.Reddy, QTP Trainer (Mobile: 9247837478)                        46
gcrindia@gmail.com

   14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set n
   15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
   16) Window("Flight Reservation").WinRadioButton("First").Set
   17) f=Window("Flight Reservation").WinEdit("Price:").GetVisibleText
   18) Window("Flight Reservation").WinRadioButton("Business").Set
   19) b=Window("Flight Reservation").WinEdit("Price:").GetVisibleText
   20) Window("Flight Reservation").WinRadioButton("Economy").Set
   21) e=Window("Flight Reservation").WinEdit("Price:").GetVisibleText
   22) f=cdbl(mid(f,2,len (f-1)))
   23) b=cdbl(mid(b,2,len (b-1)))
   24) e=cdbl(mid(e,2,len (e-1)))
   25) If f=3*e and b=2*e Then
   26) Reporter.ReportEvent 0,"Res","Pricy Consistancy is there"
   27) else
   28) Reporter.ReportEvent 1,"Res","Pricy Consistancy is NOT there"
   29) End If
   30) Window("Flight Reservation").WinButton("Button_2").Click
   31) Window("Flight Reservation").Dialog("Flight
       Reservations").WinButton("No").Click
   32) Next


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


   1) Option Explicit
   2) Dim t,p,tot,n
   3) For n= 1 to 10 step 1
   4) If Not window("Flight Reservation").Exist (2) Then
   5) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest
      Professionalsamplesflightappflight4a.exe","","C:Program FilesMercury
      InteractiveQuickTest Professionalsamplesflightapp","open"
   6) Dialog("Login").Activate
   7) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy"
   8) Dialog("Login").WinEdit("Password:").SetSecure
      "4aa892d62c529f1c23298175ad78c58f43da8e34"
   9) Dialog("Login").WinButton("OK").Click
   10) End If


                G.C.Reddy, QTP Trainer (Mobile: 9247837478)                        47
gcrindia@gmail.com

   11) Window("Flight Reservation").Activate
   12) Window("Flight Reservation").WinButton("Button").Click
   13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order
       No.").Set "ON"
   14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set n
   15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click


   16) t=Window("Flight Reservation").WinEdit("Tickets:").GetVisibleText
   17) p=Window("Flight Reservation").WinEdit("Price:").GetVisibleText
   18) tot=Window("Flight Reservation").WinEdit("Total:").GetVisibleText
   19) t=cdbl (t)
   20) p=Cdbl(mid(p,2,len (p-1)))
   21) tot=Cdbl(mid(tot,2,len (tot-1)))


   22) If tot=t*p Then
   23) Reporter.ReportEvent 0,"Res","Calculation Passed"
   24) else
   25) Reporter.ReportEvent 1,"Res","Calculation Failed"
   26) End If
   27) Next


7) Verify Flight From & Flight To Combo Boxes (In Flight reservation, select an
item from Fly From: combo box and verify weather that item available or not in Fly
To: combo box, like this select all items one by one in Fly From and verify weather
selected items available or not in Fly To.)
       1) Option explicit
       2) Dim qtp,flight_app,f,t,i,j,x,y
       3) If Not Window("text:=Flight Reservation").Exist (7)= True Then
       4) QTP=Environment("ProductDir")
       5) Flight_app="samplesflightappflight4a.exe"
       6) SystemUtil.Run QTP & Flight_app
       7) Dialog("text:=Login").Activate
       8) Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set "asdf"
       9) Dialog("text:=Login").WinEdit("attached text:=Password:").SetSecure
          "4aa5ed3daf680e7a759bee1c541939d3a54a5b65"
       10) Dialog("text:=Login").WinButton("text:=OK").Click
       11) End If


                G.C.Reddy, QTP Trainer (Mobile: 9247837478)                       48
gcrindia@gmail.com

      12) Window("text:=Flight Reservation").Activate
      13) Window("text:=Flight Reservation").WinButton("window id:=6").Click
      14) Window("text:=Flight
          Reservation").ActiveX("acx_name:=MaskEdBox","window id:=0").Type
          "090910"
      15) f=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly
          From:").GetItemsCount
      16) For i= 0 to f-1 step 1
      17) Window("text:=Flight Reservation").WinComboBox("attached text:=Fly
          From:").Select (i)
      18) x=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly
          From:").GetROProperty ("text")
      19) t=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly
          To:","x:=244","y:=147").GetItemsCount
      20) For j= 0 to t-1 step 1
      21) Window("text:=Flight Reservation").WinComboBox("attached text:=Fly
          To:","x:=244","y:=147").Select (j)
      22) y=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly
          To:","x:=244","y:=147").GetROProperty ("text")
      23) If x <> y Then
      24) Reporter.ReportEvent 0,"Res","Test Passed"
      25) Else
      26) Reporter.ReportEvent 1,"Res","Test Failed"
      27) End If
      28) Next
      29) Next
8) Verify Order No Entry in Flight Reservation. (In Open Order dialog box,
Order No object accepts numeric values only.)


   1) If Not window("Flight Reservation").Exist (2) Then
   2) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest
      Professionalsamplesflightappflight4a.exe"
   3) Dialog("Login").Activate
   4) Dialog("Login").WinEdit("Agent Name:").Set "asdf"
   5) Dialog("Login").WinEdit("Password:").SetSecure
      "4aa9ccae3bb00962b47ff7fb0ce3524c1d88cb43"
   6) Dialog("Login").WinButton("OK").Click
   7) End If
   8) Window("Flight Reservation").Activate



                 G.C.Reddy, QTP Trainer (Mobile: 9247837478)                   49
gcrindia@gmail.com

   9) Window("Flight Reservation").WinButton("Button").Click
   10) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order
       No.").Set "ON"
   11) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "a"
   12) ord=Window("Flight Reservation").Dialog("Open
       Order").WinEdit("Edit").GetVisibleText
   13) If ord= "a" Then
   14) Reporter.ReportEvent 1,"Res","Order No Object is taking invalid data"
   15) else
   16) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "1"
   17) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
   18) End If
   9) Get Test Data from a Flat file and use in Data Driven Testing (through
   Scripting)
      1) Dim fso,myfile
      2) Set fso=createobject("scripting.filesystemobject")
      3) Set myfile= fso.opentextfile ("F:gcr.txt",1)
      4) myfile.skipline
      5) While myfile.atendofline <> True
      6) x=myfile.readline
      7) s=split (x, ",")
      8) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest
         Professionalsamplesflightappflight4a.exe"
      9) Dialog("Login").Activate
      10) Dialog("Login").WinEdit("Agent Name:").Set s(0)
      11) Dialog("Login").WinEdit("Password:").SetSecure s(1)
      12) Dialog("Login").WinButton("OK").Click
      13) Window("Flight Reservation").Close
      14) Wend
10) 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")




                G.C.Reddy, QTP Trainer (Mobile: 9247837478)                        50
gcrindia@gmail.com

   5) con.open "C:Documents and SettingsAdministratorMy
      DocumentsGcr.mdb"
   6) rs.open "Select * From Login",con
   7) While rs.eof <>True
   8) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest
      Professionalsamplesflightappflight4a.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


11) Count, how many links available in Mercury Tours Home Page.
   1) Set oDesc = Description.Create()
   2) oDesc("micclass").Value = "Link"
   3) Set Lists = Browser("Welcome: Mercury").Page("Welcome:
      Mercury").ChildObjects (oDesc)
   4) NumberOfLinks = Lists.Count()
   5) Reporter.ReportEvent 2,"Res","Number of Links are: "&NumberOfLinks


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


      1) If Not window("Flight Reservation").Exist (2) Then
      2) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest
         Professionalsamplesflightappflight4a.exe"
      3) Dialog("Login").Activate
      4) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy"
      5) Dialog("Login").WinEdit("Password:").Set "mercury"
      6) Dialog("Login").WinButton("OK").Click
      7) End If
      8) Set oDesc = Description.Create()
      9) oDesc("micclass").Value = "WinButton"
      10) Set Buttons = Window("text:=Flight Reservation").ChildObjects (oDesc)
      11) Num_Buttons = Buttons.Count()


              G.C.Reddy, QTP Trainer (Mobile: 9247837478)                         51
gcrindia@gmail.com

       12) Set oDesc1=Description.Create()
       13) oDesc1("micclass").Value="WinEdit"
       14) Set Editboxes=Window("text:=Flight Reservation").ChildObjects (oDesc1)
       15) Num_Editboxes= editboxes.count ()
       16) sum= Num_Buttons+Num_Editboxes
       17) Reporter.ReportEvent 2, "Res","Total Buttons: "& Num_Buttons &"Total
           Edit boxes: "& Num_Editboxes
13) Verify search options in Open Order Dialog box
(After selecting open order, 3 search options should be enabled and not checked,
After selecting Order No option, other options should be disabled,
After selecting Customer Name, Flight date option enabled and Order No disabled
After selecting Flight date option, Customer Name enabled and Order No disabled)


   1) If Not window("Flight Reservation").Exist (2) Then
   2) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest
      Professionalsamplesflightappflight4a.exe"
   3) Dialog("Login").Activate
   4) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy"
   5) Dialog("Login").WinEdit("Password:").SetSecure
      "4aa9ed25bc0ebde66ed726ad87d7e991347d8b9c"
   6) Dialog("Login").WinButton("OK").Click
   7) End If
   8) Window("Flight Reservation").Activate
   9) Window("Flight Reservation").WinButton("Button").Click
   10) Window("Flight Reservation").Dialog("Open Order").Activate
   11) oe=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order
       No.").GetROProperty ("Enabled")
   12) ce=Window("Flight Reservation").Dialog("Open
       Order").WinCheckBox("Customer Name").GetROProperty ("Enabled")
   13) fe=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight
       Date").GetROProperty("Enabled")


   14) oc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order
       No.").GetROProperty ("Checked")
   15) cc=Window("Flight Reservation").Dialog("Open
       Order").WinCheckBox("Customer Name").GetROProperty ("Checked")
   16) fc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight
       Date").GetROProperty("Checked")



               G.C.Reddy, QTP Trainer (Mobile: 9247837478)                         52
gcrindia@gmail.com

17) If (oe=true and ce=true and fe=true) and (oc="OFF" and cc="OFF" and
    fc="OFF") Then
18) Reporter.ReportEvent 0,"Res","Pass"
19) else
20) Reporter.ReportEvent 1,"Res","Fail"
21) End If
22) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order
    No.").Set "ON"
23) ono=Window("Flight Reservation").Dialog("Open
    Order").WinCheckBox("Order No.").GetROProperty ("Checked")
24) If ono="ON" Then
25) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight
    Date").GetROProperty ("Enabled")
26) ono=Window("Flight Reservation").Dialog("Open
    Order").WinCheckBox("Customer Name").GetROProperty ("Enabled")
27) fd=false
28) ono=false
29) Reporter.ReportEvent 0,"Res","Pass"
30) else
31) Reporter.ReportEvent 1,"Res","Fail"
32) End If
33) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order
    No.").Set "OFF"
34) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer
    Name").Set "ON"
35) cn=Window("Flight Reservation").Dialog("Open
    Order").WinCheckBox("Customer Name").GetROProperty ("Checked")
36) If cn="ON" Then
37) ono=Window("Flight Reservation").Dialog("Open
    Order").WinCheckBox("Order No.").GetROProperty ("Enabled")
38) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight
    Date").GetROProperty ("Enabled")
39) fd=True
40) ono=false
41) Reporter.ReportEvent 0,"Res","Pass"
42) else
43) Reporter.ReportEvent 1,"Res","Fail"
44) End If



             G.C.Reddy, QTP Trainer (Mobile: 9247837478)                   53
gcrindia@gmail.com

   45) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer
       Name").Set "OFF"
   46) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight
       Date").Set "ON"
   47) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight
       Date").GetROProperty ("Checked")
   48) If fd="ON" Then
   49) ono=Window("Flight Reservation").Dialog("Open
       Order").WinCheckBox("Order No.").GetROProperty ("Enabled")
   50) cn=Window("Flight Reservation").Dialog("Open
       Order").WinCheckBox("Customer Name").GetROProperty ("Enabled")
   51) cn=True
   52) ono=false
   53) Reporter.ReportEvent 0,"Res","Pass"
   54) else
   55) Reporter.ReportEvent 1,"Res","Fail"
   56) End If
14) In Login Dialog box, Verify Help message (The message is ‘The password is
'MERCURY')
   1) If Not Dialog("Login").Exist (2) Then
   2) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest
      Professionalsamplesflightappflight4a.exe"
   3) End If
   4) Dialog("Login").Activate
   5) Dialog("Login").WinButton("Help").Click
   6) message=Dialog("Login").Dialog("Flight Reservations").Static("The password
      is 'MERCURY'").GetROProperty("text")
   7) If message="The password is 'MERCURY'" Then
   8) Reporter.ReportEvent 0,"Res","Correct message "&message
   9) else
   10) Reporter.ReportEvent 1,"Res","Worng message "
   11) End If


15) Count all opened Browsers on desktop and close them all?
   1) Set oDesc = Description.Create()
   2) oDesc("micclass").Value = "Browser"
   3) Set Browsers =Desktop.ChildObjects (oDesc)
   4) NumberofBrowsers = Browsers.Count()


                G.C.Reddy, QTP Trainer (Mobile: 9247837478)                    54
gcrindia@gmail.com

   5) Reporter.ReportEvent 2,"Res","Number of Browsers are:
      "&NumberOfBrowsers
   6) For Counter=0 to NumberofBrowsers-1
   7) Browsers(Counter).Close
   8) Next


16) 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




              G.C.Reddy, QTP Trainer (Mobile: 9247837478)                  55
gcrindia@gmail.com


             QTP Add-Ins Information
I) ActiveX Environment

       Object                           Description
ActiveX               An ActiveX control.
AcxButton             An ActiveX button.
AcxCalendar           An ActiveX calendar object.
AcxCheckBox           An ActiveX check box.
AcxComboBox           An ActiveX combo box object.
AcxEdit               An ActiveX edit box.
AcxRadioButton        An ActiveX radio button.
AcxTable              An ActiveX table.
                      An object that enables you to work with objects
AcxUtil               returned by performing an operation (usually via
                      the Object property) on an ActiveX test object.

II) Delphi Environment

     Object                            Description
DelphiButton      A   Delphi   button.
DelphiCheckBox A      Delphi   check box.
DelphiComboBox A      Delphi   combo box.
DelphiEdit        A   Delphi   edit box.
DelphiEditor      A   Delphi   multi-line editor.
DelphiList        A   Delphi   list.
DelphiListView    A   Delphi   list-view control.
DelphiNavigator   A   Delphi   navigator control.
DelphiObject      A   Delphi   object.
DelphiRadioButton A   Delphi   radio button.
DelphiScrollBar   A   Delphi   scroll bar.
DelphiSpin        A   Delphi   spin box.
DelphiStatic      A   Delphi   static control.
DelphiStatusBar A     Delphi   status bar.
DelphiTable       A   Delphi   table.
DelphiTabStrip    A   Delphi   tab strip.
DelphiTreeView    A   Delphi   tree-view control.


           G.C.Reddy, QTP Trainer (Mobile: 9247837478)               56
gcrindia@gmail.com


DelphiWindow        A Delphi window or dialog box.

III) Java Environment

               Object                            Description
JavaApplet                          A Java applet.
JavaButton                          A Java button.
JavaCalendar                        A Java calendar.
JavaCheckBox                        A Java check box.
JavaDialog                          A Java dialog box.
JavaEdit                            A Java edit box.
                                    A Java control that contains labeled
JavaExpandBar                       bar items, which can be expanded
                                    or collapsed by the user.
                                    An internal frame that can be
JavaInternalFrame
                                    activated from the Java applet.
                                    A Java control that displays text
JavaLink
                                    with links.
                                    A Java list box with single or
JavaList
                                    multiple selection.
JavaMenu                            A Java menu item.
JavaObject                          A generic Java object.
JavaRadioButton                     A Java radio button.
JavaSlider                          A Java slider.
JavaSpin                            A Java spin object.
JavaStaticText                      A Java static text object.
                                    A Java tabstrip control containing
JavaTab
                                    tabbed panels.
JavaTable                           A Java table.
JavaToolbar                         A Java toolbar.
JavaTree                            A Java tree.
JavaWindow                          A Java window.

IV) .NET Web Forms Environment

   Object                  Description
WbfCalendar      A .NET Web Forms calendar control.
WbfGrid          A .NET Web Forms DataGrid object.


              G.C.Reddy, QTP Trainer (Mobile: 9247837478)             57
gcrindia@gmail.com


WbfTabStrip      A   .NET   Web   Forms   tabstrip control.
WbfToolbar       A   .NET   Web   Forms   toolbar control.
WbfTreeView      A   .NET   Web   Forms   tree view object.
WbfUltraGrid     A   .NET   Web   Forms   UltraGrid object.

V) .NET Windows Forms Environment

      Object                               Description
SwfButton               A .NET Windows Forms button object.
                        A DateTimePicker or a Month Calendar .NET
SwfCalendar
                        Windows Forms calendar object.
SwfCheckBox             A .NET Windows Forms check box.
SwfComboBox             A .NET Windows Forms combo box.
SwfEdit                 A .NET Windows Forms edit box.
SwfEditor               A .NET Windows Forms multi-line edit box.
SwfLabel                A .NET Windows Forms static text object.
SwfList                 A .NET Windows Forms list.
SwfListView             A .NET Windows Forms ListView control.
SwfObject               A standard .NET Windows Forms object.
                        A property grid control based on the .NET
SwfPropertyGrid
                        Windows Forms library.
SwfRadioButton          A .NET Windows Forms radio button.
SwfScrollBar            A .NET Windows Forms scroll bar.
SwfSpin                 A .NET Windows Forms spin object.
SwfStatusBar            A .NET Windows Forms status bar control.
SwfTab                  A .NET Windows Forms tab control.
                        A grid control based on the .NET Windows Forms
SwfTable
                        library.
SwfToolBar              A .NET Windows Forms toolbar.
SwfTreeView             A .NET Windows Forms TreeView control.
SwfWindow               A .NET Windows Forms window.


VI) Windows Presentation Foundation Environment

      Object                               Description
                        A button control in a Windows Presentation
WpfButton
                        Foundation application.


              G.C.Reddy, QTP Trainer (Mobile: 9247837478)              58
gcrindia@gmail.com


                       A check box control in a Windows Presentation
WpfCheckBox
                       Foundation application.
                       A combo box control in a Windows Presentation
WpfComboBox
                       Foundation application.
                       A document, rich text box, or text control in a
WpfEdit
                       Windows Presentation Foundation application.
                       A grid control in a Windows Presentation
WpfGrid
                       Foundation application.
                       An image control in a Windows Presentation
WpfImage
                       Foundation application.
                       A hyperlink control in a Windows Presentation
WpfLink
                       Foundation application.
                       A list control in a Windows Presentation
WpfList
                       Foundation application.
                       A menu control in a Windows Presentation
WpfMenu
                       Foundation application.
                       An object control in a Windows Presentation
WpfObject
                       Foundation application.
                       A progress bar control in a Windows Presentation
WpfProgressBar
                       Foundation application.
                       A radio button control in a Windows Presentation
WpfRadioButton
                       Foundation application.
                       A scroll bar control in a Windows Presentation
WpfScrollBar
                       Foundation application.
                       A slider control in a Windows Presentation
WpfSlider
                       Foundation application.
                       A status bar control in a Windows Presentation
WpfStatusBar
                       Foundation application.
                       A tab control in a Windows Presentation
WpfTabStrip
                       Foundation application.
                       A toolbar control in a Windows Presentation
WpfToolbar
                       Foundation application.
                       A tree control in a Windows Presentation
WpfTreeView
                       Foundation application.
                       A window control in a Windows Presentation
WpfWindow
                       Foundation application.




              G.C.Reddy, QTP Trainer (Mobile: 9247837478)            59
gcrindia@gmail.com



VII) Oracle Environment

       Object                         Description
OracleApplications An Oracle Applications session window.
OracleButton       An Oracle button.
OracleCalendar     An Oracle calendar.
OracleCheckbox     A check box Oracle field.
OracleFlexWindow   An Oracle flexfield window.
OracleFormWindow   An Oracle Form window.
OracleList         An Oracle poplist (combo box) or list.
                   An Oracle window containing a list of values for
OracleListOfValues
                   selection.
OracleLogon        An Oracle Applications sign-on window.
OracleNavigator    An Oracle Navigator window.
OracleNotification An Oracle error or message window.
OracleRadioGroup   An Oracle option (radio button) group.
                   The status line and message line at the bottom
OracleStatusLine
                   of an Oracle Applications window.
OracleTabbedRegion An Oracle tabbed region.
OracleTable        An Oracle block of records.
OracleTextField    An Oracle text field.
OracleTree         An Oracle tree.

VIII) PeopleSoft Environment

     Object                          Description
PSFrame              A frame object within a PeopleSoft application.

IX) PowerBuilder Environment

    Object                  Description
PbButton       A   PowerBuilder button.
PbCheckBox     A   PowerBuilder check box.
PbComboBox     A   PowerBuilder combo box.
PbDataWindow   A   PowerBuilder DataWindow control.
PbEdit         A   PowerBuilder edit box.
PbList         A   PowerBuilder list.


            G.C.Reddy, QTP Trainer (Mobile: 9247837478)                60
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book
Advanced Qtp Book

Weitere ähnliche Inhalte

Andere mochten auch

Thomson reuters qtp training presentation
Thomson reuters qtp training presentationThomson reuters qtp training presentation
Thomson reuters qtp training presentationSravan Vasireddy
 
Qtp interview questions and answers
Qtp interview questions and answersQtp interview questions and answers
Qtp interview questions and answersRamu Palanki
 
QTP Descriptive Programming Unplugged Book
QTP Descriptive Programming Unplugged BookQTP Descriptive Programming Unplugged Book
QTP Descriptive Programming Unplugged BookTarun Lalwani
 
QTP Descriptive Programming
QTP Descriptive ProgrammingQTP Descriptive Programming
QTP Descriptive ProgrammingYaron Assa
 

Andere mochten auch (6)

Thomson reuters qtp training presentation
Thomson reuters qtp training presentationThomson reuters qtp training presentation
Thomson reuters qtp training presentation
 
Qtp interview questions and answers
Qtp interview questions and answersQtp interview questions and answers
Qtp interview questions and answers
 
QTP/UFT latest interview questions 2014
QTP/UFT latest interview questions 2014QTP/UFT latest interview questions 2014
QTP/UFT latest interview questions 2014
 
Automation Framework/QTP Framework
Automation Framework/QTP FrameworkAutomation Framework/QTP Framework
Automation Framework/QTP Framework
 
QTP Descriptive Programming Unplugged Book
QTP Descriptive Programming Unplugged BookQTP Descriptive Programming Unplugged Book
QTP Descriptive Programming Unplugged Book
 
QTP Descriptive Programming
QTP Descriptive ProgrammingQTP Descriptive Programming
QTP Descriptive Programming
 

Ähnlich wie Advanced Qtp Book (20)

Advanced+qtp+open+order
Advanced+qtp+open+orderAdvanced+qtp+open+order
Advanced+qtp+open+order
 
Vbs
VbsVbs
Vbs
 
7400354 vbscript-in-qtp
7400354 vbscript-in-qtp7400354 vbscript-in-qtp
7400354 vbscript-in-qtp
 
VB Script Overview
VB Script OverviewVB Script Overview
VB Script Overview
 
Typescript Basics
Typescript BasicsTypescript Basics
Typescript Basics
 
Vb script
Vb scriptVb script
Vb script
 
Java Script
Java ScriptJava Script
Java Script
 
Type script
Type scriptType script
Type script
 
Dot net interview questions and asnwers
Dot net interview questions and asnwersDot net interview questions and asnwers
Dot net interview questions and asnwers
 
Qtp - Introduction to fundamentals of vbscript
Qtp - Introduction to fundamentals of vbscriptQtp - Introduction to fundamentals of vbscript
Qtp - Introduction to fundamentals of vbscript
 
Introduction to Visual Basic
Introduction to Visual Basic Introduction to Visual Basic
Introduction to Visual Basic
 
Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]
 
Vb script
Vb scriptVb script
Vb script
 
Active server pages
Active server pagesActive server pages
Active server pages
 
copa-ii.pptx
copa-ii.pptxcopa-ii.pptx
copa-ii.pptx
 
js.pptx
js.pptxjs.pptx
js.pptx
 
Bca5020 visual programming
Bca5020  visual programmingBca5020  visual programming
Bca5020 visual programming
 
Bca5020 visual programming
Bca5020  visual programmingBca5020  visual programming
Bca5020 visual programming
 
Basic vbscript for qtp
Basic vbscript for qtpBasic vbscript for qtp
Basic vbscript for qtp
 
Qtp classes-in-mumbai
Qtp classes-in-mumbaiQtp classes-in-mumbai
Qtp classes-in-mumbai
 

Kürzlich hochgeladen

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 

Kürzlich hochgeladen (20)

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 

Advanced Qtp Book

  • 1. gcrindia@gmail.com Advanced QTP (In VBScript Orientation) 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) General Examples 10) Loop Through Code 11) Procedures 12) Built-In Functions 13) VBScript syntax rules and guidelines 14) Errors 15) File System Operations 16) Test Requirements 17) Solutions 18) QTP Add-Ins Information 19) VBScript Glossary G.C.Reddy, QTP Trainer (Mobile: 9247837478) 1
  • 2. gcrindia@gmail.com Introduction o VBScript is a scripting language. o A scripting language is a lightweight programming language. o VBScript is a light version of Microsoft's programming language Visual Basic. 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. 1.1 Windows Script Host (WSH) It is a Windows administration tool. WSH creates an environment for hosting scripts. That is, when a script arrives at your computer, WSH plays the part of the host — it makes objects and services available for the script and provides a set of guidelines within which the script is executed. Among other things, Windows Script Host manages security and invokes the appropriate script engine 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.2 Creating a script with Notepad 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" 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). G.C.Reddy, QTP Trainer (Mobile: 9247837478) 2
  • 3. gcrindia@gmail.com 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. 1.4 Available Script Engines 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. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 3
  • 4. gcrindia@gmail.com Comments The comment argument is the text of any comment we want to include. 2.0 Purpose of comments: o We can use comments for making the script understandable. o We can use comments for making one or more statements disable from execution. 2.1 Syntax Rem comment (After the Rem keyword, a space is required before comment.) Or Apostrophe (') symbol before the comment 2.2 Comment/Uncomment a block of statements Select block of statement and use short cut key Ctrl + M (for comment) Select comment block and use short cut key Ctrl + Shift + M (for uncomment) 2.3 Example G.C.Reddy, QTP Trainer (Mobile: 9247837478) 4
  • 5. gcrindia@gmail.com 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. 3.1 Declaring Variables 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: Dim x, Top, Bottom, Left, Right 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. 3.2 Option Explicit Forces explicit declaration of all variables in a script. Option Explicit ' Force explicit variable declaration. Dim MyVar ' Declare variable. MyInt = 10 ' Undeclared variable generates error. MyVar = 10 ' Declared variable does not generate error. 3.3 Naming Restrictions for Variables Variable names follow the standard rules for naming anything in VBScript. A variable name: o Must begin with an alphabetic character. o Cannot contain an embedded period. o Must not exceed 255 characters. o Must be unique in the scope in which it is declared. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 5
  • 6. gcrindia@gmail.com 3.4 Scope of Variables A variable's scope is determined by where we declare it. When we declare a variable within a procedure, only code within that procedure can access or change the value of that variable. If we declare a variable outside a procedure, we make it recognizable to all the procedures in our script. This is a script-level variable, and it has script-level scope. 3.5 Life Time of Variables The lifetime of a variable depends on how long it exists. The lifetime of a script-level variable extends from the time it is declared until the time the script is finished running. At procedure level, a variable exists only as long as you are in the procedure. 3.6 Assigning Values to Variables Values are assigned to variables creating an expression as follows: 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: A = 200 City = “Hyderabad” X=100: Y=200 3.7 Scalar Variables and Array Variables A variable containing a single value is a scalar variable. A variable containing a series of values, is called an array variable. Array variables and scalar variables are declared in the same way, except that the declaration of an array variable uses parentheses () following the variable name. Example: Dim A(3) 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 4, data can be assigned to the elements of an array as follows: G.C.Reddy, QTP Trainer (Mobile: 9247837478) 6
  • 7. gcrindia@gmail.com 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. We can have as many as 60 dimensions, although most people can't comprehend more than three or four dimensions. In the following example, the MyTable variable is a two-dimensional array consisting of 6 rows and 11 columns: Dim MyTable(5, 10) In a two-dimensional array, the first number is always the number of rows; the second number is the number of columns. 3.8 Dynamic Arrays 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() 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) ReDim Preserve MyArray(30) 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. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 7
  • 8. gcrindia@gmail.com VB Script Data Types 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. 4.1 Variant Subtypes 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. 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. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 8
  • 9. gcrindia@gmail.com VB Script Operators Operators are used for performing mathematical, comparison and logical operations. VBScript has a full range of operators, including arithmetic operators, comparison operators, concatenation operators, and logical operators. 4.1 Operator Precedence 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. 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. 4.3 Comparison Operators Used to compare expressions. Operator Description 1) = (Equal to) Used to compare expressions. 2) <> (Not equal to) Used to compare expressions. 3) < Less than 4) > Grater than 5) <= Less than or equal to G.C.Reddy, QTP Trainer (Mobile: 9247837478) 9
  • 10. gcrindia@gmail.com 6) >= Greater than or equal to 7) Is Object equivalence 4.4 Concatenation Operators 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 the Add. other is a string 2) Concatenation Forces string concatenation of two expressions. Operator (&) 4.5 Logical Operators Operator Description Syntax 1) Not Performs logical negation on an result= Not expression expression 2) And Performs a logical conjunction on two result= expression1 And expressions. expression2 3) Or Performs a logical disjunction on two result= expression1 Or expressions. expression2 4) Xor Performs a logical exclusion on two result= expression1 Xor expressions. expression2 5) Eqv Performs a logical equivalence on result= expression1 Eqv two expressions. expression2 6) Imp Performs a logical implication on two result= expression1 Imp expressions. expression2 G.C.Reddy, QTP Trainer (Mobile: 9247837478) 10
  • 11. gcrindia@gmail.com 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) 6.2 MsgBox Function 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. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 11
  • 12. gcrindia@gmail.com VB Script Constants A constant is a meaningful name that takes the place of a number or string and never changes. 7.1 Creating Constants 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 Declares constants for use in place of literal values. Example: Const MyString = "This is my string." Const MyAge = 49 Const CutoffDate = #6-1-97# Note that String literal is enclosed in quotation marks (" "). 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: Const price= 100, city= “Hyderabad”, x= 27 G.C.Reddy, QTP Trainer (Mobile: 9247837478) 12
  • 13. gcrindia@gmail.com 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 2) Select Case Statement 8.1 Making Decisions Using If...Then...Else The If...Then...Else statement is used to evaluate whether a condition is True or False and, depending on the result, to specify one or more statements to run. Usually the condition is an expression that uses a comparison operator to compare one value or variable with another. If...Then...Else statements can be nested to as many levels as you need. 8.1.1 Running a Statement if a Condition is True (single statement) To run only one statement when a condition is True, use the single-line syntax for the If...Then...Else statement. Dim myDate myDate = #2/13/98# If myDate < Now Then myDate = Now 8.1.2 Running Statements if a Condition is True (multiple statements) 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 If x>10 Then msgbox "Hello G.C.Reddy" msgbox "x value is: "&x msgbox "Bye Bye" End If 8.1.3 Running Certain Statements if a Condition is True and Running Others if a Condition is False We can use an If...Then...Else statement to define two blocks of executable statements: one block to run if the condition is True, the other block to run if the condition is False. Example: G.C.Reddy, QTP Trainer (Mobile: 9247837478) 13
  • 14. gcrindia@gmail.com 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 8.1.4 Deciding Between Several Alternatives A variation on the If...Then...Else statement allows us to choose from several alternatives. Adding ElseIf clauses expands the functionality of the If...Then...Else statement so we can control program flow based on different possibilities. Example: Dim x x= Inputbox (" Enter a value") If x>0 and x<=100 Then Msgbox "Hello G.C.Reddy" Msgbox "X is a Small Number" Msgbox "X value is "&x Else IF x>100 and x<=500 Then Msgbox "Hello GCR" Msgbox "X is a Medium Number" Else IF x>500 and x<=1000 Then Msgbox "Hello Chandra Mohan Reddy" Msgbox "X is a Large Number" Else Msgbox "Hello Sir" Msgbox "X is a Grand Number" End If End If End If 8.1.5 Executing a certain block of statements when two / more conditions are True (Nested If...) Example: Dim State, Region State=Inputbox ("Enter a State") Region=Inputbox ("Enter a Region") If state= "AP" Then If Region= "Telangana" Then G.C.Reddy, QTP Trainer (Mobile: 9247837478) 14
  • 15. gcrindia@gmail.com msgbox "Hello G.C.Reddy" msgbox "Dist count is 10" Else if Region= "Rayalasema" Then msgbox "Hello GCR" msgbox "Dist count is 4" Else If Region= "Costal" Then msgbox "Hello Chandra mohan Reddy" msgbox "Dist count is 9" End If End If End If End If 8.2 Making Decisions with Select Case The Select Case structure provides an alternative to If...Then...ElseIf for selectively executing one block of statements from among multiple blocks of statements. A Select Case statement provides capability similar to the If...Then...Else statement, but it makes code more efficient and readable. Example: Option explicit Dim x,y, Operation, Result x= Inputbox (" Enter x value") y= Inputbox ("Enter y value") Operation= Inputbox ("Enter an Operation") Select Case Operation Case "add" Result= cdbl (x)+cdbl (y) 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 G.C.Reddy, QTP Trainer (Mobile: 9247837478) 15
  • 16. gcrindia@gmail.com 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 Other Examples 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") If xyear mod 4=0 Then msgbox "This is a Leap year" Else msgbox "This is NOT" End If 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") If num mod 2=0 Then msgbox "This is a Even Number" Else msgbox "This is a Odd Number" End If 8.3.3 Read two numbers and display the sum? Dim num1,num2, sum num1=inputbox ("Enter num1") num2=inputbox ("Enter num2") sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion require msgbox ("Sum is " &sum) G.C.Reddy, QTP Trainer (Mobile: 9247837478) 16
  • 17. gcrindia@gmail.com 8.3.4 Read P,T,R values and Calculate the Simple Interest? Dim p,t, r, si p=inputbox ("Enter Principle") t=inputbox ("Enter Time") r=inputbox ("Enter Rate of Interest") si= (p*t*r)/100 ' p= principle amount, t=time in years, r= rate of interest msgbox ("Simple Interest is " &si) 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, sum num=inputbox ("Enter a Four digit number") If Len(num) = 4 Then sum=0 sum=sum+num mod 10 num=num/10 num= left (num, 3) sum=sum+num mod 10 num=num/10 num= left (num, 2) sum=sum+num mod 10 num=num/10 num= left (num, 1) sum=sum+num mod 10 msgbox ("Sum is " &sum) else msgbox "Number, you entered is not a 4 digit number" End If 8.3.6 Read any Four-digit number and display the number in reverse order? Dim num,rev num= inputbox("Enter a number") If len(num)=4 Then rev=rev*10 + num mod 10 num=num/10 num= left(num,3) rev=rev*10 + num mod 10 num=num/10 num= left(num,2) rev=rev*10 + num mod 10 num=num/10 num= left(num,1) rev=rev*10 + num mod 10 msgbox "Reverse Order of the number is "&rev G.C.Reddy, QTP Trainer (Mobile: 9247837478) 17
  • 18. gcrindia@gmail.com Else msgbox "Number, you entered is not a 4 digit number" End If 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') Dim e,m,p,c, tot e=inputbox ("Enter english Marks") m=inputbox ("Enter maths Marks") p=inputbox ("Enter physics Marks") c=inputbox ("Enter chemistry Marks") tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c) msgbox tot If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=300 Then msgbox "Grade is Distinction" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=240 and tot<300 Then msgbox "Grade is First" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=200 and tot<240 Then msgbox "Grade is Second" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=160 and tot<200 Then msgbox "Grade is Third" else msgbox "No Grade, Fail" End If End If End If End If 8.3.8 Display Odd numbers up to n? Dim num,n n=Inputbox ("Enter a Vaule") For num= 1 to n step 2 G.C.Reddy, QTP Trainer (Mobile: 9247837478) 18
  • 19. gcrindia@gmail.com msgbox num Next 8.3.9 Display Even numbers up to n? Dim num,n n=Inputbox ("Enter a Vaule") For num= 2 to n step 2 msgbox num Next 8.3.10 display natural numbers up to n and write in a text file? Dim num, n, fso, myfile n= inputbox ("Enter any Value") num=1 For num= 1 to n step 1 Set fso= createobject ("scripting.filesystemobject") set myfile=fso.opentextfile ("E:gcr.txt", 8, true) myfile.writeline num myfile.close Next 8.11 Display Natural numbers in reverse order up to n? Dim num,n n=Inputbox ("Enter a Vaule") For num=n to 1 step -1 msgbox num Next 8.12 Display Natural numbers sum up to n? (Using For...Next Loop) Dim num, n, sum n= inputbox ("Enter a Value") sum=0 For num= 1 to n step 1 sum= sum+num Next msgbox sum 8.13 Display Natural numbers sum up to n? (using While...Wend Loop) Dim num, n, sum n= inputbox ("Enter a Value") While num <=cdbl (n) sum= sum+num num=num+1 Wend msgbox sum G.C.Reddy, QTP Trainer (Mobile: 9247837478) 19
  • 20. gcrindia@gmail.com 8.14 Display Natural numbers sum up to n? (Using Do...Until...Loop) Dim num, n, sum n= inputbox ("Enter a Value") sum=0 num=1 Do sum= sum+num num=num+1 Loop Until num =cdbl (n+1) msgbox sum 8.15 Write a Function for Natural Numbers sum up to n? Function NNumCou (n) Dim num, sum sum=0 For num= 1 to n step 1 sum= sum+num Next msgbox sum End Function 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") d1= left (num,1) d10=Right (num,1) d2=mid (num, 2, len (1)) d3=mid (num, 3, len (1)) d4=mid (num, 4, len (1)) d5=mid (num, 5, len (1)) d6=mid (num, 6, len (1)) d7=mid (num, 7, len (1)) d8=mid (num, 8, len (1)) d9=mid (num, 9, len (1)) If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then msgbox "It is a Numeric Value" else Msgbox "It is NOT Numeric" End If G.C.Reddy, QTP Trainer (Mobile: 9247837478) 20
  • 21. gcrindia@gmail.com 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") d1= left (num,1) d10=Right (num,1) d2=mid (num, 2, len (1)) d3=mid (num, 3, len (1)) d4=mid (num, 4, len (1)) d5=mid (num, 5, len (1)) d6=mid (num, 6, len (1)) d7=mid (num, 7, len (1)) d8=mid (num, 8, len (1)) d9=mid (num, 9, len (1)) If len (num) =10 Then If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then msgbox "It is a Numeric Value" End If End If If len (num) <> 10 Then Msgbox "It is NOT valid Number " End If G.C.Reddy, QTP Trainer (Mobile: 9247837478) 21
  • 22. gcrindia@gmail.com Looping Through Code o Looping allows us to run a group of statements repeatedly. o Some loops repeat statements until a condition is False; o Others repeat statements until a condition is True. o There are also loops that repeat statements a specific number of times. The following looping statements are available in VBScript: o Do...Loop: Loops while or until a condition is True. o While...Wend: Loops while a condition is True. o For...Next: Uses a counter to run statements a specified number of times. o For Each...Next: Repeats a group of statements for each item in a collection or each element of an array. 9.1 Using Do Loops We can use Do...Loop statements to run a block of statements an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True. 9.1.1 Repeating Statements While a Condition is True Repeats a block of statements while a condition is True or until a condition becomes True a) Do While condition Statements ----------- ----------- Loop Or, we can use this below syntax: 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 G.C.Reddy, QTP Trainer (Mobile: 9247837478) 22
  • 23. gcrindia@gmail.com Example: Dim x x=1 Do Msgbox "Hello G.C.Reddy" Msgbox "Hello QTP" x=x+1 Loop While x<5 9.1.2 Repeating a Statement Until a Condition Becomes True c) Do Until condition Statements ----------- ----------- Loop Or, we can use this below syntax: Example: Dim x Do Until x=5 x=x+1 Msgbox "G.C.Reddy" Msgbox "Hello QTP" Loop Or, we can use this below syntax: d) Do Statements ----------- ----------- Loop Until condition Or, we can use this below syntax: Example: Dim x x=1 Do Msgbox “Hello G.C.Reddy” Msgbox "Hello QTP" x=x+1 Loop Until x=5 9.2 While...Wend Statement Executes a series of statements as long as a given condition is True. Syntax: While condition Statements ----------- G.C.Reddy, QTP Trainer (Mobile: 9247837478) 23
  • 24. gcrindia@gmail.com ----------- Wend Example: Dim x x=0 While x<5 x=x+1 msgbox "Hello G.C.Reddy" msgbox "Hello QTP" Wend 9.3 For...Next Statement Repeats a group of statements a specified number of times. Syntax: For counter = start to end [Step step] statements Next Example: Dim x For x= 1 to 5 step 1 Msgbox "Hello G.C.Reddy" Next 9.4 For Each...Next Statement Repeats a group of statements for each element in an array or collection. Syntax: For Each item In array Statements Next Example: (1 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 For Each element In x msgbox element Next Example: (2 MyArray = Array("one","two","three","four","five") For Each element In MyArray G.C.Reddy, QTP Trainer (Mobile: 9247837478) 24
  • 25. gcrindia@gmail.com msgbox element Next Control Flow Examples (Using Conditional and Loop Statements) 11.1 read a number and verify that number Range weather in between 1 to 100 or 101 to 1000? Option explicit Dim a,x a=Inputbox ("Enter a Vaule") a=cdbl(a) If a<= 100 Then For x= 1 to 100 If a=x Then msgbox "a is in between 1 to 100 range" End If Next else For x= 101 to 1000 If a=x Then msgbox "a is in between 101 to 1000 range" End If Next End If 11.1 read Data and find that data size, If size <>4 then display invalid data message, if data size = 4 then verify “a” is there or not in that data? Dim x x=Inputbox ("Enter 4 digit value") x1=Right(x,1) x2=Left (x,1) x3=mid (x,2,Len(1)) x4=mid (x,3,Len(1)) y=len(x) If y=4 Then If x1="a" or x2="a" or x3="a" or x4="a" Then msgbox "a is there" else msgbox "a is Not there" End If else msgbox "Invalid Data" End If G.C.Reddy, QTP Trainer (Mobile: 9247837478) 25
  • 26. gcrindia@gmail.com VB Script Procedures In VBScript, there are two kinds of procedures available; the Sub procedure and the Function procedure. 11.1 Sub Procedures 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: Sub Procedure name () Statements ----------- ----------- End Sub Or Sub Procedure name (argument1, argument2) Statements ----------- ----------- End Sub Example: 1 Sub ConvertTemp() temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperature is " & Celsius(temp) & " degrees C." End Sub Example: 2 11.2 Function Procedures A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but can also return a value. A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 26
  • 27. gcrindia@gmail.com A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant. Syntax: Function Procedure name () Statements ----------- ----------- End Function Or Function Procedure name (argument1, argument2) Statements ----------- ----------- End Function Example: 1 Function Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9 End Function Example: 2 Function cal(a,b,c) cal = (a+b+c) End Function 11.3 Getting Data into and out of Procedures o Each piece of data is passed into our procedures using an argument. o Arguments serve as placeholders for the data we want to pass into our procedure. We can name our arguments any valid variable name. o When we create a procedure using either the Sub statement or the Function statement, parentheses must be included after the name of the procedure. o Any arguments are placed inside these parentheses, separated by commas. 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. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 27
  • 28. gcrindia@gmail.com 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. Call MyProc(firstarg, secondarg) MyProc firstarg, secondarg Notice that the parentheses are omitted in the call when the Call statement isn't used. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 28
  • 29. gcrindia@gmail.com VB Script Built in Functions Types of Functions o Conversions (25) o Dates/Times (19) o Formatting Strings (4) o Input/Output (3) o Math (9) o Miscellaneous (3) o Rounding (5) o Strings (30) o Variants (8) Important Functions 1) Abs Function Returns the absolute value of a number. Dim num num=abs(-50.33) msgbox num 2) Array Function Returns a variant containing an Array Dim A A=Array("hyderabad","chennai","mumbai") msgbox A(0) ReDim A(5) A(4)="nellore" msgbox A(4) 3) Asc Function Returns the ANSI character code corresponding to the first letter in a string. Dim num num=Asc("A") msgbox num * It returns the value 65 * 4) Chr Function Returns the character associated with the specified ANSI character code. Dim char Char=Chr(65) msgbox char * It returns A * G.C.Reddy, QTP Trainer (Mobile: 9247837478) 29
  • 30. gcrindia@gmail.com 5) CInt Function Returns an expression that has been converted to a Variant of subtype Integer. Dim num num=123.45 myInt=CInt(num) msgbox MyInt 6) Date Function Returns the Current System Date. Dim mydate mydate=Date msgbox mydate 7) Day Function Ex1) Dim myday myday=Day("17,December,2009") msgbox myday Ex2) Dim myday mydate=date myday=Day(Mydate) msgbox myday 8) DateDiff Function Returns the number of intervals between two dates. Dim myday mydate=#02-17-2009# x=Datediff("d",mydate,Now) msgbox x 9) Hour Function Returns a whole number between 0 and 23, inclusive, representing the hour of the day. Dim mytime, Myhour mytime=Now myhour=hour (mytime) msgbox myhour 10) Join Function Returns a string created by joining a number of substrings contained in an array. Dim mystring, myarray(3) myarray(0)="Chandra " myarray(1)="Mohan " myarray(2)="Reddy" mystring=Join(MyArray) msgbox mystring G.C.Reddy, QTP Trainer (Mobile: 9247837478) 30
  • 31. gcrindia@gmail.com 11) Eval Function Evaluates an expression and returns the result. 12) Time Function Returns a Variant of subtype Date indicating the current system time. Dim mytime mytime=Time msgbox mytime 13) VarType Function Returns a value indicating the subtype of a variable. Dim MyCheck MyCheck = VarType(300) ' Returns 2. Msgbox Mycheck MyCheck = VarType(#10/19/62#) ' Returns 7. Msgbox Mycheck MyCheck = VarType("VBScript") ' Returns 8. Msgbox Mycheck 14) Left Function Dim MyString, LeftString MyString = "VBSCript" LeftString = Left(MyString, 3) ' LeftString contains "VBS". 14) Right Function Dim AnyString, MyStr AnyString = "Hello World" ' Define string. MyStr = Right(AnyString, 1) ' Returns "d". MyStr = Right(AnyString, 6) ' Returns " World". MyStr = Right(AnyString, 20) ' Returns "Hello World". 15) Len Function Returns the number of characters in a string or the number of bytes required to store a variable. Ex 1): Dim Mystring mystring=Len("G.C.Reddy") msgbox mystring Ex 2): Dim Mystring Mystring=Inputbox("Enter a Value") Mystring=Len(Mystring) Msgbox Mystring G.C.Reddy, QTP Trainer (Mobile: 9247837478) 31
  • 32. gcrindia@gmail.com 16) Mid Function Returns a specified number of characters from a string. Dim MyVar MyVar = Mid("VB Script is fun!", 4, 6) Msgbox MyVar * It Returns ‘Script’ * 17) Timer Function Returns the number of seconds that have elapsed since 12:00 AM (midnight). Function myTime(N) Dim StartTime, EndTime StartTime = Timer For I = 1 To N Next EndTime = Timer myTime= EndTime - StartTime msgbox myTime End Function Call myTime(2000) 17) isNumeric Function Dim MyVar, MyCheck MyVar = 53 MyCheck = IsNumeric(MyVar) msgbox MyCheck MyVar = "459.95" MyCheck = IsNumeric(MyVar) msgbox MyCheck MyVar = "45 Help" MyCheck = IsNumeric(MyVar) msgbox MyCheck * It Returns True/False like Result * 18) 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. Dim Input Input = InputBox("Enter your name") MsgBox ("You entered: " & Input) 19) Msgbox Function 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. Dim MyVar MyVar = MsgBox ("Hello World!", 65, "MsgBox Example") G.C.Reddy, QTP Trainer (Mobile: 9247837478) 32
  • 33. gcrindia@gmail.com VBScript syntax rules and guidelines 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. For example, the two statements below are identical in VBScript: Browser("Mercury").Page("Find a Flight:").WebList("toDay").Select "31" browser("mercury").page("find a flight:").weblist("today").select "31" 21.2 Text strings: 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. Browser("Mercury").Page("Find a Flight:").WaitProperty("items count", Total_Items, 2000) 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: 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. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 33
  • 34. gcrindia@gmail.com 21.7 Spaces: We can add extra blank spaces to our script to improve clarity. These spaces are ignored by VBScript. Errors We have two types Errors in VB Script; they are VBScript Run-time Errors and VBScript Syntax Errors 13.1 VBScript Run-time 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. 13.2 VBScript Syntax Errors VBScript syntax errors are errors that result when the structure of one of our VBScript statements violates one or more of the grammatical rules of the VBScript scripting language. VBScript syntax errors occur during the program compilation stage, before the program has begun to be executed. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 34
  • 35. gcrindia@gmail.com File System Operations I) Working with Drives and Folders a) Creating a Folder Option Explicit Dim objFSO, objFolder, strDirectory strDirectory = "D:logs" Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFolder = objFSO.CreateFolder(strDirectory) b) Deleting a Folder Set oFSO = CreateObject("Scripting.FileSystemObject") oFSO.DeleteFolder("E:FSO") c) Copying Folders Set oFSO=createobject("Scripting.Filesystemobject") oFSO.CopyFolder "E:gcr6", "C:jvr", True d) Checking weather the folder available or not, if not creating the folder Option Explicit Dim objFSO, objFolder, strDirectory strDirectory = "D:logs" 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 e) Returning a collection of Disk Drives Set oFSO = CreateObject("Scripting.FileSystemObject") Set colDrives = oFSO.Drives For Each oDrive in colDrives MsgBox "Drive letter: " & oDrive.DriveLetter Next f) Getting available space on a Disk Drive Set oFSO = CreateObject("Scripting.FileSystemObject") Set oDrive = oFSO.GetDrive("C:") MsgBox "Available space: " & oDrive.AvailableSpace G.C.Reddy, QTP Trainer (Mobile: 9247837478) 35
  • 36. gcrindia@gmail.com II) Working with Flat Files a) Creating a Flat File Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.CreateTextFile("E:ScriptLog.txt") b) Checking weather the File is available or not, if not creating the File strDirectory="E:" strFile="Scripting.txt" Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.FileExists(strDirectory & strFile) Then Set objFolder = objFSO.GetFolder(strDirectory) Else Set objFile = objFSO.CreateTextFile("E:ScriptLog.txt") End if c) Reading Data character by character from a Flat File G.C.Reddy, QTP Trainer (Mobile: 9247837478) 36
  • 37. gcrindia@gmail.com Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("E:gcr.txt", 1) Do Until objFile.AtEndOfStream strCharacters = objFile.Read(1) msgbox strCharacters Loop d) Reading Data line by line from a Flat File Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("E:gcr.txt", 1) Do Until objFile.AtEndOfStream strCharacters = objFile.Readline msgbox strCharacters Loop e) 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:gcr.txt",1) myfile.skipline While myfile.atendofline <> True x=myfile.readline s=split (x, ",") SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe","","C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightapp","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set s(0) Dialog("Login").WinEdit("Password:").SetSecure s(1) Dialog("Login").WinButton("OK").Click Window("Flight Reservation").Close Wend f) Writing data to a text file Dim Stuff, myFSO, WriteStuff, dateStamp dateStamp = Date() Stuff = "I am Preparing this script: " &dateStamp Set myFSO = CreateObject("Scripting.FileSystemObject") Set WriteStuff = myFSO.OpenTextFile("e:gcr.txt", 8, True) WriteStuff.WriteLine(Stuff) WriteStuff.Close SET WriteStuff = NOTHING SET myFSO = NOTHING g) Delete a text file Set objFSO=createobject("Scripting.filesystemobject") Set txtFilepath = objFSO.GetFile("E:gcr.txt") G.C.Reddy, QTP Trainer (Mobile: 9247837478) 37
  • 38. gcrindia@gmail.com txtFilepath.Delete() h) Checking weather the File is available or not, if available delete the File strDirectory="E:" strFile="gcr.txt" Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.FileExists(strDirectory & strFile) Then Set objFile = objFSO.Getfile(strDirectory & strFile) objFile.delete () End if i) Comparing two text files Dim f1, f2 f1="e:gcr1.txt" f2="e:gcr2.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." G.C.Reddy, QTP Trainer (Mobile: 9247837478) 38
  • 39. gcrindia@gmail.com End If j) Counting the number of times a word appears in a file sFileName="E:gcr.txt" sString="gcreddy" Const FOR_READING = 1 Dim oFso, oTxtFile, sReadTxt, oRegEx, oMatches Set oFso = CreateObject("Scripting.FileSystemObject") Set oTxtFile = oFso.OpenTextFile(sFileName, FOR_READING) sReadTxt = oTxtFile.ReadAll Set oRegEx = New RegExp oRegEx.Pattern = sString oRegEx.IgnoreCase = bIgnoreCase oRegEx.Global = True Set oMatches = oRegEx.Execute(sReadTxt) MatchesFound = oMatches.Count Set oTxtFile = Nothing : Set oFso = Nothing : Set oRegEx = Nothing msgbox MatchesFound III) Working with Word Docs a) Create a word document and enter some data & save Dim objWD Set objWD = CreateObject("Word.Application") objWD.Documents.Add objWD.Selection.TypeText "This is some text." & Chr(13) & "This is some more text" objWD.ActiveDocument.SaveAs "e:gcreddy.doc" objWD.Quit IV) Working with Excel Sheets a) Create an excel sheet and enter a value into first cell Dim objexcel Set objExcel = createobject("Excel.application") objexcel.Visible = True objexcel.Workbooks.add objexcel.Cells(1, 1).Value = "Testing" objexcel.ActiveWorkbook.SaveAs("f:gcreddy1.xls") objexcel.Quit b) Compare two excel files Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True Set objWorkbook1= objExcel.Workbooks.Open("E:gcr1.xls") Set objWorkbook2= objExcel.Workbooks.Open("E:gcr2.xls") G.C.Reddy, QTP Trainer (Mobile: 9247837478) 39
  • 40. gcrindia@gmail.com Set objWorksheet1= objWorkbook1.Worksheets(1) Set objWorksheet2= objWorkbook2.Worksheets(1) For Each cell In objWorksheet1.UsedRange If cell.Value <> objWorksheet2.Range(cell.Address).Value Then msgbox "value is different" Else msgbox "value is same" End If Next objWorkbook1.close objWorkbook2.close objExcel.quit set objExcel=nothing G.C.Reddy, QTP Trainer (Mobile: 9247837478) 40
  • 41. gcrindia@gmail.com Test Requirements 1) Verify Login Boundary (Check all the boundary conditions of the Login window. Checks to see if the correct message appears in the error window (Flight Reservation Message) 2) Verify Cancel Operation (in Login Dialog box, if user selects cancel button, before enter any data after enter data dialog box should be disappeared.) 3) Verify Addition, Subtraction, Multiplication and Division Operations in Calculator Application. 4) Verify state of Update Order Button, before open an Order and after open an Order (in Flight Reservation before opening an order Update Order button should be disabled after opening an order enabled.) 5) Price Consistency, In Flight Reservation (In Flight Reservation, First class price=3*Economy class price and Business class price=2*Economy class price) 6) Verify Total, In Flight Reservation (In Flight Reservation, Total = Tickets * Price) 7) Verify Flight From & Flight To Combo Boxes (In Flight reservation, select an item from Fly From: combo box and verify weather that item available or not in Fly To: combo box, like this select all items one by one in Fly From and verify weather selected items available or not in Fly To.) 8) Verify Order No Entry in Flight Reservation. (In Open Order dialog box, Order No object accepts numeric values only.) 9) Get Test Data from a Flat file and use in Data Driven Testing (through Scripting) 10) Get Test Data From a Database and use in Data Driven Testing (through Scripting) 11) Count, how many links available in Mercury Tours Home Page? 12) Count how many Buttons and Edit boxes available in Flight Reservation window? G.C.Reddy, QTP Trainer (Mobile: 9247837478) 41
  • 42. gcrindia@gmail.com 13) Verify search options in Open Order Dialog box (After selecting open order, 3 search options should be enabled and not checked, After selecting Order No option, other options should be disabled, After selecting Customer Name, Flight date option enabled and Order No disabled After selecting Flight date option, Customer Name enabled and Order No disabled) 14) In Login Dialog box, Verify Help message (The message is ‘The password is 'MERCURY') 15) Count all opened Browsers on desktop and close all? 16) Create an Excel file, enter some data and save the file through VB scripting? Solutions: 1) Verify Login Boundary (Check all the boundary conditions of the Login dialog box. Checks to see if the correct message appears in the error window (Flight Reservation Message) 1) ApplicationDir = Environment("ProductDir") 2) ApplicationPath = "samplesflightappflight4a.exe" 3) If Window("Flight Reservation").Exist(2) Then 4) Window("Flight Reservation").Close 5) SystemUtil.Run ApplicationDir & ApplicationPath 6) Elseif Not Dialog("Login").Exist(1) Then 7) SystemUtil.Run ApplicationDir & ApplicationPath 8) End If 9) Dialog("Login").WinEdit("Agent Name:").Set Datatable.Value ("AgentName",dtGlobalSheet) 10) Dialog("Login").WinEdit("Password:").Set Datatable.Value ("Password",dtGlobalSheet) 11) Dialog("Login").WinButton("OK").Click 12) If Dialog("Login").Dialog("Flight Reservations").Exist(1) and Datatable.Value ("Status",dtGlobalSheet)="Fail" Then 13) Dialog("Login").Dialog("Flight Reservations").Static("Agent name must be at").Check CheckPoint("Agent name must be at least 4 characters long.") 14) Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click G.C.Reddy, QTP Trainer (Mobile: 9247837478) 42
  • 43. gcrindia@gmail.com 15) Elseif Window("Flight Reservation").Exist(10) and Datatable.Value ("Status",dtGlobalSheet)="Pass" Then 16) Reporter.ReportEvent PASS,"Login: ","Succeeded" 17) Else 18) Reporter.ReportEvent Fail,"Login: ","Combination #" & Datatable.GetCurrentRow & " was not according to Excel file" 19) End If 2) Verify Cancel Operation (in Login Dialog box, if user selects cancel button, before enter any data after enter data dialog box should be disappeared.) 1) Invokeapplication "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe" 2) Dialog("Login").Activate 3) Dialog("Login").WinButton("Cancel").Click 4) If Dialog("Login").Exist (2) =True Then 5) Reporter.ReportEvent 1,"sd","Fail" 6) Else 7) Reporter.ReportEvent 0,"sd","Pass" 8) Invokeapplication "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe" 9) End If 10) Dialog("Login").Activate 11) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 12) Dialog("Login").WinButton("Cancel").Click 13) If Dialog("Login").Exist (2) =True Then 14) Reporter.ReportEvent 1,"sd","Fail" 15) Else 16) Reporter.ReportEvent 0,"sd","Pass" 17) Invokeapplication "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe" 18) End If 19) Dialog("Login").Activate 20) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 21) Dialog("Login").WinEdit("Password:").SetSecure "4a993af45dcbd506c8451b274d2da07b38ff5531" 22) Dialog("Login").WinButton("Cancel").Click G.C.Reddy, QTP Trainer (Mobile: 9247837478) 43
  • 44. gcrindia@gmail.com 23) If Dialog("Login").Exist (2)=True Then 24) Reporter.ReportEvent 1,"sd","Fail" 25) Else 26) Reporter.ReportEvent 0,"sd","Pass" 27) Invokeapplication "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe" 28) End If 29) Dialog("Login").Activate 30) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 31) Dialog("Login").WinEdit("Password:").SetSecure "4a993af45dcbd506c8451b274d2da07b38ff5531" 32) Dialog("Login").WinButton("OK").Click 3) Verify Addition, Subtraction, Multiplication and Division Operations in Calculator Application. 1) Dim aRes,sRes,dRes,mRes 2) VbWindow("VbWindow").Activate 3) VbWindow("VbWindow").VbEdit("VbEdit").Set "10" 4) VbWindow("VbWindow").VbEdit("VbEdit_2").Set "20" 5) v1=VbWindow("VbWindow").VbEdit("VbEdit").GetROProperty ("text") 6) v2=VbWindow("VbWindow").VbEdit("VbEdit_2").GetROProperty ("text") 7) VbWindow("VbWindow").VbButton("ADD").Click 8) aRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText 9) VbWindow("VbWindow").VbButton("SUB").Click 10) sRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText 11) VbWindow("VbWindow").VbButton("MUL").Click 12) mRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText 13) VbWindow("VbWindow").VbButton("DIV").Click 14) dRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText 15) v1=cdbl(v1) 16) v2=cdbl(v2) 17) aRes=cdbl (aRes) 18) sRes=cdbl (sRes) 19) mRes=cdbl (mRes) 20) dRes=cdbl (dRes) 21) If aRes=v1+v2 Then G.C.Reddy, QTP Trainer (Mobile: 9247837478) 44
  • 45. gcrindia@gmail.com 22) Reporter.ReportEvent 0,"Res","Addition Passed" 23) else 24) Reporter.ReportEvent 1,"Res","Addition Failed" 25) End If 26) If sRes=v1-v2 Then 27) Reporter.ReportEvent 0,"Res","Subtraction Passed" 28) else 29) Reporter.ReportEvent 1,"Res","Subtraction Failed" 30) End If 31) If mRes=v1*v2 Then 32) Reporter.ReportEvent 0,"Res","Multiplecation Passed" 33) else 34) Reporter.ReportEvent 1,"Res","Multiplecation Failed" 35) End If 36) If dRes=v1/v2 Then 37) Reporter.ReportEvent 0,"Res","Division Passed" 38) else 39) Reporter.ReportEvent 1,"Res","Division Failed" 40) End If 4) Verify state of Update Order Button, before open an Order and after open an Order (in Flight Reservation before opening an order Update Order button should be disabled after opening an order enabled.) 1) Option explicit 2) Dim bo,ao 3) If Not window("Flight Reservation").Exist (2) Then 4) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe" 5) Dialog("Login").Activate 6) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy" 7) Dialog("Login").WinEdit("Password:").SetSecure "4aa8bce9984f1a15ea187a2da5b18c545abb01cf" 8) Dialog("Login").WinButton("OK").Click 9) End If 10) Window("Flight Reservation").Activate 11) bo=Window("Flight Reservation").WinButton("Update Order").GetROProperty ("Enabled") G.C.Reddy, QTP Trainer (Mobile: 9247837478) 45
  • 46. gcrindia@gmail.com 12) Window("Flight Reservation").WinButton("Button").Click 13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "1" 15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click 16) ao=Window("Flight Reservation").WinButton("Update Order").GetROProperty ("Enabled") 17) If bo=False Then 18) Reporter.ReportEvent 0,"Res","Update Order Button Disabled" 19) else 20) Reporter.ReportEvent 1,"Res","Update Order Button Enabled" 21) End If 22) If ao=True Then 23) Reporter.ReportEvent 0,"Res","Update Order Button Enabled" 24) else 25) Reporter.ReportEvent 1,"Res","Update Order Button Disabled" 26) End If 5) Price Consistency, In Flight Reservation (In Flight Reservation, First class price=3*Economy class price and Business class price=2*Economy class price) 1) Option explicit 2) Dim n,f,b,e 3) If Not window("Flight Reservation").Exist (2) Then 4) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe" 5) Dialog("Login").Activate 6) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 7) Dialog("Login").WinEdit("Password:").SetSecure "4aa8b7b7c5823680cfcb24d30714c9bbf0dff1eb" 8) Dialog("Login").WinButton("OK").Click 9) End If 10) For n= 1 to 10 step 1 11) Window("Flight Reservation").Activate 12) Window("Flight Reservation").WinButton("Button").Click 13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" G.C.Reddy, QTP Trainer (Mobile: 9247837478) 46
  • 47. gcrindia@gmail.com 14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set n 15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click 16) Window("Flight Reservation").WinRadioButton("First").Set 17) f=Window("Flight Reservation").WinEdit("Price:").GetVisibleText 18) Window("Flight Reservation").WinRadioButton("Business").Set 19) b=Window("Flight Reservation").WinEdit("Price:").GetVisibleText 20) Window("Flight Reservation").WinRadioButton("Economy").Set 21) e=Window("Flight Reservation").WinEdit("Price:").GetVisibleText 22) f=cdbl(mid(f,2,len (f-1))) 23) b=cdbl(mid(b,2,len (b-1))) 24) e=cdbl(mid(e,2,len (e-1))) 25) If f=3*e and b=2*e Then 26) Reporter.ReportEvent 0,"Res","Pricy Consistancy is there" 27) else 28) Reporter.ReportEvent 1,"Res","Pricy Consistancy is NOT there" 29) End If 30) Window("Flight Reservation").WinButton("Button_2").Click 31) Window("Flight Reservation").Dialog("Flight Reservations").WinButton("No").Click 32) Next 6) Verify Total, In Flight Reservation (In Flight Reservation, Total = Tickets * Price) 1) Option Explicit 2) Dim t,p,tot,n 3) For n= 1 to 10 step 1 4) If Not window("Flight Reservation").Exist (2) Then 5) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe","","C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightapp","open" 6) Dialog("Login").Activate 7) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy" 8) Dialog("Login").WinEdit("Password:").SetSecure "4aa892d62c529f1c23298175ad78c58f43da8e34" 9) Dialog("Login").WinButton("OK").Click 10) End If G.C.Reddy, QTP Trainer (Mobile: 9247837478) 47
  • 48. gcrindia@gmail.com 11) Window("Flight Reservation").Activate 12) Window("Flight Reservation").WinButton("Button").Click 13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set n 15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click 16) t=Window("Flight Reservation").WinEdit("Tickets:").GetVisibleText 17) p=Window("Flight Reservation").WinEdit("Price:").GetVisibleText 18) tot=Window("Flight Reservation").WinEdit("Total:").GetVisibleText 19) t=cdbl (t) 20) p=Cdbl(mid(p,2,len (p-1))) 21) tot=Cdbl(mid(tot,2,len (tot-1))) 22) If tot=t*p Then 23) Reporter.ReportEvent 0,"Res","Calculation Passed" 24) else 25) Reporter.ReportEvent 1,"Res","Calculation Failed" 26) End If 27) Next 7) Verify Flight From & Flight To Combo Boxes (In Flight reservation, select an item from Fly From: combo box and verify weather that item available or not in Fly To: combo box, like this select all items one by one in Fly From and verify weather selected items available or not in Fly To.) 1) Option explicit 2) Dim qtp,flight_app,f,t,i,j,x,y 3) If Not Window("text:=Flight Reservation").Exist (7)= True Then 4) QTP=Environment("ProductDir") 5) Flight_app="samplesflightappflight4a.exe" 6) SystemUtil.Run QTP & Flight_app 7) Dialog("text:=Login").Activate 8) Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set "asdf" 9) Dialog("text:=Login").WinEdit("attached text:=Password:").SetSecure "4aa5ed3daf680e7a759bee1c541939d3a54a5b65" 10) Dialog("text:=Login").WinButton("text:=OK").Click 11) End If G.C.Reddy, QTP Trainer (Mobile: 9247837478) 48
  • 49. gcrindia@gmail.com 12) Window("text:=Flight Reservation").Activate 13) Window("text:=Flight Reservation").WinButton("window id:=6").Click 14) Window("text:=Flight Reservation").ActiveX("acx_name:=MaskEdBox","window id:=0").Type "090910" 15) f=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").GetItemsCount 16) For i= 0 to f-1 step 1 17) Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").Select (i) 18) x=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").GetROProperty ("text") 19) t=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").GetItemsCount 20) For j= 0 to t-1 step 1 21) Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").Select (j) 22) y=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").GetROProperty ("text") 23) If x <> y Then 24) Reporter.ReportEvent 0,"Res","Test Passed" 25) Else 26) Reporter.ReportEvent 1,"Res","Test Failed" 27) End If 28) Next 29) Next 8) Verify Order No Entry in Flight Reservation. (In Open Order dialog box, Order No object accepts numeric values only.) 1) If Not window("Flight Reservation").Exist (2) Then 2) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe" 3) Dialog("Login").Activate 4) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 5) Dialog("Login").WinEdit("Password:").SetSecure "4aa9ccae3bb00962b47ff7fb0ce3524c1d88cb43" 6) Dialog("Login").WinButton("OK").Click 7) End If 8) Window("Flight Reservation").Activate G.C.Reddy, QTP Trainer (Mobile: 9247837478) 49
  • 50. gcrindia@gmail.com 9) Window("Flight Reservation").WinButton("Button").Click 10) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 11) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "a" 12) ord=Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").GetVisibleText 13) If ord= "a" Then 14) Reporter.ReportEvent 1,"Res","Order No Object is taking invalid data" 15) else 16) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "1" 17) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click 18) End If 9) Get Test Data from a Flat file and use in Data Driven Testing (through Scripting) 1) Dim fso,myfile 2) Set fso=createobject("scripting.filesystemobject") 3) Set myfile= fso.opentextfile ("F:gcr.txt",1) 4) myfile.skipline 5) While myfile.atendofline <> True 6) x=myfile.readline 7) s=split (x, ",") 8) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe" 9) Dialog("Login").Activate 10) Dialog("Login").WinEdit("Agent Name:").Set s(0) 11) Dialog("Login").WinEdit("Password:").SetSecure s(1) 12) Dialog("Login").WinButton("OK").Click 13) Window("Flight Reservation").Close 14) Wend 10) 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") G.C.Reddy, QTP Trainer (Mobile: 9247837478) 50
  • 51. gcrindia@gmail.com 5) con.open "C:Documents and SettingsAdministratorMy DocumentsGcr.mdb" 6) rs.open "Select * From Login",con 7) While rs.eof <>True 8) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.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 11) Count, how many links available in Mercury Tours Home Page. 1) Set oDesc = Description.Create() 2) oDesc("micclass").Value = "Link" 3) Set Lists = Browser("Welcome: Mercury").Page("Welcome: Mercury").ChildObjects (oDesc) 4) NumberOfLinks = Lists.Count() 5) Reporter.ReportEvent 2,"Res","Number of Links are: "&NumberOfLinks 12) Count, how many Buttons and Edit boxes available in Flight Reservation main window. 1) If Not window("Flight Reservation").Exist (2) Then 2) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe" 3) Dialog("Login").Activate 4) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy" 5) Dialog("Login").WinEdit("Password:").Set "mercury" 6) Dialog("Login").WinButton("OK").Click 7) End If 8) Set oDesc = Description.Create() 9) oDesc("micclass").Value = "WinButton" 10) Set Buttons = Window("text:=Flight Reservation").ChildObjects (oDesc) 11) Num_Buttons = Buttons.Count() G.C.Reddy, QTP Trainer (Mobile: 9247837478) 51
  • 52. gcrindia@gmail.com 12) Set oDesc1=Description.Create() 13) oDesc1("micclass").Value="WinEdit" 14) Set Editboxes=Window("text:=Flight Reservation").ChildObjects (oDesc1) 15) Num_Editboxes= editboxes.count () 16) sum= Num_Buttons+Num_Editboxes 17) Reporter.ReportEvent 2, "Res","Total Buttons: "& Num_Buttons &"Total Edit boxes: "& Num_Editboxes 13) Verify search options in Open Order Dialog box (After selecting open order, 3 search options should be enabled and not checked, After selecting Order No option, other options should be disabled, After selecting Customer Name, Flight date option enabled and Order No disabled After selecting Flight date option, Customer Name enabled and Order No disabled) 1) If Not window("Flight Reservation").Exist (2) Then 2) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe" 3) Dialog("Login").Activate 4) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy" 5) Dialog("Login").WinEdit("Password:").SetSecure "4aa9ed25bc0ebde66ed726ad87d7e991347d8b9c" 6) Dialog("Login").WinButton("OK").Click 7) End If 8) Window("Flight Reservation").Activate 9) Window("Flight Reservation").WinButton("Button").Click 10) Window("Flight Reservation").Dialog("Open Order").Activate 11) oe=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled") 12) ce=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled") 13) fe=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty("Enabled") 14) oc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Checked") 15) cc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Checked") 16) fc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty("Checked") G.C.Reddy, QTP Trainer (Mobile: 9247837478) 52
  • 53. gcrindia@gmail.com 17) If (oe=true and ce=true and fe=true) and (oc="OFF" and cc="OFF" and fc="OFF") Then 18) Reporter.ReportEvent 0,"Res","Pass" 19) else 20) Reporter.ReportEvent 1,"Res","Fail" 21) End If 22) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 23) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Checked") 24) If ono="ON" Then 25) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Enabled") 26) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled") 27) fd=false 28) ono=false 29) Reporter.ReportEvent 0,"Res","Pass" 30) else 31) Reporter.ReportEvent 1,"Res","Fail" 32) End If 33) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "OFF" 34) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").Set "ON" 35) cn=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Checked") 36) If cn="ON" Then 37) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled") 38) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Enabled") 39) fd=True 40) ono=false 41) Reporter.ReportEvent 0,"Res","Pass" 42) else 43) Reporter.ReportEvent 1,"Res","Fail" 44) End If G.C.Reddy, QTP Trainer (Mobile: 9247837478) 53
  • 54. gcrindia@gmail.com 45) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").Set "OFF" 46) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").Set "ON" 47) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Checked") 48) If fd="ON" Then 49) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled") 50) cn=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled") 51) cn=True 52) ono=false 53) Reporter.ReportEvent 0,"Res","Pass" 54) else 55) Reporter.ReportEvent 1,"Res","Fail" 56) End If 14) In Login Dialog box, Verify Help message (The message is ‘The password is 'MERCURY') 1) If Not Dialog("Login").Exist (2) Then 2) SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe" 3) End If 4) Dialog("Login").Activate 5) Dialog("Login").WinButton("Help").Click 6) message=Dialog("Login").Dialog("Flight Reservations").Static("The password is 'MERCURY'").GetROProperty("text") 7) If message="The password is 'MERCURY'" Then 8) Reporter.ReportEvent 0,"Res","Correct message "&message 9) else 10) Reporter.ReportEvent 1,"Res","Worng message " 11) End If 15) Count all opened Browsers on desktop and close them all? 1) Set oDesc = Description.Create() 2) oDesc("micclass").Value = "Browser" 3) Set Browsers =Desktop.ChildObjects (oDesc) 4) NumberofBrowsers = Browsers.Count() G.C.Reddy, QTP Trainer (Mobile: 9247837478) 54
  • 55. gcrindia@gmail.com 5) Reporter.ReportEvent 2,"Res","Number of Browsers are: "&NumberOfBrowsers 6) For Counter=0 to NumberofBrowsers-1 7) Browsers(Counter).Close 8) Next 16) 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 G.C.Reddy, QTP Trainer (Mobile: 9247837478) 55
  • 56. gcrindia@gmail.com QTP Add-Ins Information I) ActiveX Environment Object Description ActiveX An ActiveX control. AcxButton An ActiveX button. AcxCalendar An ActiveX calendar object. AcxCheckBox An ActiveX check box. AcxComboBox An ActiveX combo box object. AcxEdit An ActiveX edit box. AcxRadioButton An ActiveX radio button. AcxTable An ActiveX table. An object that enables you to work with objects AcxUtil returned by performing an operation (usually via the Object property) on an ActiveX test object. II) Delphi Environment Object Description DelphiButton A Delphi button. DelphiCheckBox A Delphi check box. DelphiComboBox A Delphi combo box. DelphiEdit A Delphi edit box. DelphiEditor A Delphi multi-line editor. DelphiList A Delphi list. DelphiListView A Delphi list-view control. DelphiNavigator A Delphi navigator control. DelphiObject A Delphi object. DelphiRadioButton A Delphi radio button. DelphiScrollBar A Delphi scroll bar. DelphiSpin A Delphi spin box. DelphiStatic A Delphi static control. DelphiStatusBar A Delphi status bar. DelphiTable A Delphi table. DelphiTabStrip A Delphi tab strip. DelphiTreeView A Delphi tree-view control. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 56
  • 57. gcrindia@gmail.com DelphiWindow A Delphi window or dialog box. III) Java Environment Object Description JavaApplet A Java applet. JavaButton A Java button. JavaCalendar A Java calendar. JavaCheckBox A Java check box. JavaDialog A Java dialog box. JavaEdit A Java edit box. A Java control that contains labeled JavaExpandBar bar items, which can be expanded or collapsed by the user. An internal frame that can be JavaInternalFrame activated from the Java applet. A Java control that displays text JavaLink with links. A Java list box with single or JavaList multiple selection. JavaMenu A Java menu item. JavaObject A generic Java object. JavaRadioButton A Java radio button. JavaSlider A Java slider. JavaSpin A Java spin object. JavaStaticText A Java static text object. A Java tabstrip control containing JavaTab tabbed panels. JavaTable A Java table. JavaToolbar A Java toolbar. JavaTree A Java tree. JavaWindow A Java window. IV) .NET Web Forms Environment Object Description WbfCalendar A .NET Web Forms calendar control. WbfGrid A .NET Web Forms DataGrid object. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 57
  • 58. gcrindia@gmail.com WbfTabStrip A .NET Web Forms tabstrip control. WbfToolbar A .NET Web Forms toolbar control. WbfTreeView A .NET Web Forms tree view object. WbfUltraGrid A .NET Web Forms UltraGrid object. V) .NET Windows Forms Environment Object Description SwfButton A .NET Windows Forms button object. A DateTimePicker or a Month Calendar .NET SwfCalendar Windows Forms calendar object. SwfCheckBox A .NET Windows Forms check box. SwfComboBox A .NET Windows Forms combo box. SwfEdit A .NET Windows Forms edit box. SwfEditor A .NET Windows Forms multi-line edit box. SwfLabel A .NET Windows Forms static text object. SwfList A .NET Windows Forms list. SwfListView A .NET Windows Forms ListView control. SwfObject A standard .NET Windows Forms object. A property grid control based on the .NET SwfPropertyGrid Windows Forms library. SwfRadioButton A .NET Windows Forms radio button. SwfScrollBar A .NET Windows Forms scroll bar. SwfSpin A .NET Windows Forms spin object. SwfStatusBar A .NET Windows Forms status bar control. SwfTab A .NET Windows Forms tab control. A grid control based on the .NET Windows Forms SwfTable library. SwfToolBar A .NET Windows Forms toolbar. SwfTreeView A .NET Windows Forms TreeView control. SwfWindow A .NET Windows Forms window. VI) Windows Presentation Foundation Environment Object Description A button control in a Windows Presentation WpfButton Foundation application. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 58
  • 59. gcrindia@gmail.com A check box control in a Windows Presentation WpfCheckBox Foundation application. A combo box control in a Windows Presentation WpfComboBox Foundation application. A document, rich text box, or text control in a WpfEdit Windows Presentation Foundation application. A grid control in a Windows Presentation WpfGrid Foundation application. An image control in a Windows Presentation WpfImage Foundation application. A hyperlink control in a Windows Presentation WpfLink Foundation application. A list control in a Windows Presentation WpfList Foundation application. A menu control in a Windows Presentation WpfMenu Foundation application. An object control in a Windows Presentation WpfObject Foundation application. A progress bar control in a Windows Presentation WpfProgressBar Foundation application. A radio button control in a Windows Presentation WpfRadioButton Foundation application. A scroll bar control in a Windows Presentation WpfScrollBar Foundation application. A slider control in a Windows Presentation WpfSlider Foundation application. A status bar control in a Windows Presentation WpfStatusBar Foundation application. A tab control in a Windows Presentation WpfTabStrip Foundation application. A toolbar control in a Windows Presentation WpfToolbar Foundation application. A tree control in a Windows Presentation WpfTreeView Foundation application. A window control in a Windows Presentation WpfWindow Foundation application. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 59
  • 60. gcrindia@gmail.com VII) Oracle Environment Object Description OracleApplications An Oracle Applications session window. OracleButton An Oracle button. OracleCalendar An Oracle calendar. OracleCheckbox A check box Oracle field. OracleFlexWindow An Oracle flexfield window. OracleFormWindow An Oracle Form window. OracleList An Oracle poplist (combo box) or list. An Oracle window containing a list of values for OracleListOfValues selection. OracleLogon An Oracle Applications sign-on window. OracleNavigator An Oracle Navigator window. OracleNotification An Oracle error or message window. OracleRadioGroup An Oracle option (radio button) group. The status line and message line at the bottom OracleStatusLine of an Oracle Applications window. OracleTabbedRegion An Oracle tabbed region. OracleTable An Oracle block of records. OracleTextField An Oracle text field. OracleTree An Oracle tree. VIII) PeopleSoft Environment Object Description PSFrame A frame object within a PeopleSoft application. IX) PowerBuilder Environment Object Description PbButton A PowerBuilder button. PbCheckBox A PowerBuilder check box. PbComboBox A PowerBuilder combo box. PbDataWindow A PowerBuilder DataWindow control. PbEdit A PowerBuilder edit box. PbList A PowerBuilder list. G.C.Reddy, QTP Trainer (Mobile: 9247837478) 60