QTP

131
www.stctek.com 1 VIRTUAL OBJECT VIRTUAL OBJECT In the process of recording the test script when In the process of recording the test script when we click on a feature which is having a specific we click on a feature which is having a specific functionality QTP generating the script statement functionality QTP generating the script statement as if we clicked on screen area (window) Because as if we clicked on screen area (window) Because the feature is non real object, so we have to the feature is non real object, so we have to configure these non real objects. In order to configure these non real objects. In order to differentiate the script statements and to differentiate the script statements and to provide some methods to test this type of provide some methods to test this type of features. features. You can teach Quick Test to recognize any area of You can teach Quick Test to recognize any area of your application as an object by defining it as a your application as an object by defining it as a virtual object. virtual object. Virtual objects enable you to record and run Virtual objects enable you to record and run tests on objects that are not normally recognized tests on objects that are not normally recognized by Quick Test. by Quick Test.

Transcript of QTP

Page 1: QTP

www.stctek.com 1

VIRTUAL OBJECT VIRTUAL OBJECT In the process of recording the test script when we In the process of recording the test script when we click on a feature which is having a specific click on a feature which is having a specific functionality QTP generating the script statement functionality QTP generating the script statement as if we clicked on screen area (window) Because as if we clicked on screen area (window) Because the feature is non real object, so we have to the feature is non real object, so we have to configure these non real objects. In order to configure these non real objects. In order to differentiate the script statements and to provide differentiate the script statements and to provide some methods to test this type of features.some methods to test this type of features.

You can teach Quick Test to recognize any area of You can teach Quick Test to recognize any area of your application as an object by defining it as a your application as an object by defining it as a virtual object. virtual object.

Virtual objects enable you to record and run tests Virtual objects enable you to record and run tests on objects that are not normally recognized by on objects that are not normally recognized by Quick Test. Quick Test.

Using the Virtual Object Wizard, you can map a Using the Virtual Object Wizard, you can map a virtual object to a standard object class, specify the virtual object to a standard object class, specify the boundaries and the parent of the virtual object, and boundaries and the parent of the virtual object, and assign it a logical name.assign it a logical name.

Page 2: QTP

www.stctek.com 2

To define a virtual object: • With Quick Test open (but not in record mode), open With Quick Test open (but not in record mode), open

your Web site or application and display the object your Web site or application and display the object containing the area you want to define as a virtual containing the area you want to define as a virtual object.object.

• In Quick Test, choose Tools > Virtual Objects > New In Quick Test, choose Tools > Virtual Objects > New Virtual Object. The Virtual Object Wizard opens. Click Virtual Object. The Virtual Object Wizard opens. Click Next. Select a standard class to which you want to Next. Select a standard class to which you want to map your virtual object. Click Mark Object. map your virtual object. Click Mark Object.

• The Quick Test window and the Virtual Object Wizard The Quick Test window and the Virtual Object Wizard are minimized. Use the crosshairs pointer to mark the are minimized. Use the crosshairs pointer to mark the area of the virtual object. You can use the arrow keys area of the virtual object. You can use the arrow keys while holding down the left mouse button to make while holding down the left mouse button to make precise adjustments to the area you define with the precise adjustments to the area you define with the crosshairs. Click Next. crosshairs. Click Next. Click an object in the Click an object in the object tree to assign it as the parent of the object tree to assign it as the parent of the virtual object.virtual object.

   

Page 3: QTP

www.stctek.com 3

•In the Identify object-using box, select how you want Quick Test to identify and map the virtual object.

•If you want Quick Test to identify all occurrences of the virtual object, select parent only. Quick Test identifies the virtual object using its direct parent only, regardless of the entire parent hierarchy.

• If you want Quick Test to identify the virtual object in one occurrence only, select entire parent hierarchy. Quick Test identifies the virtual object only if it has the exact parent hierarchy. Click Next.

•Specify a name and a collection for the virtual object. Choose from the list of collections or create a new one by entering a new name in the Collection name box.

•To add the virtual object to the Virtual Object Manager and close the wizard, select No and then click Finish.

Page 4: QTP

www.stctek.com 4

Example: In normal recording if we select the paint brush window, the script will look like this-

window(“Paint”).Activate Window(“Paint”).Winobject(“colors”).Click 72,16 Window(“Paint”).Winobject(“colors”).Click 80,14 window(“Paint”).Close

If we are using Virtual object, the script will look like this-

window(“Paint”).Activate Window(“Paint”).Winobject(“colors”).Virtual Button(“RED”) Window(“Paint”).Winobject(“colors”).Virtual Button(“BLUE”) window(“Paint”).Close

Page 5: QTP

www.stctek.com 5Saturday, April 8, 2023 5

Descriptive Programming-

Without using the object repository test engineer can develop automation test in this particular accept, we need to use a technique called as descriptive programming.

Script: Dialog(“test:=Login”).Activate Dialog(“text;=Login”).wineidt(“attached text:= Login name”). Set

“Axisitt” Dialog(“text:=Login”).wineidt(“attached text:= Password”). Set

“88888” . Dialog(“text:=Login”).Close

Page 6: QTP

www.stctek.com 6

RUNNING TEST IN VERIFY MODE:-

The test can be executes individually or all at once. Initially we execute the test scripts one by one to verify individual screens once we integrate the screens to generate a module we have to execute all the test scripts in a single run sessionto test complete module. Q.T.P provides us two ways to execute multiple test scripts in a single run session.

1. Test Batch Runner2. Automation Object Model (AOM)

Test Batch Runner:- It is used to execute multiple test scripts in order to test the module or complete application. Using this tool we can create a batch file by adding number of Q.T.P scripts. Extension of batch file is .mtb. Once we execute the batch file we can see the results using test results viewer.

Navigation to create & run batch file:Start---Programs---Q.T.P---Tools---Test Batch RunnerTo Add Tests:- Batch---Add---Select Test---Click OpenTo Save Batch File:- File---SaveTo Run Batch File:- Batch---Run

Page 7: QTP

www.stctek.com 7

Navigation to view the results:Start---Programs---Q.T.P---Tools---Test Result Viewer---File---Open---Click Browse Button--- Select the Test---Select Result Name---Click Open

AOM

As we use Q.T.P to automate the manual testing process (developing test & executing test) we can use Q.T.P automation object model to automat Q.T.P itself.Using AOM we can execute number of test scripts in a single run session by configuring them at run time (modifying add in selection, libraries, recovery files, repository files etc.,) using objets, methods &properties provided by Q.T.P AOM.

We can develop a program in vb script file. If we execute the program automatically will be open in that one by one tests are opened configured, executed & closed finally Q.T.P also close. We can see the results using test results viewer.

Page 8: QTP

www.stctek.com 8

Navigation To Develop AOM:- Thru Settings File---Settings---Select the Required Options in the Tabs (Run, Resources, Environment, Recovery)---Click on Apply Button---Click on Generate Script Button in Properties Tab---Select Location—Click Save Button.

STEPS TO DEVELOP AOM PROGRAM:Open Notepad --Write statements in the following manner--Save file

Page 9: QTP

www.stctek.com 9

Save file with .vbs extensionTo execute double click on vb script file icon.AOM:- (Automatic Object Model)Ex:-Dim qtaapSet qtaap=createobject(“Quicktest.Application”)qtaap.launchqtaap.visible=trueqtaap.open “f:\\t1”qtaap.test.settings.run.objectsynctimeout=20qtaap.test.runqtaap.test.closeqtaap.open “f:\\t2”------------------------------qtaap.test.closeqtaap.quitSet qtaap=nothing

Page 10: QTP

www.stctek.com 10

What is VBScript?

