Sep
25
2008
--

Implementing elegant if else

A typical if else condition in VBScript would look like below

If (message = "ok") Then 
    Msgbox "I am calling ok"
Else
    Msgbox "I am calling not ok"
End if

VB provides a elegant function named IIf for such small if else conditions. The function can be easily witten in VBScript

Public Function IIf(ByVal pCondition, ByVal trueValue, ByVal falseValue)
    If pCondition Then
        IIf = trueValue
    Else
        IIf = falseValue
    End If
End Function

Now the same code be written in single line of code

Msgbox "I am calling " & IIf(message="ok","ok", "not ok")
Rating: 6.5/10 (11 votes cast)
Written by Tarun Lalwani in: VBScript | Tags: , , , , , , ,
Sep
23
2008
--

Implementing Callback in VBScript

Callback is a function which is executed on completion of a registered event. VBScript is not a event driven language, which means we are limited in terms of events for which callback can be implemented.

This article will demonstrate how to implement a callback on finish/terminate event. This finish/terminate event could be one of the following

  • The script finishes/terminates
  • A function finishes/terminates
  • A class finishes/terminates

CallBack implementation

We will create a special CallBack class for this

Class Callback
	'The object which called
	Dim Caller
 
	'Code to be executed during callback
	Dim CallBackCode
 
	'When the class ends execute the callback code
	Sub Class_Terminate()
		Execute CallBackCode
	End Sub
End Class

Executing code when script ends
If we want a Finalize function to be called when the script ends we can use the below code

Dim OC
Set OC = New Callback
OC.CallBackCode = "Call Finalize(0)"
 
Function Finalize(ByVal ExitCode)
	Msgbox "The code end with exit code - "  & ExitCode
End Function
 
Msgbox "Script ends here"

Executing code when a function ends

Function Test()
	Dim OC
	Set OC = New CallBack
	OC.CallBackCode = "Msgbox ""Function Test ended"""
 
	x = 2/0
	Msgbox "Unreachable code"
End Function
 
Call Test()

The advantage of implementing this call back is that they are guaranteed to be executed even in case the script end with a error or the function ends with an error. In QTP we can similarly execute a code at the end of the Test by declaring the variable in one of the associate global libraries.

Note: The approach works on the concept that all variables are destroyed once the scope in which they exist ends. It is important to make sure the CallBack object is always taken in a variable declared (as shown in code “Dim OC”)

Executing the Callback on a Class method

In case we want a class method to be called on a class object we can use the caller property

Class Test
     Function CallMe()
            Msgbox "You called me"
     End Function
End Class
 
Dim oTest
Set oTest = new Test
 
Dim OC
Set OC = New CallBack
Set OC.Caller = oTest
OC.CallBackCode = "Call Caller.CallMe"
Rating: 7.2/10 (6 votes cast)
Written by Tarun Lalwani in: VBScript | Tags: , , , , , , , , , , , ,
Sep
21
2008
0

VBScript Part 2 - Variables

What is variable?
Variable is a named container used to store values

Declaring a variable
There are three possible ways to declare a variable

Dim <VariableName>
Public <VariableName>
Private <VariableName>

Ex –

Dim x, y, z
Dim a
Dim b, c

Variable naming rules
Variable names should following the below rules

  • Must not exceed 255 characters.
  • Must be unique in the scope in which it is declared.
  • Must begin with an alphabetic character.
  • Cannot contain an embedded period.

Though these are the naming conventions specified by Microsoft. But we will be breaking the last 2 rules later in this article
Assigning values to variables
Variables can be assigned values why using the “=” to operator. Below code shows how different types of values can be assigned to a variable

Dim myVar
myVar = "Assigning a string value"
'Assigning a integer value
myVar = 2
'Assigning a double value
myVar = 3.3

Data Type of variables
All variables declared in VBScript are of Data type VARIANT. A VARIANT data type can store any types of value listed below

  • Boolean
  • Byte
  • Date (Time)
  • Double
  • Error
  • Integer
  • Long
  • Object
  • Single
  • String

All actual type of the data stored in a VARIANT type is known as the sub-type of the variable.

Declaring constant variable
Constants can be declared using below syntax

Const  <ConstName> = <ConstValue>

Ex –

