Monday, January 9, 2012

VBScript Variables

A variable is a convenient placeholder that refers to a computer memory location where you can store program information that may change during the time your script is running. For example, you might create a variable called ClickCount to store the number of times a user clicks an object on a particular Web page. Where the variable is stored in computer memory is unimportant. What is important is that you only have to refer to a variable by name to see or change its value. In VBScript, variables are always of one fundamental data type, Variant.

Declaring Variables

You declare variables explicitly in your script using the Dim statement, the Public statement, and the Private statement. For example:
Dim DegreesFahrenheit  
You declare multiple variables by separating each variable name with a comma. For example:
Dim Top, Bottom, Left, Right 
You can also declare a variable implicitly by simply using its name in your script. That is not generally a good practice because you could misspell the variable name in one or more places, causing unexpected results when your 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 your script.

 

Naming Restrictions

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


Scope and Lifetime of Variables

A variable's scope is determined by where you declare it. When you declare a variable within a procedure, only code within that procedure can access or change the value of that variable. It has local scope and is a procedure-level variable.

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


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. When the procedure exits, the variable is destroyed. Local variables are ideal as temporary storage space when a procedure is executing. You can have local variables of the same name in several different procedures because each is recognized only by the procedure in which it is declared.

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:
B = 200
 

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.
You assign data to each of the elements of the array using an index into the array. Beginning at zero and ending at 10, data can be assigned to the elements of an array as follows:
A(0) = 256
A(1) = 324
A(2) = 100
 . . .
A(10) = 55
Similarly, the data can be retrieved from any element using an index into the particular array element you want. For example:
 . . . 
SomeVariable = A(8) 
 . . . 
Arrays aren't limited to a single dimension. You can have as many as 60 dimensions, although most people can't comprehend more than three or four dimensions. You can declare multiple dimensions by separating an array's size numbers in the parentheses with commas.

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.
You can also declare an array whose size changes during the time your 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 you can resize a dynamic array, although if you make an array smaller, you lose the data in the eliminated elements.

Sunday, January 8, 2012

VBScript Features

The following table is a list of VBScript features.
Category Keywords
Array handling Array
Dim, Private, Public, ReDim
IsArray
Erase
LBound, UBound
Assignments Set
Comments Comments using ' or Rem
Constants/Literals Empty
Nothing
Null
True, False
Control flow Do...Loop
For...Next
For Each...Next
If...Then...Else
Select Case
While...Wend
With
Conversions Abs
Asc, AscB, AscW
Chr, ChrB, ChrW
CBool, CByte
CCur, CDate
CDbl, CInt
CLng, CSng, CStr
DateSerial, DateValue
Hex, Oct
Fix, Int
Sgn
TimeSerial, TimeValue
Dates/Times Date, Time
DateAdd, DateDiff, DatePart
DateSerial, DateValue
Day, Month, MonthName
Weekday, WeekdayName, Year
Hour, Minute, Second
Now
TimeSerial, TimeValue
Declarations Class
Const
Dim, Private, Public, ReDim
Function, Sub
Property Get, Property Let, Property Set
Error Handling On Error
Err
Expressions Eval
Execute
RegExp
Replace
Test
Formatting Strings FormatCurrency
FormatDateTime
FormatNumber
FormatPercent
Input/Output InputBox
LoadPicture
MsgBox
Literals Empty
False
Nothing
Null
True
Math Atn, Cos, Sin, Tan
Exp, Log, Sqr
Randomize, Rnd
Miscellaneous Eval Function
Execute Statement
RGB Function
Objects CreateObject
Err Object
GetObject
RegExp
Operators Addition (+), Subtraction (-)
Exponentiation (^)
Modulus arithmetic (Mod)
Multiplication (*), Division (/)
Integer Division (\)
Negation (-)
String concatenation (&)
Equality (=), Inequality (<>)
Less Than (<), Less Than or Equal To (<=)
Greater Than (>)
Greater Than or Equal To (>=)
Is
And, Or, Xor
Eqv, Imp
Options Option Explicit
Procedures Call
Function, Sub
Property Get, Property Let, Property Set
Rounding Abs
Int, Fix, Round
Sgn
Script Engine ID ScriptEngine
ScriptEngineBuildVersion
ScriptEngineMajorVersion
ScriptEngineMinorVersion
Strings Asc, AscB, AscW
Chr, ChrB, ChrW
Filter, InStr, InStrB
InStrRev
Join
Len, LenB
LCase, UCase
Left, LeftB
Mid, MidB
Right, RightB
Replace
Space
Split
StrComp
String
StrReverse
LTrim, RTrim, Trim
Variants IsArray
IsDate
IsEmpty
IsNull
IsNumeric
IsObject
TypeName
VarType

Looping Through Code

Looping allows you 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.

Using Do Loops

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

Repeating Statements While a Condition is True