VBScript is a subset of Visual Basic 4.0 language. It was developed by Microsoft to provide more processing power to Web pages. VBScript can be used to write both server side and client side scripting.

(If you already know Visual Basic or Visual Basic for Applications (VBA), VBScript will be very familiar. Even if you do not know Visual Basic, once you learn VBScript, you are on your way to programming with the whole family of Visual Basic languages.)

Page 11: QTP

www.stctek.com 11

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.

Page 12: QTP

www.stctek.com 12

VBScript Data TypesVBScript 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.

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

Page 13: QTP

www.stctek.com 13

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

Page 14: QTP

www.stctek.com 14

VBScript VariablesVBScript VariablesDeclaring VariablesDeclaring VariablesYou declare variables explicitly in your script using the Dim statement, You declare variables explicitly in your script using the Dim statement, the Public statement, and the Private statement.the Public statement, and the Private statement.Variables declared with Dim at the script level are available to all Variables declared with Dim at the script level are available to all procedures within the script. At the procedure level, variables are procedures within the script. At the procedure level, variables are available only within the procedure. available only within the procedure.

Public statement variables are available to all procedures in all scripts.Public statement variables are available to all procedures in all scripts.

Private statement variables are available only to the script in which they Private statement variables are available only to the script in which they are declared.are declared.

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

Page 15: QTP

www.stctek.com 15

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 = 200City = “Hyderabad”X=100: Y=200

Page 16: QTP

www.stctek.com 16

Dim varName1 [, varName2...]Private varName1 [, varName2...]Public varName1 [, varName2...]

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.

Page 17: QTP

www.stctek.com 17

Scope of VariablesA 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.

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.

Page 18: QTP

www.stctek.com 18

Scope and Lifetime of VariablesScope and Lifetime of Variables

A variable's scope is determined by where you declare it. When you A variable's scope is determined by where you declare it. When you declare a variable within a procedure, only code within that declare a variable within a procedure, only code within that procedure can access or change the value of that variable. It has procedure can access or change the value of that variable. It has local scope and is a procedure-level variable. If you declare a local scope and is a procedure-level variable. If you declare a variable outside a procedure, you make it recognizable to all the variable outside a procedure, you make it recognizable to all the procedures in your script. This is a script-level variable, and it has procedures in your script. This is a script-level variable, and it has script-level scope.script-level scope.The lifetime of a variable depends on how long it exists. The 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 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 until the time the script is finished running. At procedure level, a variable exists only as long as you are in the procedure. When the variable exists only as long as you are in the procedure. When the procedure exits, the variable is destroyed. Local variables are ideal procedure exits, the variable is destroyed. Local variables are ideal as temporary storage space when a procedure is executing. You as temporary storage space when a procedure is executing. You can have local variables of the same name in several different can have local variables of the same name in several different procedures because each is recognized only by the procedure in procedures because each is recognized only by the procedure in which it is declared. which it is declared.

Page 19: QTP

www.stctek.com 19

Scalar Variables and Array Variables

Much of the time, you only want to assign a single value to a variable you have declared. A variable containing a single value is a scalar variable. Other times, it is convenient to assign more than one related value to a single variable. Then you can create a variable that can contain a series of values. This 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. In the following example, a single-dimension array containing 11 elements is declared: Dim A(10) Although the number shown in the parentheses is 10, all arrays in VBScript are zero-based, so this array actually contains 11 elements. In a zero-based array, the number of array elements is always the number shown in parentheses plus one. This kind of array is called a fixed-size array.

Page 20: QTP

www.stctek.com 20

A(0) = 256A(1) = 324A(2) = 100A(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.

Page 21: QTP

www.stctek.com 21

Some of the Array keywords and their uses:Keyword FunctionDim- It will Declare an arrayErase -Reinitializes the elements if it is a fixed-size array and deallocates the memory used if it is a dynamic array.IsArray -will Return True if A is an array, False if it is notLBound -will Return lower bound of an array, in VBScript it will always returns 0Preserve -Preserve (Optional) is used to preserve the data in an existing array,when you resize it.ReDim- This is used to size or resize a dynamic array.Ubound- will Return an upper bound of array

Page 22: QTP

www.stctek.com 22

Array FunctionReturns a variant containing an Array

SyntaxArray(arglist)

The required arglist argument is a comma-delimited list of values that are assigned to the elements of an array contained with the Variant. If no arguments are specified, an array of zero length is created.

Dim AA=Array("hyderabad","chennai","mumbai")msgbox A(0)ReDim A(5)A(4)="nellore"msgbox A(4)

Page 23: QTP

www.stctek.com 23www.stctek.com

UBound Function Returns the largest available subscript

for the indicated dimension of an array.Syntax : UBound(arrayname[, dimension])Argumentsarrayname Required. Name of the array variable; follows

standardvariable naming conventions. dimension Optional. Whole number indicating which

dimension's upper bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Page 24: QTP

www.stctek.com 24www.stctek.com

Note:The UBound function is used with the

LBound function to determine the size of an array. Use the LBound function to find the lower limit of an array dimension.

The lower bound for any dimension is always 0. As a result, UBound returns the following values for an array with these dimensions:

Dim A(100,3,4)Statement Return ValueUBound(A, 1) 100UBound(A, 2) 3UBound(A, 3) 4

Page 25: QTP

www.stctek.com 25www.stctek.com

LBound FunctionReturns the smallest available subscript for the

indicated dimension of an array.

Syntax:LBound(arrayname[, dimension])

Argumentsarrayname Name of the array variable; follows standard variable

naming conventions. dimension Whole number indicating which dimension's lower

bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Return Value Variant of type Long (0)

Page 26: QTP

www.stctek.com 26www.stctek.com

Note:The LBound function is used with the UBound

function to determine the size of an array. Use the UBound function to find the upper limit of an array dimension.

The lower bound for any dimension is always 0.If dimension isn't specified, 1 is assumed. To

determine the lower limit of the first dimension of an array, set dimension to 1, to 2 for the second, and so on.

Page 27: QTP

www.stctek.com 27www.stctek.com

CONST statementConst StatementDeclares constants for use in place of literal values. [Public | Private] Const constname = expression ArgumentsPublic Optional. Keyword used at script level to declare

constants that are available to all procedures in all scripts. Not allowed in procedures.

Page 28: QTP

www.stctek.com 28www.stctek.com

Private Optional. Keyword used at script level to declare

constants that are available only within the script where the declaration is made. Not allowed in procedures.

constname Required. Name of the constant; follows standard

variable naming conventions.

Page 29: QTP

www.stctek.com 29www.stctek.com

The following code illustrates the use of the Const statement:

Const MyVar = 459 ' Constants are Public by default. Private Const MyString = "HELP" ' Declare Private constant. Const MyStr = "Hello", MyNumber = 3.4567 ' Declare multiple constants on same line.

Note  : Constants can make your scripts self-documenting and easy to modify. Unlike variables, constants cannot be inadvertently changed while your script is running.

Page 30: QTP

www.stctek.com 30

Description SymbolExponentiation ^Unary negation -Multiplication *Division /Integer division \Modulus arithmetic ModAddition +Subtraction -String concatenation &

VBScript Operators Arithmetic Operators

Page 31: QTP

www.stctek.com 31

Description SymbolEquality =Inequality <>Less than <Greater than >Less than or equal to <=

Greater than or equal to >=

Object equivalence Is

Comparison Operators

Page 32: QTP

www.stctek.com 32

Logical Operators

Description SymbolLogical negation NotLogical conjunction AndLogical disjunction OrLogical exclusion XorLogical equivalence EqvLogical implication Imp

Page 33: QTP

www.stctek.com 33

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

Page 34: QTP

www.stctek.com 34

If...Then...Else statement.

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.

Example:

If value = 0 Then AlertLabel.ForeColor = vbRedElse AlertLabel.Forecolor = vbBlackEnd If

Page 35: QTP

www.stctek.com 35

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

Page 36: QTP

www.stctek.com 36

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 xx= 20If x>10 Then

msgbox "Hello G.C.Reddy"msgbox "x value is: "&xmsgbox "Bye Bye"

End If

Page 37: QTP

www.stctek.com 37

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:Dim xx= 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: "&XEnd If

Page 38: QTP

www.stctek.com 38

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 xx= 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

Page 39: QTP

www.stctek.com 39

Else IF x>100 and x<=500 ThenMsgbox "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 IfEnd IfEnd If

Page 40: QTP

www.stctek.com 40

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

Example:

Dim State, RegionState=Inputbox ("Enter a State")Region=Inputbox ("Enter a Region")If state= "AP" Then

If Region= "Telangana" Thenmsgbox "Hello G.C.Reddy"msgbox "Dist count is 10"

Page 41: QTP

www.stctek.com 41

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

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

End IfEnd IfEnd IfEnd If

Page 42: QTP

www.stctek.com 42

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

Page 43: QTP

www.stctek.com 43

Select Case OperationCase "add"

Result= cdbl (x)+cdbl (y)Msgbox "Hello Satish"Msgbox "Addition of x,y values is "&Result

Case "sub"Result= x-yMsgbox "Hello Suresh"Msgbox "Substraction of x,y values is "&Result

Case "mul" Result= x*y

Msgbox "Hello Raman"Msgbox "Multiplication of x,y values is "&Result

Case "div" Result= x/y

Msgbox "Hello Dinesh"Msgbox "Division of x,y values is "&Result

Page 44: QTP

www.stctek.com 44

Case "mod"Result= x mod yMsgbox "Hello Dharmesh"Msgbox "Mod of x,y values is "&Result

Case "expo" Result= x^y

Msgbox "Hello Sarvesh"Msgbox"Exponentation of x,y values is "&Result

Case ElseMsgbox "Hello Harish"msgbox "Wrong Operation"

End Select

Page 45: QTP

www.stctek.com 45

Looping Through Code

•Looping allows us to run a group of statements repeatedly. •Some loops repeat statements until a condition is False; •Others repeat statements until a condition is True. •There are also loops that repeat statements a specific number of times.

The following looping statements are available in VBScript:

Do...Loop: Loops while or until a condition is True.While...Wend: Loops while a condition is True.For...Next: Uses a counter to run statements a specified number of times.For Each...Next: Repeats a group of statements for each item in a collection or each element of an array.

Page 46: QTP

www.stctek.com 46

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.

Page 47: QTP

www.stctek.com 47

Repeating Statements While a Condition is TrueRepeats 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 xDo While x<5 x=x+1

Msgbox "Hello G.C.Reddy"Msgbox "Hello QTP"

Loop

Page 48: QTP

www.stctek.com 48

b) Do Statements ----------- ----------- Loop While condition