Const APP_ NAME = "Testing VBScript"
Const APP_VERSION = "1.01"

It is advised to use all caps variable name when declaring a constant.

Variable Naming conventions
Since variables can store various types of values it is always a good practice to name them with a consistent convention

Data Type

Prefix 1

Prefix 2

Prefix 3

Boolean

b

b_

bln_

Byte

by

by_

byt_

Date (Time)

dt

dt_

dt_

Double

Dbl

dbl_

dbl_

Error

err

err_

err_

Integer

i

i_

int_

Long

l

l_

lng_

Object

o

o_

obj_

Single

sng

sng_

sng_

String

s

s_

str_

Above table shows few prefixes that can be used during scripting. You should choose the ones you like and stick to them. I personally prefer the Prefix 2 column. Below is the list of other Prefixes that might be required

  • Function – fn
  • Sub – sub
  • Global variable – g
  • Class member – m
  • Class – cls

We would be discussing all above mentioned topics in the upcoming articles

Forcing variable declaration
VBScript allows a very poor programming practice which is not to declare the variable being used
Ex –

str_Message = "Tarun Lalwani"
Msgbox str_Message
Msgbox for a undefined variable

Msgbox for a undefined variable

Above code will work even when we haven’t declared the ” str_Message” variable using a Dim/Public/Private statement. VBscript when it looks at a variable name which is not yet declared it declares with an Empty value. In programming a typo when using the variable name is always a possibility. Ex –

str_Message = "Tarun Lalwani"
Msgbox str_Messge
Msgbox for undefined and unused variables

Msgbox for undefined and unused variables

The value above is empty message because we haven’t declared str_Messge variable and when used VBScript declares it with an empty value. Though it is pretty easy to spot the issue in above code but when the code size is huge, these issues become very difficult to debug as wrong variable name used at once place might cause an issue at different location of code. To avoid such a situation VBScript provides an “Option Explicit” statement which can be used at the top of the code as shown below

Option Explicit
str_Message = "Tarun Lalwani"
Msgbox str_Messge

Now above code would throw an error

Undefined variable error when Option explicit is used

Undefined variable error when Option explicit is used

Breaking the 2 rules of naming restriction
Let us reiterate the last 2 rules for variable naming in VBScript

  • Must begin with an alphabetic character.
  • Cannot contain an embedded period.

Thought this is pretty much true the normal way
All below declaration will give syntax errors

Dim 1A
Dim _AB
Dim A B
Dim A.B

Though the error might be different for above declarations but the source of the error is the same, bnot following the naming convention. Now VBScript provides a very less talked about square bracket “[]” declaration

Dim [9X]
Dim [_varName]
Dim [My Name]
Dim [this.A]
[My Name] = "Tarun Lalwani"
[this.A] = [My Name]
MsgBox [this.A]
Msgbox for a undefined variable

Breaking the variable declaration rules

Rating: 8.0/10 (5 votes cast)
Sep
21
2008
0

VBScript Part 1 - Introduction

VBScript is a scripting language. A VBScript can be executed in various ways

  • Using Windows Script Host (wscript.exe and cscript.exe). Will cover this later
  • Inside HTML page for IE Browser.
  • Other host process which allows to execute code in VBScript format (ex - HP QuickTest Pro)

Internal methods and objects
VBScript provides method and objects that can be used in the script. Internal methods are one which not dependent on the Host running the script. For Ex, below code would run fine on any of scripting host

Dim myName
myName = "Tarun Lalwani"
Dim myNameLength
myNameLength = Len(myName)
WScript Message box

WScript Message box

Above code would run fine if run in standalone VBScript, HTML or QTP
Host specific methods and objects

These methods or objects are provided by the Host running the script. Scripts using such methods are specific to the Host and can only run by them. Consider the below VBScript

Dim myName
myName = "Tarun Lalwani"
WScript.Echo myName

In the above script we are using a special object named “WScript” and a method “Echo” of that object. The code would run fine when run as a standalone script file and would produce the below message

No if we paste the same code in an HTML file and try to open the file in a IE browser

<HTML>
<BODY>
<SCRIPT type="text\VBScript">
Dim myName
myName = "Tarun Lalwani"
WScript.Echo myName
</SCRIPT>
</BODY>
<HTML>