Use the While keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the following ChkFirstWhile example), or you can check it after the loop has run at least once (as shown in the ChkLastWhile example). In the ChkFirstWhile procedure, if myNum is set to 9 instead of 20, the statements inside the loop will never run. In the ChkLastWhile procedure, the statements inside the loop run only once because the condition is already False.
Sub ChkFirstWhile()
   Dim counter, myNum
   counter = 0
   myNum = 20
   Do While myNum > 10
      myNum = myNum - 1
      counter = counter + 1
   Loop
   MsgBox "The loop made " & counter & " repetitions."
End Sub

Sub ChkLastWhile()
   Dim counter, myNum
   counter = 0
   myNum = 9
   Do
      myNum = myNum - 1
      counter = counter + 1
   Loop While myNum > 10
   MsgBox "The loop made " & counter & " repetitions."
End Sub

Repeating a Statement Until a Condition Becomes True

There are two ways to use the Until keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the following ChkFirstUntil example), or you can check it after the loop has run at least once (as shown in the ChkLastUntil example). As long as the condition is False, the looping occurs.
Sub ChkFirstUntil()
   Dim counter, myNum
   counter = 0
   myNum = 20
   Do Until myNum = 10
      myNum = myNum - 1
      counter = counter + 1
   Loop
   MsgBox "The loop made " & counter & " repetitions."
End Sub

Sub ChkLastUntil()
   Dim counter, myNum
   counter = 0
   myNum = 1
   Do
      myNum = myNum + 1
      counter = counter + 1
   Loop Until myNum = 10
   MsgBox "The loop made " & counter & " repetitions."
End Sub

Exiting a Do...Loop Statement from Inside the Loop

You can exit a Do...Loop by using the Exit Do statement. Because you usually want to exit only in certain situations, such as to avoid an endless loop, you should use the Exit Do statement in the True statement block of an If...Then...Else statement. If the condition is False, the loop runs as usual.
In the following example, myNum is assigned a value that creates an endless loop. The If...Then...Else statement checks for this condition, preventing the endless repetition.
Sub ExitExample()
   Dim counter, myNum
      counter = 0
      myNum = 9
      Do Until myNum = 10
         myNum = myNum - 1
         counter = counter + 1
         If myNum < 10 Then Exit Do
      Loop
      MsgBox "The loop made " & counter & " repetitions."
End Sub

Using While...Wend

The While...Wend statement is provided in VBScript for those who are familiar with its usage. However, because of the lack of flexibility in While...Wend, it is recommended that you use Do...Loop instead.

Using For...Next

You can use For...Next statements to run a block of statements a specific number of times. For loops, use a counter variable whose value increases or decreases with each repetition of the loop.
The following example causes a procedure called MyProc to execute 50 times. The For statement specifies the counter variable x and its start and end values. The Next statement increments the counter variable by 1.
Sub DoMyProc50Times()
   Dim x
   For x = 1 To 50
      MyProc
   Next
End Sub
Using the Step keyword, you can increase or decrease the counter variable by the value you specify. In the following example, the counter variable j is incremented by 2 each time the loop repeats. When the loop is finished, the total is the sum of 2, 4, 6, 8, and 10.
Sub TwosTotal()
   Dim j, total
   For j = 2 To 10 Step 2
      total = total + j
   Next
   MsgBox "The total is " & total
End Sub
To decrease the counter variable, use a negative Step value. You must specify an end value that is less than the start value. In the following example, the counter variable myNum is decreased by 2 each time the loop repeats. When the loop is finished, total is the sum of 16, 14, 12, 10, 8, 6, 4, and 2.
Sub NewTotal()
   Dim myNum, total
   For myNum = 16 To 2 Step -2
      total = total + myNum
   Next
   MsgBox "The total is " & total
End Sub
You can exit any For...Next statement before the counter reaches its end value by using the Exit For statement. Because you usually want to exit only in certain situations, such as when an error occurs, you should use the Exit For statement in the True statement block of an If...Then...Else statement. If the condition is False, the loop runs as usual.

Using For Each...Next

A For Each...Next loop is similar to a For...Next loop. Instead of repeating the statements a specified number of times, a For Each...Next loop repeats a group of statements for each item in a collection of objects or for each element of an array. This is especially helpful if you don't know how many elements are in a collection.
In the following HTML code example, the contents of a Dictionary object is used to place text in several text boxes.
<HTML>
<HEAD><TITLE>Forms and Elements</TITLE></HEAD>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub cmdChange_OnClick
   Dim d   'Create a variable 
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "0", "Athens"   'Add some keys and items
   d.Add "1", "Belgrade"
   d.Add "2", "Cairo"

   For Each I in d
      Document.frmForm.Elements(I).Value = D.Item(I)
   Next
End Sub
-->
</SCRIPT>
<BODY>
<CENTER>
<FORM NAME="frmForm"