Example:

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

Page 49: QTP

www.stctek.com 49

Repeating a Statement Until a Condition Becomes True

c) Do Until condition Statements ----------- ----------- Loop

Or, we can use this below syntax:

Example:

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

Page 50: QTP

www.stctek.com 50

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

Or, we can use this below syntax:

Example:

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

Page 51: QTP

www.stctek.com 51

While...Wend StatementExecutes a series of statements as long as a given condition is True.Syntax:

While condition Statements ----------- -----------Wend

Example:Dim xx=0 While x<5 x=x+1

msgbox "Hello G.C.Reddy"msgbox "Hello QTP"

Wend

Page 52: QTP

www.stctek.com 52

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 xFor x= 1 to 5 step 1Msgbox "Hello G.C.Reddy"Next

Page 53: QTP

www.stctek.com 53

For Each...Next Statement

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

Syntax:

For Each item In array StatementsNext

Page 54: QTP

www.stctek.com 54

Example: (1Dim a,b,x (3)a=20b=30x(0)= "Addition is "& a+b x(1)="Substraction is " & a-bx(2)= "Multiplication is " & a*bx(3)= "Division is " & a/bFor Each element In x msgbox elementNext

Example: (2

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

Page 55: QTP

www.stctek.com 55

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

Option explicitDim a,xa=Inputbox ("Enter a Vaule")a=cdbl(a)If a<= 100 ThenFor x= 1 to 100If a=x Then

msgbox "a is in between 1 to 100 range"End IfNextelseFor x= 101 to 1000If a=x Thenmsgbox "a is in between 101 to 1000 range"End IfNextEnd If

Page 56: QTP

www.stctek.com 56www.stctek.com

Exit Statement

Exits a block of Do...Loop, For...Next, Function, or Sub code.

Exit DoExit ForExit FunctionExit PropertyExit Sub

Page 57: QTP

www.stctek.com 57www.stctek.com

Exit Do

Provides a way to exit a Do...Loop statement. It can be used only inside a Do...Loop statement. Exit Do transfers control to the statement following the Loop statement. When used within nested Do...Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where it occurs.

Page 58: QTP

www.stctek.com 58www.stctek.com

Exit ForProvides a way to exit a For loop. It can be

used only in a For...Next or For Each...Next loop. Exit For transfers control to the statement following the Next statement. When used within nested For loops, Exit For transfers control to the loop that is one nested level above the loop where it occurs.

Page 59: QTP

www.stctek.com 59www.stctek.com

Exit FunctionImmediately exits the Function procedure in

which it appears. Execution continues with the statement following the statement that called the Function.

Page 60: QTP

www.stctek.com 60www.stctek.com

Exit PropertyImmediately exits the Property procedure in

which it appears. Execution continues with the statement following the statement that called the Property procedure.

Page 61: QTP

www.stctek.com 61www.stctek.com

Exit SubImmediately exits the Sub procedure in

which it appears. Execution continues with the statement following the statement that called the Sub.

Page 62: QTP

www.stctek.com 62www.stctek.com

Example:

Sub RandomLoop Dim I, MyNum Do ' Set up infinite loop. For I = 1 To 1000 ' Loop 1000 times. MyNum = Int(Rnd * 100) ' Generate random numbers. Select Case MyNum ' Evaluate random number. Case 17: MsgBox "Case 17" Exit For ' If 17, exit For...Next. Case 29: MsgBox "Case 29" Exit Do ' If 29, exit Do...Loop. Case 54: MsgBox "Case 54" Exit Sub ' If 54, exit Sub procedure. End Select Next LoopEnd Sub

Page 63: QTP

www.stctek.com 63

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 MyVarMyVar = MsgBox ("Hello World!", 65, "MsgBox Example")

Page 64: QTP

www.stctek.com 64

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 InputInput = InputBox("Enter your name") MsgBox ("You entered: " & Input)

Page 65: QTP

www.stctek.com 65

VB Script Constants

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

Constants

You create user-defined constants in VBScript using the Const statement. Using the Const statement, you can create string or numeric constants with meaningful names and assign them literal values. For example:

Const MyString = "This is my string."Const MyAge = 49Const 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

Page 66: QTP

www.stctek.com 66

VB Script Procedures

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

Page 67: QTP

www.stctek.com 67

Sub ProceduresSub ProceduresA Sub procedure is a series of VBScript statements (enclosed by A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform actions but don't Sub and End Sub statements) that perform actions but don't return a value. return a value. A Sub procedure can take arguments (constants, variables, or A Sub procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure).expressions that are passed by a calling procedure). If a Sub procedure has no arguments, its Sub statement must If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses ().include an empty set of parentheses ().

Syntax:Syntax:

Sub Procedure name ()Sub Procedure name ()StatementsStatements--------------------------------------------End SubEnd Sub

Page 68: QTP

www.stctek.com 68

OrOr

Sub Procedure name (argument1, argument2)Sub Procedure name (argument1, argument2)StatementsStatements--------------------------------------------End SubEnd Sub

Example: 1Example: 1

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

End SubEnd Sub

Page 69: QTP

www.stctek.com 69

Function ProceduresFunction Procedures

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

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

A Function procedure can take arguments (constants, variables, A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure). or expressions that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function statement If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. must include an empty set of parentheses. A Function returns a value by assigning a value to its name in one 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 or more statements of the procedure. The return type of a Function is always a Variant.Function is always a Variant.

Page 70: QTP

www.stctek.com 70

Syntax:Syntax:

Function Procedure name ()Function Procedure name ()StatementsStatements--------------------------------------------End FunctionEnd FunctionOrOrFunction Procedure name (argument1, argument2)Function Procedure name (argument1, argument2)StatementsStatements--------------------------------------------End FunctionEnd Function

Example: 1Example: 1

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

Page 71: QTP

www.stctek.com 71

Example: 2Function cal(a,b,c) cal = (a+b+c)End Function

Getting Data into and out of Procedures

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

Page 72: QTP

www.stctek.com 72

Using Sub and Function Procedures in Code

A Function in our code must always be used on the right side of a variable assignment or in an expression.

For example:

Temp = Celsius(fDegrees)-Or-MsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."To call a Sub procedure from another procedure, type the name of the procedure along with values for any required arguments, each separated by a comma. The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses.The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other doesn't. Both do exactly the same thing. Call MyProc(firstarg, secondarg)MyProc firstarg, secondargNotice that the parentheses are omitted in the call when the Call statement isn't used.

Page 73: QTP

www.stctek.com 7373

Call Statement To call a Sub procedure from another procedure, type the

name of the procedure along with values for any required arguments, each separated by a comma.

The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses.

The Call statement Transfers control to a Sub or Function procedure.

If you omit the Call keyword, you also must omit the parentheses around argumentlist.

Page 74: QTP

www.stctek.com 7474

Call Statement If you use either Call syntax to call any intrinsic or user-

defined function, the function's return value is discarded.

Call MyFunction("Hello World") Function MyFunction(text)

MsgBox text End Function

Page 75: QTP

www.stctek.com 75

Arguments in ProceduresArguments in Procedures

There are two types of arguments in proceduresThere are two types of arguments in procedures

1) By Val: 1) By Val: Indicates that the argument is passed by value.Indicates that the argument is passed by value.2) By Ref: 2) By Ref: Indicates that the argument is passed by reference.Indicates that the argument is passed by reference.