The IE browser will display an error (Make sure you have unchecked the Disable Script Debugging in IE Options…Advanced Tab)

WScript object required error

WScript object required error

The reason the error is thrown is that WScript is Host specific object which is defined by the WScript.exe or CScript.exe scripting hosts. When we run the same code in IE this Host specific object does not exists. It is important to understand which methods or objects are host specific when porting scripts from one host to another (Ex VBScript to QTP Script, VBScript to HTML web page etc…)

Executing a Script

Different scripting host have different ways of running the script. In windows we can write the script in a notepad file and then save it with “vbs” extension

Script written in Notepad

Script written in Notepad

Save script as VBS

Save script as VBS

Double clicking the “Demo.vbs” file in explorer execute the script. By default windows is configured to execute the script using WScript.exe

Running the script by double clicking in explorer

Running the script by double clicking in explorer

Another way to the run the script is through windows run window or command prompt. Below screenshot shows how to execute a script using cscript.exe from console.

Script executed using CScript thorugh DOS command line

Script executed using CScript thorugh DOS command line

For an IE host we would need to run the HTML file containing the code which in turn would.

Rating: 9.5/10 (4 votes cast)
Oct
26
2006
--

Review - Test Design Studio (TDS)

Test Design Studio (TDS) is enhanced IDE for WinRunner and QTP. It provides a Visual Studio style editor which provided enhanced code editing experience. This review will walk you through some of the key features of TDS

Solution
A solution allows you to group various types of files into one solution. This includes QTP, Winrunner, VBS, text, ini etc…

Expand/Collapse functions
The editor allows expanding and collapsing function into single lines.

Expand/Collapse function definition

Expand/Collapse function definition

Smart Indentation
The editor is smart to identify the indentation for current line. So if you are Typing “End Function” but are not at the same ident level as the function start then TDS will automatically decrease the indent level to match the function start.

Track Modification
Lines changed during current session can be tracked using the color code yellow(unsaved)/green(saved).

Split Windows
You split a window horizontally or vertically or both. This allows editing various parts of the file at the same time.

Vertically split window

Vertically split window

Enhanced Intellisense
TDS provides intellisense for almost everything. It provides intellisense for all QTP object even when the machine does not have QTP installed. This allows automation developers to easily code there scripts on any machine without being dependent on QTP. TDS also provides intellisense on COM libraries available to be used with the CreateObject function.

Lists COM Libraries available on the System

Lists COM Libraries available on the System

Using smart tags TDS allows you to quickly reference a library. Once reference is added to a library, intellisense is available for all objects present in the library

Reference Libraries using smart Tags

Reference Libraries using smart Tags

Intellisense for referenced libraries

Intellisense for referenced libraries

Other intellisense features:

  • Intellisense for QTP OR (only in case QTP 9.2 or higher installed on machine)
  • Intellisense for QTP OR using exported XML (QTP not required on the machine)
  • XML documentation for custom intellisense. This is really cool feature which makes coding even more fun.

Object Browser
Object Browser provides easy reference to all methods and properties available for a class/library in the current solution.

Object Browser

Object Browser

Quality Center Support

TDS allows adding different quality center servers. Once the server is added you can access any of the the projects to which you have access. TDS has following feature when working with QC

  • View/Modify the workflow scripts of project
  • View/Modify QTP, WinRunner, VBS, XML etc… files present in QC. Allows auto sync which updates the file on the QC server
  • Add reference to other file types which TDS does not support (excel files etc…)
  • Run multiple SQL Queries on project’s database tables and export results to excel
  • Active/Deactivate any project from within TDS (provided you have admin access) and few more admin related feature
  • Supports VCS (QC project should have VCS add-in installed)
  • Supports scripted Business Process Components
SQL Query on QC Project tables

SQL Query on QC Project tables

Inbuilt Browser
TDS provides an inbuilt tabbed browser window, which you can use browse websites

Why TDS and not QTP?
QTP IDE lacks many features and is no where near to being called a professional IDE for automation programmers. TDS helps bridge this gap and improve productivity of automation engineers. QTP licenses cost far more then a TDS licenses and most of the times not all QTP licenses are utilized simultaneously. Which gives a good reason to consider purchasing less licenses for QTP and investing in TDS licenses. Licensing information can be found here

Rating: 0.0/10 (0 votes cast)