<Input Type = "Text"><p>
<Input Type = "Text"><p>
<Input Type = "Text"><p>
<Input Type = "Text"><p>
<Input Type = "Button" NAME="cmdChange" VALUE="Click Here"><p>
</FORM>
</CENTER>
</BODY>
</HTML>

Visual Basic for Applications Features Not In VBScript

The following table lists Visual Basic for Applications Features not in VBScript.
Category Omitted Feature/Keyword
Array Handling Option Base
Declaring arrays with lower bound <> 0
Collection Add, Count, Item, Remove
Access to collections using ! character
Conditional Compilation #Const
#If...Then...#Else
Control Flow DoEvents
GoSub...Return, GoTo
On Error GoTo
On...GoSub, On...GoTo
Line numbers, Line labels
Conversion CVar, CVDate
Str, Val
Data Types All intrinsic data types except Variant
Type...End Type
Date/Time Date statement, Time statement
DDE LinkExecute, LinkPoke, LinkRequest, LinkSend
Debugging Debug.Print
End, Stop
Declaration Declare (for declaring DLLs)
Optional
ParamArray
Static
Error Handling Erl
Error
Resume, Resume Next
File Input/Output All traditional Basic file I/O
Financial All financial functions
Object Manipulation TypeOf
Objects Clipboard
Collection
Operators Like
Options Deftype
Option Base
Option Compare
Option Private Module
Select Case Expressions containing Is keyword or any comparison operators
Expressions containing a range of values using the To keyword.
Strings Fixed-length strings
LSet, RSet
Mid Statement
StrConv
Using Objects Collection access using !

Thursday, January 5, 2012

Understanding the Object Repository Manager

You open the Object Repository Manager by choosing Resources > Object Repository Manager. The Object Repository Manager enables you to open multiple shared object repositories and modify them as needed. You can open shared object repositories both from the file system and from a Quality Center project.

You can open as many shared object repositories as you want. Each shared object repository opens in a separate document window. You can then resize, maximize, or minimize the windows to arrange them as you require to copy, drag, and move objects between different shared object repositories, as well as perform operations on a single object repository.

You open shared object repositories from the Open Shared Object Repository dialog box. In this dialog box, the Open in read-only mode check box is selected, by default. If you clear this check box, the shared object repository opens in editable mode. Otherwise, the shared object repository opens in read-only mode and you must click the Enable Editing button to modify it.

When you choose a menu item or click a toolbar button in the Object Repository Manager, the operation you select is performed on the shared object repository whose window is currently active (in focus). The name and file path of the shared object repository is shown in the title bar of the window.

Many of the shared object repository operations you can perform in the Object Repository Manager are done in a similar way to how you modify objects stored in a local object repository.

Most of the procedures apply equally to the Object Repository Manager and the Object Repository window, but the windows and options may differ slightly.  



About Managing Object Repositories

The Object Repository Manager enables you to manage all of the shared object repositories used in your organization from a single, central location, including adding and defining objects, modifying objects and their descriptions, parameterizing repositories to make them more generic, maintaining and organizing repositories, merging repositories, and importing and exporting repositories in XML format. 

The Object Repository Manager enables you to create and maintain shared object repositories. You can work with object repositories saved both in the file system and in a Quality Center project.  

Each object repository contains the information that enables QuickTest to identify the objects in your application. QuickTest enables you to maintain the reusability of your tests by storing all the information regarding your test objects in a shared object repository. When objects in your application change, the Object Repository Manager provides a single, central location in which you can update test object information for multiple tests.

If an object with the same name and description is located in both the local object repository and in a shared object repository that is associated with the same action, the action uses the local object definition.

If an object with the same name and description is located in more than one shared object repository, and these shared object repositories are all associated with the same action, QuickTest uses the object definition from the first occurrence of the object, according to the order in which the shared object repositories are associated with the action.

You can use the same shared object repository with multiple actions. You can also use multiple object repositories with each action. In addition, you can save objects directly with an action in a local object repository. This enables them to be accessed only from that action. 

If one or more of the property values of an object in your application differ from the property values QuickTest uses to identify the object, your test may fail. Therefore, when the property values of objects in your application change, you should modify the corresponding test object property values in the corresponding object repository so that you can continue to use your existing tests.

You can modify objects in a shared object repository using the Object Repository Manager, as described in this section. You can modify objects stored in a local object repository using the Object Repository window.

Tuesday, January 3, 2012

Understanding the Virtual Object Manager

The Virtual Object Manager contains all the virtual object collections defined on your computer. From the Virtual Object Manager, you can define and delete virtual objects and collections.

Available virtual object collections list. Displays the virtual object collections defined on your computer and the virtual objects contained in each one. Use the + and - signs next to a collection to view or hide the virtual objects defined in that collection.

New. Opens the Virtual Object Wizard, which guides you through the process of defining a new virtual object for a new or existing collection. For more information, see Defining a Virtual Object.

Delete. Deletes the selected virtual object or virtual object collection. For more information, see Removing or Disabling Virtual Object Definitions.