By default all arguments are 'ByRef'.By default all arguments are 'ByRef'.For example:For example:

Function demo_add(a,b)Function demo_add(a,b)demo_add=a+bdemo_add=a+bEnd FunctionEnd Function

Here ‘a,b’ are the arguments. By default these are 'ByRef'.Here ‘a,b’ are the arguments. By default these are 'ByRef'.In simple terms ‘ByRef’ Means the value which is assigned to the variable with In simple terms ‘ByRef’ Means the value which is assigned to the variable with in the function is permanent and we can use that value out side that function as in the function is permanent and we can use that value out side that function as well. ‘ByVal’ means the value, which is assigned to the variable with in the well. ‘ByVal’ means the value, which is assigned to the variable with in the function, is temporary and we can use that value only with in that function.function, is temporary and we can use that value only with in that function.

Page 76: QTP

www.stctek.com 76

For example:For example:Function demo_parameters(byref x,byval y)Function demo_parameters(byref x,byval y)x=20x=20y=50y=50demo_parameters=x+ydemo_parameters=x+yEnd FunctionEnd Functiona=10a=10b=20b=20msgbox demo_parameters(a,b)msgbox demo_parameters(a,b)msgbox amsgbox amsgbox bmsgbox b

In the above function ‘x’ and ‘y’ are the arguments, declared as ‘byref’ and ‘byval’. With in that function we have assigned values to ‘x’ and ‘y’. Outside of the function we have assigned values to two variables and passing those variables in to the function. Here 'a' is passing reference to x and b is passing value to y. With in that function we are changing the value for ‘x’. This value is permanent for 'a' - because 'a' is passed as 'ByRef'. But the value of 'b' will notbe changed because it is passed as 'ByVal'.

Page 77: QTP

www.stctek.com 77

Coding ConventionsCoding Conventions

Coding conventions are suggestions that may help you write Coding conventions are suggestions that may help you write code using Microsoft Visual Basic Scripting Edition. Coding code using Microsoft Visual Basic Scripting Edition. Coding conventions can include the following:conventions can include the following:

Naming conventions for objects, variables, and procedures Naming conventions for objects, variables, and procedures Commenting conventions Commenting conventions Text formatting and indenting guidelines Text formatting and indenting guidelines

The main reason for using a consistent set of coding conventions is The main reason for using a consistent set of coding conventions is to standardize the structure and coding style of a script or set of to standardize the structure and coding style of a script or set of scripts so that you and others can easily read and understand the scripts so that you and others can easily read and understand the code. Using good coding conventions results in precise, readable, code. Using good coding conventions results in precise, readable, and unambiguous source code that is consistent with other and unambiguous source code that is consistent with other language conventions and as intuitive as possible.language conventions and as intuitive as possible.

Page 78: QTP

www.stctek.com 78

Constant Naming ConventionsConstant Naming Conventions

Earlier versions of VBScript had no mechanism for creating Earlier versions of VBScript had no mechanism for creating user-defined constants. Constants, if used, were implemented user-defined constants. Constants, if used, were implemented as variables and distinguished from other variables using all as variables and distinguished from other variables using all uppercase characters. Multiple words were separated using uppercase characters. Multiple words were separated using the underscore (_) character. For example: the underscore (_) character. For example:

USER_LIST_MAX USER_LIST_MAX NEW_LINE NEW_LINE

While this is still an acceptable way to indentify your constants, you While this is still an acceptable way to indentify your constants, you may want to use an alternative naming scheme, now that you can may want to use an alternative naming scheme, now that you can create true constants using the Const statement. This convention create true constants using the Const statement. This convention uses a mixed-case format in which constant names have a "con" uses a mixed-case format in which constant names have a "con" prefix. For example:prefix. For example:

conYourOwnConstantconYourOwnConstant

Page 79: QTP

www.stctek.com 79

Variable Naming ConventionsFor purposes of readability and consistency, use the following prefixes with descriptive names for variables in your VBScript code.Subtype Prefix ExampleBoolean bln blnFoundByte byt bytRasterDataDate (Time) dtm dtmStartDouble dbl dblToleranceError err errOrderNumInteger int intQuantityLong lng lngDistanceObject obj objCurrentSingle sng sngAverageString str strFirstName

Page 80: QTP

www.stctek.com 80

Variable ScopeVariables should always be defined with the smallest scope possible. VBScript variables can have the following scope.

Scope Where Variable Is Declared

Visibility

Procedure-level Event, Function, or Sub procedure

Visible in the procedure in which it is declared

Script-level HEAD section of an HTML page, outside any procedure

Visible in every procedure in the script

Page 81: QTP

www.stctek.com 81

Variable Scope Prefixes

As script size grows, so does the value of being able to quickly differentiate the scope of variables. A one-letter scope prefix preceding the type prefix provides this, without unduly increasing the size of variable names.

Scope Prefix ExampleProcedure-level None dblVelocityScript-level s sblnCalcInProgress

Page 82: QTP

www.stctek.com 82

Descriptive Variable and Procedure NamesDescriptive Variable and Procedure Names

The body of a variable or procedure name should use mixed The body of a variable or procedure name should use mixed case and should be as complete as necessary to describe its case and should be as complete as necessary to describe its purpose. In addition, procedure names should begin with a purpose. In addition, procedure names should begin with a verb, such as InitNameArray or CloseDialog.verb, such as InitNameArray or CloseDialog.

For frequently used or long terms, standard abbreviations are For frequently used or long terms, standard abbreviations are recommended to help keep name length reasonable. In recommended to help keep name length reasonable. In general, variable names greater than 32 characters can be general, variable names greater than 32 characters can be difficult to read. When using abbreviations, make sure they are difficult to read. When using abbreviations, make sure they are consistent throughout the entire script. For example, randomly consistent throughout the entire script. For example, randomly switching between Cnt and Count within a script or set of switching between Cnt and Count within a script or set of scripts may lead to confusion. scripts may lead to confusion.

Page 83: QTP

www.stctek.com 83

Object Naming Conventions The following table lists recommended conventions for objects you may encounter while programming VBScript.Object type Prefix Example

3D Panel pnl pnlGroup

Animated button ani aniMailBox

Check box chk chkReadOnly

Combo box, drop-down list box cbo cboEnglish

Command button cmd cmdExit

Common dialog dlg dlgFileOpen

Frame fra fraLanguage

Horizontal scroll bar hsb hsbVolume

Image img imgIcon

Label lbl lblHelpMessage

Line lin linVertical

List Box lst lstPolicyCodes

Spin spn spnPages

Text box txt txtLastName

Vertical scroll bar vsb vsbRate

Slider sld sldScale

Page 84: QTP

www.stctek.com 84

Code Commenting ConventionsCode Commenting Conventions

All procedures should begin with a brief comment describing All procedures should begin with a brief comment describing what they do. This description should not describe the what they do. This description should not describe the implementation details (how it does it) because these often implementation details (how it does it) because these often change over time, resulting in unnecessary comment change over time, resulting in unnecessary comment maintenance work, or worse, erroneous comments. The code maintenance work, or worse, erroneous comments. The code itself and any necessary inline comments describe the itself and any necessary inline comments describe the implementation. implementation.

Arguments passed to a procedure should be described when Arguments passed to a procedure should be described when their purpose is not obvious and when the procedure expects their purpose is not obvious and when the procedure expects the arguments to be in a specific range. Return values for the arguments to be in a specific range. Return values for functions and variables that are changed by a procedure, functions and variables that are changed by a procedure, especially through reference arguments, should also be especially through reference arguments, should also be described at the beginning of each procedure.described at the beginning of each procedure.Procedure header comments should include the following Procedure header comments should include the following section headings. For examples, see the "Formatting Your section headings. For examples, see the "Formatting Your Code" section that follows.Code" section that follows.

Page 85: QTP

www.stctek.com 85

Section Heading Comment ContentsPurpose What the procedure does (not how).Assumptions List of any external variable, control, or other element whose

state affects this procedure.Effects List of the procedure's effect on each external variable, control,

or other element.Inputs Explanation of each argument that isn't obvious. Each argument

should be on a separate line with inline comments.Return Values Explanation of the value returned.

Remember the following points: Remember the following points: •Every important variable declaration should include an inline comment Every important variable declaration should include an inline comment describing the use of the variable being declared. describing the use of the variable being declared. •Variables, controls, and procedures should be named clearly enough Variables, controls, and procedures should be named clearly enough that inline comments are only needed for complex implementation details. that inline comments are only needed for complex implementation details. •At the beginning of your script, you should include an overview that At the beginning of your script, you should include an overview that describes the script, enumerating objects, procedures, algorithms, dialog describes the script, enumerating objects, procedures, algorithms, dialog boxes, and other system dependencies. Sometimes a piece of boxes, and other system dependencies. Sometimes a piece of pseudocode describing the algorithm can be helpful.pseudocode describing the algorithm can be helpful.

Page 86: QTP

www.stctek.com 86

Formatting Your Code

Screen space should be conserved as much as possible, while still allowing code formatting to reflect logic structure and nesting. Here are a few pointers:

Standard nested blocks should be indented four spaces. The overview comments of a procedure should be indented one space.

The highest level statements that follow the overview comments should be indented four spaces, with each nested block indented an additional four spaces. For example:

Page 87: QTP

www.stctek.com 87

'********************************************************* *******************************Purpose: Locates the first occurrence of a specified user ' in the UserList array. ' *Inputs: strUserList(): the list of users to be searched. ' * strTargetUser: the name of the user to search for. ' *Returns: The index of the first occurrence of the trTargetUser ' in the strUserList array. ' *If the target user is not found, return -1. '************************************************************************************** Function intFindUser (strUserList(), strTargetUser)

Dim i ' Loop counter. Dim blnFound ' Target found flag intFindUser = -1

i = 0 ' Initialize loop counter Do While i <= Ubound(strUserList) and Not blnFound

If strUserList(i) = strTargetUser Then blnFound = True ' Set flag to True intFindUser = i ' Set return value to loop count

End If i = i + 1 ' Increment loop counter

Loop End Function

Page 88: QTP

www.stctek.com 88

FUNCTION: Asc()

Implemented in version 1.0 Asc(String)

The Asc function returns the ANSI character code value for the first character in a string.

In these two examples, note that the ANSI value is returned only for the "a".

Code: <% =Asc("abcde fghij klmno pqrst uvwxyz") %> Output: 97

Code: <% =Asc("a") %> Output: 97

Page 89: QTP

www.stctek.com 89

FUNCTION: Chr()

Implemented in version 1.0 Chr(ANSIvalue)

The Chr function converts an ANSI character code value to a character.

Code: <% =Chr(98) %> Output: b

Page 90: QTP

www.stctek.com 90

Data Subtype ConversionData Subtype Conversion

VBScript provides several functions that convert a VBScript VBScript provides several functions that convert a VBScript variable from one data subtype to another.variable from one data subtype to another.Since VBScript uses the Variant data type, these functions Since VBScript uses the Variant data type, these functions are not generally required. However, when passing data are not generally required. However, when passing data between IWS (or CEView) and VBScipt, or calling built-in IWS between IWS (or CEView) and VBScipt, or calling built-in IWS functions from VBScript where variables need to be put into functions from VBScript where variables need to be put into the proper argument format, these VBScript data subtypethe proper argument format, these VBScript data subtypeconversion functions can be very useful.conversion functions can be very useful.

Page 91: QTP

www.stctek.com 91

FUNCTION: CBool( )

Implemented in version 1.0 You can determine the expression subtype by using the function VarType( ). CBool(Number) The CBool function converts any number to the variant of subtype Boolean. The output for Boolean is either true or false. If the conversion is successful, the output will be true. If the conversion fails, the output will be false or an error message.

Code: <% anynumber=7.77 %> <% =CBool(anynumber) %> Output: True

Code: <% notnumber=abc %> <% =CBool(notnumber) %> Output: False

Page 92: QTP

www.stctek.com 92

FUNCTION: CByte( ) Implemented in version 1.0 You can determine the expression subtype by using the function VarType( ).

CByte(Number)

The CByte function converts any number between 0 and 255 to the variant of subtype Byte.

Code: <% anynumber=(9.876) %> <% =CByte(anynumber) %> Output: 10

Code: <% anynumber=(255) %> <% =CByte(anynumber) %> Output: 255

Page 93: QTP

www.stctek.com 93

FUNCTION: CCur( ) Implemented in version 1.0 You can determine the expression subtype by using the function VarType( ). CCur(Number) The CCur function converts any number or numeric string to the variant of subtype Currency.

Converts to currency values ranging from -922,337,203,685,477.5808 to 922,337,203,685,477.5807

Code: <% anynumber=(12345) %> <% =CCur(any_number) %> Output: 12345

Code: <% any_numeric_string=("98765") %> <% =CCur(any_numeric_string) %> Output: 98765

This function rounds off to 4 decimal places. Code: <% anynumber=(55555.123456) %> <% =CCur(anynumber) %> Output: 55555.1235

Page 94: QTP

www.stctek.com 94

FUNCTION: CDate( ) Implemented in version 1.0 You can determine the expression subtype by using the function VarType( ). CDate(Date)

The CDate function converts any valid date and time expression to the variant of subtype Date.

The default date output will be of the format: **/**/** The default time output will be of the format: **:**:** *M Converted date values can range from January 1, 100 to December 31, 9999

Code: <% anydate = "June 26, 1943" %> <% =CDate(anydate) %> Output: 6/26/43 Code: <% anydate = #6/26/43# %> <% =CDate(anydate) %> Output: 6/26/43 Code: <% anytime="2:23:59 PM" %> <% =CDate(anytime) %> Output: 2:23:59 PM

Page 95: QTP

www.stctek.com 95

FUNCTION: CDbl( )

Implemented in version 1.0 You can determine the expression subtype by using the function VarType( ).

CDbl(Number)

The CDbl function converts any number to the variant of subtype Double.

Converted values can range from -1.79769313486232E308 to -4.94065645841247E-324 for negative values and 4.94065645841247E-324 to 1.79769313486232E308 for positive values. Code: <% anynumber=1234.5 %> <% =CDbl(anynumber) %> Output: 1234.5

Page 96: QTP

www.stctek.com 96

FUNCTION: CInt( )

Implemented in version 1.0 You can determine the expression subtype by using the function VarType( ).

CInt(Number) The CInt function converts any number to the variant of subtype Integer. Converts to values ranging from -32,768 to 32,767 The number is rounded off.

Code: <% anynumber=1234.567 %> <% =CInt(anynumber) %> Output: 1235

Page 97: QTP

www.stctek.com 97

FUNCTION: CLng( ) Implemented in version 1.0 You can determine the expression subtype by using the function VarType( ).

CLng(Number)

The CLng function converts any number to the variant of subtype Long, with floating-point numbers rounded. Converts to integers ranging from -2,147,483,648 to 2,147,483,647

Code: <% anynumber=1234.6 %> <% =CLng(anynumber) %> Output: 1235

Page 98: QTP

www.stctek.com 98

FUNCTION: CSng( )

Implemented in version 1.0 You can determine the expression subtype by using the function VarType( ).

CSng(Number)

The CSng function converts any number to the variant of subtype Single. Converts to values ranging from -3.402823E38 to -1.401298E-45 for negative values and 1.401298E-45 to 3.402823E38 for positive values.

Code: <% anynumber=5678.123 %> <% =CSng(anynumber) %> Output: 5678.123

Page 99: QTP

www.stctek.com 99

FUNCTION: CStr( )

Implemented in version 1.0 You can determine the expression subtype by using the function VarType( ).

CStr(Expression)

The CStr function converts an expression into a variant of subtype String. If the expression is Boolean, the output is a string containing either true or false. If the expression is a Date, the output is a string using the short-date format. If the expression is empty, the output is a zero length string. If the expression is an error, the output is a string with the word error followed by the error number. If the expression is numeric, the output string contains the number. If the expression is Null (does not exist), the output is a runtime error.

Code: <% anyexpression=5678 %> <% =CStr(anyexpression) %> Output: 5678

Page 100: QTP

www.stctek.com 100

FUNCTION: Hex( ) Implemented in version 1.0

Hex(Number)

The Hex function returns the hexadecimal value of an integer number.

Code: <% =Hex(123) %> Output: 7B

You can also use a negative integer number. Code: <% =Hex(-123) %> Output: FF85

For a number with a decimal point (floating-point), the digits to the right of the decimal point are ignored. Code: <% =Hex(123.456) %> Output: 7B

Page 101: QTP

www.stctek.com 101

FUNCTION: Oct( ) Implemented in version 1.0

Oct(Number)

The Oct function returns the octal value of an integer number.

Code: <% =Oct(123) %> Output: 173

You can also use a negative integer number. Code: <% =Oct(-123) %> Output: 177605

For a number with a decimal point (floating-point), the digits to the right of the decimal point are ignored. Code: <% =Oct(123.456) %> Output: 173

Page 102: QTP

www.stctek.com 102

FUNCTION: IsArray( ) Implemented in version 1.0

IsArray(Expression)

The IsArray function determines if the expression is an array.

Code: <% Dim myarray(10) %> <% =IsArray(myarray) %> Output: True

Code: <% =IsArray("This is a string.") %> Output: False

Page 103: QTP

www.stctek.com 103

FUNCTION: IsDate( ) Implemented in version 1.0

IsDate(Expression)

The IsDate function determines if the expression is a date.

Code: <% mydate = "6/26/1943" %> <% =IsDate(mydate) %> Output: True

Code: <% =IsDate("This is a string.") %> Output: False

Page 104: QTP

www.stctek.com 104

FUNCTION: IsEmpty( )

Implemented in version 1.0

IsEmpty(variant)

The IsEmpty function returns True when passed a Variant that has been declared but not initialized. It returns False in all other cases.

Code: <% =IsEmpty(notbeen) %> Output: True

Code: <% =IsEmpty("This is a string.") %> Output: False

Page 105: QTP

www.stctek.com 105

FUNCTION: IsNull( )

Implemented in version 1.0 IsNull(Expression)

The IsNull function determines if the expression is Null.

Code: <% nothere = null %> <% =IsNull(nothere) %> Output: True

Code: <% =IsNull("This is a string.") %> Output: False

Page 106: QTP

www.stctek.com 106

FUNCTION: IsNumeric( )

Implemented in version 1.0

IsNumeric(Expression)

The IsNumeric function determines if the expression is a number.

Code: <% =IsNumeric(123.456) %> Output: True

Code: <% =IsNumeric("This is a string.") %> Output: False

Page 107: QTP

www.stctek.com 107

FUNCTION: IsObject( )

Implemented in version 1.0

IsObject(Expression)

The IsObject function determines if the expression is an automation object.

Code: <% Set anyvariable =Server.CreateObject("Scripting.FileSystemObject") %> <% =IsObject(anyvariable) %> Output: True

Code: <% =IsObject("This is a string, not an object.") %> Output: False

Page 108: QTP

www.stctek.com 108

VBScript String ManipulationThese functions allow you to manipulate string data.

UCase(string) returns string with all lowercase letters converted to uppercase letters.

LCase(string) returns string with all uppercase letters converted to lowercase letters.

LTrim(string) removes all the spaces from the left side of string.

RTrim(string) removes all the spaces from the right side of string.

Trim(string) removes spaces from both the left and the right sides of string.

Space(number) returns a string consisting of number spaces.String(number, character) returns a string consisting of character repeated number times.

Len(string) returns the number of characters in string.

Page 109: QTP

www.stctek.com 109

Len(variable) returns the number of bytes required by variable.

LenB(string) returns the number of bytes required to store string.

StrReverse(string) returns string with the characters in reverse order.

StrComp(string1, string2, comparetype) is used to perform string comparisons. If comparetype is zero or omitted, the two strings are compared as if uppercase letters come before lowercase letters. If comparetype is one, the two strings are compared as if uppercase and lowercase letters are the same. StrComp returns -1 if string1 is less than string2. It returns 0 if they are the same, and 1 if string1 is greater than string2.

Right(string, number) returns the number rightmost characters of string.RightB(string, number) works like Right, but number is taken to be a number of bytes rather than characters.

Left(string, number) returns the number leftmost characters of string.LeftB(string, number) works like Left, but number is taken to be a number of bytes rather than characters.

Page 110: QTP

www.stctek.com 110

Mid(string, start, length) returns length characters from string, starting at position start. When length is greater than the number of characters left in the string, the rest of the string is returned. If length is not specified, the rest of the string starting at the specified starting position is returned.

MidB(string, start, length) works like Mid, but start and length are both taken to be byte numbers rather than character numbers.

Instr(start, string1, string2, comparetype) is used to check if and where string2 occurs within string1. start is an optional argument that specifies where in string1 to start looking for string2. comparetype is an optional argument that specifies which type of comparison to perform. If comparetype is 0, a binary comparison is performed - uppercase are distinct from lowercase.If comparetype is 1, a textual comparison is performed - uppercase and lowercase are the same.

Instr returns zero if srting1 is empty (""), if string2 is not found in string1, or if start is greater than the length of string2. It returns Null if either string is Null. It returns start if string2 is empty. If string2 is successfully found in string1, it returns the starting position where it is first found.

Page 111: QTP

www.stctek.com 111

InstrB works the same as Instr except that the start position and return value are byte positions, not character positions.

Instr(start, string1, string2, comparetype) starts looking for a match at the right side of the string rather than the left side. start is by default -1, which means to start at the end of the string.

Replace(string, find, replace, start, count, comparetype) is used to replace occurences of find with replace in string. start, count, and comparetype are optional, but if you want to use one, you must use the ones that come before it. start indicates where the resulting string will start and where to start searching for find. It defaults to 1. count indicates how many times to perform the replacement. By default count is -1, which means to replace every occurence. If comparetype is 0, a binary comparison is performed - uppercase are distinct from lowercase.If comparetype is 1, a textual comparison is performed - uppercase and lowercase are the same.

Page 112: QTP

www.stctek.com 112

Filter(arrStrings, SearchFor, include, comparetype) searches an array of strings, arrStrings, and returns a subset of the array. include is a Boolean value. If include is True, Filter searches through all the strings in arrStrings and returns an array containing the strings that contain SearchFor. If include is False, Filter returns an array of the strings that do not contain SearchFor. include is optional and defaults to True. If comparetype is 0, a binary comparison is performed - uppercase are distinct from lowercase.If comparetype is 1, a textual comparison is performed - uppercase and lowercase are the same. If you want to use comparetype you must also use include.

Split(expression, delimiter, count, comparetype) takes a string and splits it into an array of strings. expression is the string to be split. If expression is zero length, Split returns an array of no elements. delimiter is a string that indicates what is used to separate the sub-strings in expression. This is optional; by default the delimiter is the space. If delimiter is zero length (""), an array of one element consisting of the whole string is returned. count is used to specify a maximum number of sub-strings to be created. The default for count is -1, which means no limit.

Page 113: QTP

www.stctek.com 113

If comparetype is 0, a binary comparison is performed - uppercase are distinct from lowercase.

If comparetype is 1, a textual comparison is performed - uppercase and lowercase are the same.

comparetype is only useful when the delimiter you have chosen is a letter.

Join(stringarray, delimiter) does just the opposite of Split. It takes an array of strings and joins them into one string, using delimiter to separate them. delimiter is optional; space is the default.

Page 114: QTP

www.stctek.com 114

VBScript Date/Time ManipulationVBScript Date/Time Manipulation

These functions deal with the manipulation of date values.

Date returns the current date on the server.

Time returns the current time on the server.

Now returns the current date and time on the server.

Year(date) returns the year portion from date as a number.

Month(date) returns the month portion from date as a number.

MonthName(date) returns the month portion from date as a name.

Day(date) returns the day portion from date as a number.

Weekday(date) returns the day of the week of date as a number.

Hour(time) returns the hour portion from time.

Page 115: QTP

www.stctek.com 115

Minute(time) returns the minute portion from time.

Second(time) returns the second portion from time.

DateAdd(interval, number, date) is used to add the date specified by date.  interval is a string that represents whether you want to add days, months, years, and so on.  number indicates the number of intervals you want to add.

Page 116: QTP

www.stctek.com 116

DateDiff(interval, date1, date2, firstDOW, firstWOY) is used to find the time between two dates.interval is one of the interval values from the table below. DateDiff returns the number of intervals elapsed between date1 and date2. The optional integer firstDOW specifies what day of the week to treat as the first. The optional firstWOY specifies which week of the year to treat as the first.

DateSerial(year, month, day) takes the integers year, month, and day and puts them together into a date value. They may be negative.

TimeSerial(hour, minute, second) takes the integers hour, minute, and second and puts them together into a time value. They may be negative.Timer returns the number of seconds elapsed since midnight.

DatePart(interval, datetime, firstDOW, firstWOY) allows you to retreive the part of datetime specified by interval. The valid values for interval are listed in the table below. The optional integer firstDOW specifies what day of the week to treat as the first. [See table] The optional firstWOY specifies which week of the year to treat as the first. [See table]

Page 117: QTP

www.stctek.com 117

   ValueValue MeaningMeaning   "yyyy""yyyy" YearYear   "q""q" QuarterQuarter   "m""m" MonthMonth   "y""y" Day of YearDay of Year   "d""d" DayDay   "w""w" WeekdayWeekday   "ww""ww" Week of YearWeek of Year   "h""h" HourHour   "n""n" MinuteMinute   "s""s" SecondSecond

IntervalInterval Codes for the Date Functions

Page 118: QTP

www.stctek.com 118

  Value Name Meaning  0 vbUseSystem National Language Support API Setting  1 vbSunday Sunday  2 vbMonday Monday  3 vbTuesday Tuesday  4 vbWednesday Wednesday  5 vbThursday Thursday  6 vbFriday Friday  7 vbSaturday Saturday

  Value Name Meaning

  0 vbUseSystemvbUseSystem National Language Support API Setting

  1 vbFirstJan1 Week of January 1

  2 vbFirstFourDays First week with four days of new year

  3 vbFirstFullWeek First full week

DayDay of the Week Constants

  First WeekWeek of the Year Constants

Page 119: QTP

www.stctek.com 119

Function DescriptionAbs Returns the absolute value of a specified number

Atn Returns the arctangent of a specified number

Cos Returns the cosine of a specified number (angle)

Exp Returns e raised to a power

Hex Returns the hexadecimal value of a specified number

Int Returns the integer part of a specified number

Fix Returns the integer part of a specified number

Log Returns the natural logarithm of a specified number

Oct Returns the octal value of a specified number

Rnd Returns a random number less than 1 but greater or equal to 0

Sgn Returns an integer that indicates the sign of a specified number

Sin Returns the sine of a specified number (angle)

Sqr Returns the square root of a specified number

Tan Returns the tangent of a specified number (angle)

VBScripts Math Manipulation

Page 120: QTP

www.stctek.com 120

Function Description

FormatCurrency Returns an expression formatted as a currency valueFormatDateTime Returns an expression formatted as a date or timeFormatNumber Returns an expression formatted as a numberFormatPercent Returns an expression formatted as a percentage

VBScripts Format Manipulation

Page 121: QTP

www.stctek.com 121

Set Statement

Assigns an object reference to a variable or property, or associates a procedure reference with an event.

Set objectvar = {objectexpression | New classname | Nothing} -or-Set object.eventname = GetRef(procname) Parameters

objectvar Required. Name of the variable or property; follows standard variable naming conventions.

objectexpression Optional. Expression consisting of the name of an object, another declared variable of the same object type, or a function or method that returns an object of the same object type.

Page 122: QTP

www.stctek.com 122

New Keyword used to create a new instance of a class. If objectvar contained a reference to an object, that reference is released when the new one is assigned. The New keyword can only be used to create an instance of a class.

classname Optional. Name of the class being created. A class and its members are defined using the Class statement.

Nothing Optional. Discontinues association of objectvar with any specific object or class. Assigning objectvar to Nothing releases all the system and memory resources associated with the previously referenced object when no other variable refers to it.

object Required. Name of the object with which event is associated.

event Required. Name of the event to which the function is to be bound.

procname Required. String containing the name of the Sub or Function being associated with the event.

Page 123: QTP

www.stctek.com 123

Remarks

To be valid, objectvar must be an object type consistent with the object being assigned to it.

The Dim, Private, Public, or ReDim statements only declare a variable that refers to an object. No actual object is referred to until you use the Set statement to assign a specific object. Generally, when you use Set to assign an object reference to a variable, no copy of the object is created for that variable. Instead, a reference to the object is created. More than one object variable can refer to the same object. Because these variables are references to (rather than copies of) the object, any change in the object is reflected in all variables that refer to it.

Page 124: QTP

www.stctek.com 124

Function ShowFreeSpace(drvPath) Dim fso, d, s Set fso = CreateObject("Scripting.FileSystemObject") Set d = fso.GetDrive(fso.GetDriveName(drvPath)) s = "Drive " & UCase(drvPath) & " - " s = s & d.VolumeName & "<BR>" s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0) s = s & " Kbytes" ShowFreeSpace = sEnd Function

Page 125: QTP

www.stctek.com 125

Nothing KeywordNothing KeywordThe Nothing keyword in VBScript is used to disassociate an object The Nothing keyword in VBScript is used to disassociate an object variable from any actual object. Use the Set statement to assign variable from any actual object. Use the Set statement to assign Nothing to an object variable. For example:Nothing to an object variable. For example:

Set MyObject = NothingSet MyObject = NothingSeveral object variables can refer to the same actual object. When Several object variables can refer to the same actual object. When Nothing is assigned to an object variable, that variable no longer refers Nothing is assigned to an object variable, that variable no longer refers to any actual object. When several object variables refer to the same to any actual object. When several object variables refer to the same object, memory and system resources associated with the object to object, memory and system resources associated with the object to which the variables refer are released only after all of them have been which the variables refer are released only after all of them have been set to Nothing, either explicitly by using Set, or implicitly after the last set to Nothing, either explicitly by using Set, or implicitly after the last object variable that is not set to Nothing goes out of scope. object variable that is not set to Nothing goes out of scope. You can use the You can use the Is OperatorIs Operator to determine whether an object variable is to determine whether an object variable is assigned Nothing, as shown in the following example.assigned Nothing, as shown in the following example.If MyObject is Nothing Then If MyObject is Nothing Then The Null keyword is used to The Null keyword is used to indicate that a variable contains no valid data. This is not indicate that a variable contains no valid data. This is not the same thing as Empty.the same thing as Empty.

Page 126: QTP

www.stctek.com 126

CreateObject FunctionCreateObject FunctionCreates and returns a reference to an Automation object.Creates and returns a reference to an Automation object.

CreateObjectCreateObject(servername.typename [, location])(servername.typename [, location]) ArgumentsArguments

servernameservername Required. The name of the application providing the object. Required. The name of the application providing the object.

typenametypename Required. The type or class of the object to create. Required. The type or class of the object to create.

locationlocation Optional. The name of the network server where the object is to be Optional. The name of the network server where the object is to be created. created.

RemarksRemarksAutomation servers provide at least one type of object. For example, a Automation servers provide at least one type of object. For example, a word-processing application may provide an application object, a word-processing application may provide an application object, a document object, and a toolbar object.document object, and a toolbar object.To create an Automation object, assign the object returned by To create an Automation object, assign the object returned by CreateObjectCreateObject to an object variable: to an object variable: Dim ExcelSheet Set ExcelSheet = Dim ExcelSheet Set ExcelSheet = CreateObjectCreateObject("Excel.Sheet")("Excel.Sheet")

Page 127: QTP

www.stctek.com 127

This code starts the application that creates the object (in this case, a Microsoft Excel spreadsheet). Once an object is created, refer to it in code using the object variable you defined. As shown in the following example, you can access properties and methods of the new object using the object variable, ExcelSheet, and other Excel objects, including the Application object and the ActiveSheet.Cells collection:

' Make Excel visible through the Application object. ExcelSheet.Application.Visible = True ' Place some text in the first cell of the sheet. ExcelSheet.ActiveSheet.Cells(1,1).Value = "This is column A, row 1" ' Save the sheet. ExcelSheet.SaveAs "C:\DOCS\TEST.XLS" ‘ Close Excel with the Quit method on the Application object. ExcelSheet.Application.Quit ' Release the object variable. Set ExcelSheet = Nothing

Page 128: QTP

www.stctek.com 128

Creating an object on a remote server can only be accomplished when Internet security is turned off. You can create an object on a remote networked computer by passing the name of the computer to the servername argument of CreateObject. That name is the same as the machine name portion of a share name. For a network share named "\\myserver\public", the servername is "myserver". In addition, you can specify servername using DNS format or an IP address.The following code returns the version number of an instance of Excel running on a remote network computer named "myserver":

Function GetVersion Dim XLApp Set XLApp = CreateObject("Excel.Application", "MyServer") GetVersion = XLApp.Version

End Function

An error occurs if the specified remote server does not exist or cannot be found.

Page 129: QTP

www.stctek.com 129

File System Object Model:File System Object Model:

The File System Object (FSO) model provides an object-based The File System Object (FSO) model provides an object-based tool for working with folders and files. It allows us to use the tool for working with folders and files. It allows us to use the familiar object. method syntax with a rich set of properties, familiar object. method syntax with a rich set of properties, methods, and events to process folders and files. methods, and events to process folders and files. The FSO model gives the application the ability to create, alter, move, and delete folders, or to determine if and where particular folders exist. It also enables us to get information about folders, such as their names and the date they were created or last modified.The FSO model makes processing files much easier as well. When processing files, our primary goal is to store data in an efficient, easy-to-access format. We need to be able to create files, insert and change the data, and output (read) the data. The FSO model, contained in the Scripting type library (Scrrun.dll), supports the creation and manipulation of text files through the TextStream object; however, the FSO model does not support binary files. To manipulate binary files, use the FileOpen Function with the Binary keyword.

Page 130: QTP

www.stctek.com 130

1) Create a Folder

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

2) Delete a Folder

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

3) Copying Folders

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

Page 131: QTP

www.stctek.com 131

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

Option ExplicitDim objFSO, objFolder, strDirectorystrDirectory = "D:\us"Set objFSO = CreateObject("Scripting.FileSystemObject")If objFSO.FolderExists(strDirectory) ThenSet objFolder = objFSO.GetFolder(strDirectory)msgbox strDirectory & " already created "elseSet objFolder = objFSO.CreateFolder(strDirectory)end if

5) Returning a collection of Disk Drives

Set oFSO = CreateObject("Scripting.FileSystemObject")Set colDrives = oFSO.DrivesFor Each oDrive in colDrivesMsgBox "Drive letter: " & oDrive.DriveLetterNext