Sunday, March 27

Descriptive Programming in QTP - Part 3

Hello friends!

In Part-1 and Part-2 of this post, we learned type of DP and how to use DP. In this part, we'll cover -

- Using childobjects
- Using GetROProperty

Childobjects and Getroproperty are two most commonly used and i think most useful methods for DP.

Life is easy while working on a stable application where objects are not changing dynamically. But imagine the situation where there are only one or two properties found by QTP for a particular object, and these are also not constant!!

Childobjects may save your day!! Yess!!

You can do a lot using Childobjects and Getroproperty. Lets start with simple things in this post.


Childobjects the collection of child objects contained within particular object.


Okey. Consider the below screen -

This is a Login dialog, contain few other object i.e. Agent name, password, buttons.
In this case Login Dialog is parent and Agent name, password, buttons are child objects.

How to use Childobjects method:

Suppose you have a page which gives you few options, i.e. Individual and Corporate. If you select 1st, on next page, you will see few fields like name, passport no, age, sex etc. But if you choose 2nd, you will see name, registration no, type of business etc.

Means page will be change on the basis of selection. Suppose you have 50 options, so you'll be having 50 different pages, all with different number/type of objects. You don't know how many objects will be there on any page.

Now you need to count the number of buttons on a particular screen, or, let's say number of links on a web page. How to do that?

And the answer is.. using childobjects method!!

Open the above window - Start>>Program>>QuickTest Professional\Sample Applications\flight.exe>>Login into application, and run the following code in QTP..

Set oDesc=Description.Create()
Set oAll=Window("text:=Flight Reservation").ChildObjects(oDesc)
Print "Total number of objects: "&cnt
For i=0 to cnt-1
      Print "Class: "&oAll(i).GetROproperty("micclass")&", Text: "&oAll(i).GetROproperty("text")

Above code will give you the number of objects on window. You can provide more specific description. Suppose you need to enter some value in all the textboxes on the page. You don't know how many textboxes are there on page. Run following code..

Set oDesc=Description.Create()

Set oAll=Window("text:=Flight Reservation").ChildObjects(oDesc)
Print "Total number of EditBox: "&cnt
For i=0 to cnt-1
    If  oAll(i).Getroproperty("enabled") Then
        oAll(i).Set "Editbox:"&i
    End If

Here oAll is an array which contain all the textboxes and it's index starts from zero. So if there are total 9 textboxes on window, array index will be oAll(0) to oAll(8).

Following is one more example. You have to click on particular button (if it displayed on the page). t might come or not..

Set oDesc=Description.Create()

Set oAll=Window("text:=Flight Reservation").ChildObjects(oDesc)
Print "Total number of Buttons: "&cnt
For i=0 to cnt-1
    If  oAll(i).Getroproperty("text")="FLIGHT" Then
    End If

I was working on a application, where you need to work on two instances of the application at the same time.(1st as customer and 2nd as trader). All properties are same because application is exactly same. In that type of situations, childobjects is the way you can survive upon!!

So it was starting learning advanced DP uses. Explore above codes and try to get good understanding of childobjects and getroproperty methods.

In next part of this post we'll cover more advanced stuff of DP.

In case of any queries, please post your comments. Happy QTPing...!!

Friday, March 18

Running QTP on Remote Machine - Tips

Hello Friends!

This post although is not QTP specific but might be helpful if are dealing with remote machine. Many times you need to work on remote system using Remote Desktop Connection(RDC). Sometime your QTP is installed on that remote machine only and you need to access it through RDC.

In this post, I'll giving few useful tips for RDC....

Tip 1. How to start RDC?

One traditional way to start RDC is - Go to Start>>Programmes>>Accessories>>Remote Desktop Connection.

Instead of doing all this exercise, you can simply - Start>>Run>> and type mstsc>> press Enter.
Done!! :)

Tip 2. How to open Task Manager of remote machine?

What to do if your remote machine is hanged? Obviously, try to kill some processes from Task Manager. But how to open Task Manager of remote machine, because if you use Ctrl+Alt+Del, it'll open your machine's Task Manager. 

No worries!! There are two ways -

a) Press Ctrl+Shift+Esc. It'll open remote machine's Task Manager, not yours machine.
b) On remote machine, Go to Start>>Run>> type taskmgr>> press Enter , and it's done!

Tip 3: How to restart remote machine?

This is most important tip and generally people don't know about this. 
What'll you do if you are working on a remote machine and it got completely hanged? Or by any other reason you need to restart it.

Relax guys!

Your remote machine is hanged, but yours not. Right? 

Simply Go to Start>>Run>> type CMD.
Now your command prompt is open in front of you.
Type - Shutdown -r -f -m \\NDL030799 (replace this with remote machine's name)

Please not that NDL030799 is just sample remote machine name. So provide your remote machine's name here and it's done. After 3-4 minutes, you can again connect to remote machine.

Please note that you can run this command from any machine in your network. Yess!! It's not necessary to run this from yours machine or this remote machine you are working on.  you can run this command from any machine in your network, only Admin Rights should be available on that machine, that's it!

Please leave your comments if you like this post or you have any queries.

Tuesday, March 15

Sendkeys Method - Keyboard Oprations in QTP

Hello Friends!
In this post we'll learn how to perform keyboard operation in QTP using vbscript.

What's the need of Sendkeys?

Hmmm... ok.. Refer the blow code.

Set oShell = CreateObject("WScript.Shell")
SystemUtil.Run "D:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Click
oShell.SendKeys "john"
Dialog("text:=Login").WinEdit("attached text:=Password:").Click
oShell.SendKeys "wrong "

Copy this code in QTP and run it.

Okie.. Now you can see, because we have entered incorrect password, following error dialog will be displayed.

Now we need to close error dialog and enter correct password in the login window.

If do this using DP code, we need to get the properties of error window and write one more line of code.

Dialog("text:=Flight Reservations").WinButton("text:=OK").Click

Instead of addind more objects in our code and writing extra lines for this, we can simply press escape key (ESC) from keyboard and our job is done!!

How can we do that using QTP?

All you need to do is, create a Wscript object and then you can use Sendkeys for that purpose.

Set oShell = CreateObject("WScript.Shell")
oShell.SendKeys "{ESC}"


This thing is very useful when application have no automation interface. And it's quite fast as well. Depends on the need.

Most keyboard characters are represented by a single keystroke. Some keyboard characters are made up of combinations of keystrokes (CTRL+SHIFT+HOME, for example).

Please note:-

- To send a single keyboard character, send the character itself as the string argument. For example,
- To send the letter x, send the string argument "x".
- To send a space, send the string " ".
- You cannot send the PRINT SCREEN key {PRTSC} to an application.


  • oShell.SendKeys "{ESC}"    - press escape key
  • oShell.SendKeys "john"    - type john
  • oShell.SendKeys "+^{ESC}"    - press Ctrl + Shift + Esc keys (open Windows Task Manager)
  • oShell.SendKeys "%{F}"    - press Alt + F key (open file menu)

For details of all the characters, please refer the following table.

In case of any queries, please post your comments.

Sunday, March 13

How to design Automation Frameworks in QTP

Hello Friends!

In this post, we are going to discuss about Automation Framework! I'm not going to write any bookish definitions here. It's all what I learned from practical experience.


First thing first...

What is framework?

Do you watch movies in Cinema Hall? I know you do!!

Take a moment and think about what happens starting from the point you enter in Cinema Hall to the point you come out. Here are few typical steps..

- You enter in hall >> go the ticket window >> pick a movie broacher somewhere nearby ticket window

- Choose a particular movie you wanna watch (decision influenced by the choice of wife/girlfriend!!)

- Come in the queue and wait for your turn, pay by card and get the ticket.

- On ticket you find some very important information i.e. show start time, Audi No. (Hall No.) etc.

- You go into the given sign-posted Audi, 5-10 minutes earlier then show time, watch the movie (along with other activities ;) ...... and so on....

Everything is planned.. In order!!  Isn’t it? This is nothing but a framework..

Automation Framework is a set of guidelines and process you use to manage and optimize your automation testing. 

In simple words, Framework is a way to do the things in fashioned and organized manner! Framework is nothing but a concept.

Why I need a Framework?:

Now assume that Cinema Hall doesn’t follow any framework.

- You enter in Cinema Hall, go the ticket window, - but there is no movie broacher nearby ticket window??

- You go to the ticket window, but they don’t accept credit/debit cards?? (and you don't carry cash..)
- Okay! You somehow managed to buy ticket, but ticket doesn’t tell you show time and Audi/Hall No.??

- You reached into the Audi but movie has not been started on time??

Would you like to go again in this Cinema Hall?? I'm sure not..

It's always possible to work without framework but you'll be doing a lot of rework, everything will be here & there and in most of the time you will end-up with a mess, especially in the large projects.

Framework lets you predefine your automation plans, strategies and how you are going to proceed.

Types of Framework:

Framework can be of several types, but here are three main types of frameworks-

1. Keyword driven framework
2. Data driven framework
3. Hybrid framework

But this is only theoretical. Practically, there is no 'Chinese Wall' between the framework types.

In every organization you work, you'll find that it's quite different from the other and not only on organization level, you can feel the difference within different projects!

Yess, but most of the them could be mapped with Hybrid type and I like it!! :)
Hybrid framework has no boundaries and open to take benefit of all possible type of frameworks.

How to design a framework?

I have done a lot of automation projects and designed a lot a frameworks, but seriously guys, I never used any particular type of framework!

Practically, every application/project has its own expectation. You just need to start your work in organized way and believe me friends, at the end of the day; your framework will be ready automatically!! Sounds crazy??

You can't design a complete framework and then start automation! You start automation and framework will start building simultaneously. 

The first step of any test automation framework is to do a quick POC with few high priority test cases aka 'smoke tests'. By doing POC, you will identify the object identification issues, challenges, complexities, required test-data and limitation you have. Once you are ready with this information, you can proceed with next steps. On the basis of above information, you can decide what type of framework is most suitable to you.

But before starting, you must take some time to decide your strategies about..

1. Object Identification
2. Test-Data
3. Function Library
4. Error Handling
5. Controller/Driver script
6. Documents and Manuals
7. Test Reults

1. Object Identification:
One of the most important aspect of QTP automation is - How to identify objects i.e. using Object Repository(OR) or Descriptive programming(DP) or both. As per my understanding, dont't try to stick on one particular. Depending on the application/object types, mixed approach is most fruitful most of the time.

Although  both OR and DP have their own pros n cons, but remember, you get full benefit of QTP only when you use OR like debugging, chechpoints etc. So make sure how to identify objects.

Many claim that DP should be used for whole project without using any OR approach, but I disagree. DP is nice thing to use but should be used only when required like if your application is having dynamic objects etc. Doing whole automation using DP without any solid reason is not sensible (personal opinion!).

2. Test-Data:
How to manage you data? DataTable or Excel or may be flat/csv files.

3. Function Library:
Function library could be QTP specific (.qfl) or external (i.e. .vbs). Be clear about what type of function libraries you are going to use and why.

4. Error Handling:
What's your plan for handling errors? Be clear about it. Are you going to use QTP's Recovery Scenarios or you will be writing your own .vbs functions?

5. Controller script:
Design a controller script, which will control all your automation. It should be neat. This helps to understand what actually you are going to call.

6. Documents and Manuals:
Keep all the documentation, user guide/manuals, keywords descriptions here.
7. Test Results:
Result is probably most important part of the framework. Put extra attention to results.. always!!

Why? Because result is the face of your framework! This is what you show to world. If your result is fantastic, nobody bothers what type of framework you use, what the hell you have written in your functions!! :) But if results are not flashy.. then.. you know!!

So never underestimate the importance of the results. It must be very well presented.

Create different folder for the these seven things and keep data in folders accordingly.

This was the one part.

Apart from this, from first day of your automation, keep only one thing in your mind.. follow general good practices!

Here are few points need to be take care in designing successful framework.

  • Try to document each and every thing, as much as you can! like comments in script, modification etc.
  • Don't stick with any particular object identification, use mix of OR and DP
  • While using OR, don't use record and playback, just add object in the object repository and code the script manually.
  • Follow proper Naming-Conventions for all your variables, functions, files.
  • Define all the variables in you scripts, use Option Explicit.
  • Try to keep you functions small to enhance reusability and portability.
  • Never hard code any data in the scripts, use parametrization.
  • Take regular back-up of your work.

Okey guys! Please share your views by posting comments.

Related Posts:

QTP - General Tips


Wednesday, March 9

Descriptive Programming in QTP - Part 2

Hello guys!
In Part-1 of this post, we discussed about Static DP. Let's look into Dynamic DP in this part.


Second way to write DP is by using the Description object. This way also known as Programmatic Description. Description Object also do the same thing as static way do but there are some differences.

  • Description Object stores the properties and values of a particular object in an instance of that object. So it become easy to use it in the statement.
  • Description Object are used with ChildObjects (very useful method) of QTP.
  • It's more useful if you are using multiple properties to identify object. As you will use only instance name in your statement, your code looks more organized.
  • It's very handy if you are using index property for object identification (we'll discuss later)

Look into following line. It is DP statement, written by Static approach (as we discussed Part-1 of this post)

Browser(“name:=myBro”).page(“title:=myPage”).webbutton(“name:=Enter”,”type:= Submit”).click

Now let's write the same using Dynamic approach. We see that there are 3 objects in above statement i.e. Browser, Page, webbutton.

Now, first we need to create empty description objects. We'll create 3 object (1 for each object)

Dim oBrowser, oPage, oButton ' declaration is not mandatory but good practice!

Set oBrowser = Description.Create
Set oPage = Description.Create
Set oButton = Description.Create

Now we'll add identification properties & values to these objects.

oBrowser("name").value = "myBro"

oPage("title").value = "myPage"

oButton("name").value = "Enter"
oButton("type").value = "Submit"
oButton("x").value = "301"

And that's it! Our objects are now ready to use now. So, here we go...


As we can see, we will write only the instance name (oButton) instead of all properties and values in statement. If you need to use same object multiple times in your code, your code will not become very lengthy!

Tedious?? I know! :)

Explore the following code to make the things clear...

  1. Browser("myBro”).page(“myPage”).webbutton(“Enter”).click - OR approach
  2. Browser(“name:=myBro”).page(“title:=myPage”).webbutton(“name:=Enter”,”type:= Submit”).click - Static DP.
  3. Browser(oBrowser).page(oPage).webbutton(oButton).click - Dynamic DP

First statement is written using OR approach. For this, objects must be stored in Object Repository.
Second statement is written using Static DP. All the properties are given directly in the code. Convenient!!
Third statement is written using Dynamic DP. You need to create a description for every object.

Please note that any statement can be written by combining all three ways!! Really?? Yesss!

Lets see how...


In above statement, we have used all 3 ways..

Browser - Object Repository
Page - Static DP
webbutton - Dynamic DP

Ohhh I see!!

Only point to take care here is that OR can't be used after DP.

Okey guys.. In next part of post, we'll discuss pros & cons of each way and other good stuff about DP.

In case of any queries, please post your comments.

Monday, March 7

Using excel sheet as database table

Excel sheet can be used as a database for the parameterization purpose. Following code demonstrate how to connect and consider excel sheet as database table.

This might be usefull while working with databases. You can export database table into excel (one time) and then work on excel as database.

Dim objCon, objRecordSet, strExlFile, colCount, row, i

Set objCon = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

strExlFile = "C:\abhikansh.xls"

objCon.Open "DRIVER={Microsoft Excel Driver (*.xls)};DBQ=" &strExlFile & ";Readonly=True"

strSQLStatement = "SELECT * FROM [Sheet2$]"

objRecordSet.Open strSQLStatement, objCon 'create recordset

colCount = objRecordSet.Fields.count    'No of columns in the table

While objRecordSet.EOF=false
    For i=0 to colCount-1
        row=row &"    "& objRecordSet.fields(i)
    Print row
Set objRecordSet = Nothing
Set objCon = Nothing

Screen-shots of sample excel and output are following -

In case of any queries, please post your comments.

Sunday, March 6

Arrays in QTP - Part 2

In the 1st part of this post we discussed about Static(fixed size) arrays. Now we are going to discuss another type of array - Dynamic Array.

Dynamic Arrays:-

A dynamic array, also called resizable array is a variable-size array that allows elements to be added or removed at runtime. Dynamic arrays are useful when size of the array cannot be determined at the time of declaration.

Dynamic or Variable Sized Array
    2.1. Single dimentional Dynamic Array
    2.2. Multi-dimentional Dynamic Array

Dim myArray()  'create a dynamic array.

It creates an array, which can be resized at runtime. For initial use, it must be initialized with some value i.e. size

This will be done using ReDim.

ReDim myArray(3)   'before using first time

Now you can assign values to array


Dynamic array can be resized n number of times, but remember, if you resize it again using ReDim, all its previous data will lost.
For that purpose, Preserve is used with ReDim.

ReDim Preserve myArray(5)


ReDim Preserve resize the array by keeping existing data safe!!

Dynamic arrays can be Multidimensional but only one of the dimensions (the 'right side') can be changed. Refer the below code..

Dim myArray()
Redim myArray(1,0)
myArray(0,0) = "John"
myArray(1,0) = 21
msgbox (ubound (myArray, 2)) '0
Redim preserve myArray(ubound (myArray, 1), ubound (myArray, 2) + 1)
myArray(0,1) = "Bob"
myArray(1,1) = 21
msgbox (ubound (myArray, 2)) '1

So point to be noted about Dynamic Arrays:-

(i) -   Dynamic Arrays are variable-size arrays that allows elements to be added or removed at runtime

(ii) -  Dynamic Arrays are useful when size of the array cannot be determined at declaration time
(iii) - Dynamic Arrays must be initialized with some value i.e. size before using first time

(iv) - Dynamic Arrays can be resized n number of time

(v) - 'Preserve' must be used with ReDim to keep the existing data of Dynamic Arrays

In case of any queries, please post your comments. Have a nice QTPing :)

Friday, March 4

Count number of files in a folder

Dim iFileCount, FolderName, vFiles, objFSO
iFileCount = 0
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set FolderName = objFSO.GetFolder("C:\Desktop") ' Folder Path
Set vFiles =FolderName.Files

For each vFile in vFiles
    Print vFile
    iFileCount = iFileCount + 1
msgbox iFileCount

Above code will print names of all the file in given folder and display the total count of files.

Arrays in QTP - Part 1

Hello Friends! In this post, we'll brush-up our understanding about vbscript arrays and to use arrays in QTP.

Fisrt thing first.. What is an Array?

- An array variable is used to store multiple values in a single variable.

- Array can contain a series of values of same data type.

- An array is a memory space referred by a common name.

Please note that VBScript explicitly supports only one data type - ‘Variant’. A variant can store a number as well as a string.

In vbscript, Arrays are of two types..

1. Static or Fixed Sized Array
2. Dynamic or Variable Sized Array

Both type of arrays can be of single dimensional or multi-dimensional. So to make the things simple, we can write this like...

1. Static or Fixed Sized Array
    1.1. Single dimensional Static Array   'Exp - Dim myArray(4)
    1.2. Multi-dimensional Static Array   'Exp - Dim myArray(3,4)

2. Dynamic or Variable Sized Array

    2.1. Single dimensional Dynamic Array
    2.2. Multi-dimensional Dynamic Array

Sounds batter? Okey.. great!!

Dim myArray(4)    'declaring array in vbscript

In the above example, an array containing 5 elements is declared:

But why 5? The number shown in the parentheses is 4!!

Ya! But array index actually starts from zero, so this array contains 5 elements. This is a fixed-size array.

You assign data to each of the elements of the array like this:

myArray(0)= 21
myArray(1)= 42
myArray(2)= 51
myArray(3)= 33
myArray(4)= 15

It was one way of declaring and assigning values to an array.
Here is the another way...

Dim myArray
myArray = Array(21,42,51,33,15)   'integer values
myArray = Array("val1","val2","val3","val4","val5")   'string values
myArray = Array("1",2,"val3",4,"val5")   'mix of num and string values

As I mentioned above as well, VBScript explicitly supports only one data type - ‘Variant’. A variant can store a number as well as a string.

It was the VBScript Array Method of Creating Arrays.

Array we have discussed above is Static Array - Single dimensions. A Static Array -

- has a pre-defined number of elements.
- size of a static array cannot be altered at run time.

Multiple dimensions are declared by separating the numbers in the parentheses with commas. Here we have a two-dimensional array consisting of 5 rows and 7 columns:

Dim myArray(4,6)

In the above example, an array containing 5 rows and 7 columns has been declared.

Calculating the Size of Arrays:

ubound method is used to count the length of array. It returns the highest index number of the array.
But remember, the actual size of the array is highest index number plus one!! (since the array starts at index number 0).

Dim myArray(4),  len1
len1 = ubound(myArray)  '4
msgbox "Length of the Array is: " & len1+1   'output is 5

ubound method can be used to count the size of a multidimensional array also, but this time it's slightly different..

The dimension number needs to be included in ubound.

Dim myArray(4,6)
msgbox ubound(myArray, 1) 'shows highest index of the first dimension - 4
msgbox ubound(myArray, 2) 'shows highest index of the second dimension - 6

Tired! me too...!!

Another type of array is Dynamic array. In next part of post, we'll explore dynamic arrays and other good stuff about using arrays.

Please post your comments and tell me how you find this article!!

Thursday, March 3

Working with Excel Sheets - Add new sheet

'This code demonstrate how to add new sheet to existing excel file and rename it at runtime

Dim oExcel, oWB, oSheet, getVal
Set oExcel=CreateObject("Excel.Application")
oExcel.DisplayAlerts = False   'this will not allow alerts to be displayed
Set oWB=oExcel.Workbooks.Open("C:\abhikansh.xls")
Set oSheet1=oWB.Sheets.Add  'a new sheet is added with default name i.e. Sheet4 etc.

oSheet1.Name="QTPSchools"  'rename newly added sheet
oSheet1.cells(1,1).value="Welcome"  'enter value
Set oExcel=Nothing

Synchronization in QTP - Exist, WaitProperty, Wait

The following example will demonstrate, why synchronization is necessary in many situations.

Option Explicit
Dim orderNo, mypath
mypath = Environment( "ProductDir" ) & "\samples\flight\app\"   ' ProductDir is In-built environment variable
SystemUtil.Run "flight4a.exe", "", mypath,"open"

If Dialog("Login").Exist( 2000 ) Then ' A way of synchronization
    Dialog("Login").WinEdit("Agent Name:").Set "Abhikansh"

    Dialog("Login").WinEdit("Password:").Set "Mercury"
    wait 1
    Reporter.ReportEvent micFail, "Synchronization time-out", "Login dialog is not dispalyed"
    ExitTest( "your test name" )  ' it is the name of your QTP Test
End If
If Not Window("Flight Reservation").Exist( 2000 ) Then
    Reporter.ReportEvent micFail, "Synchronization time-out", "Flight Reservation window is not dispalyed"
    ExitTest( "your test name" )  ' it is the name of your QTP Test
End If
With Window("Flight Reservation")
    .ActiveX("MaskEdBox").Type "010112"
    .WinComboBox("Fly From:").Select "London"
    .WinComboBox("Fly To:").Select "Los Angeles"
    .Dialog("Flights Table").WinButton("OK").Click
    .WinEdit("Name:").Set "Abhikansh"
    .WinEdit("Tickets:").SetSelection 0,1
    .WinEdit("Tickets:").Set "2"
    .WinButton("Insert Order").Click
    '.ActiveX("Threed Panel Control").WaitProperty "text", "Insert Done...", 2000 -
    orderNo = Window("Flight Reservation").WinEdit("Order No:").GetROProperty("text")
    MsgBox orderNo, vbInformation, "Order Number"
End With

As there is no sychronization after WinButton("Insert Order").Click , it will display blank message box, which is incorrect!

Think if you are paasing this number to other tests as argument, you might end-up with peculier results.

Now just uncomment this line in above code, and see the difference..
.ActiveX("Threed Panel Control").WaitProperty "text", "Insert Done...", 2000

As we can see in this example, synchronization is required here.
Synchronization points must be used whenever its necessary.
Following are different ways of synchronization :-

1. Exist property 'used above
2. WaitProperty 'used above
3. Wait  'used above

For further information, please post your comments. I'll try to cover all your queries in further posts.

Wednesday, March 2

Working with Excel Sheets - create, open, modify, save, close!!

'Getting value from an existing excel sheet

Dim oExcel, oWB, oSheet, getVal
Set oExcel=CreateObject("Excel.Application")
Set oWB=oExcel.Workbooks.Open("C:\abhikansh.xls")
Set oSheet=oWB.WorkSheets("Sheet1")
print getVal
Set oExcel=Nothing

'Inserting value to an existing excel sheet
Dim oExcel, oWB, oSheet, setVal
Set oExcel=CreateObject("Excel.Application")
Set oWB=oExcel.Workbooks.Open("C:\abhikansh.xls")
Set oSheet=oWB.WorkSheets("Sheet1")

Set oExcel=Nothing

'Create a new excel sheet, insert values and save it..
Dim oExcel, oWB, oSheet, setVal
Set oExcel=CreateObject("Excel.Application")
Set oWB=oExcel.Workbooks.Add
Set oSheet=oWB.WorkSheets("Sheet1")

Set oExcel=Nothing

Find the highest number in the array

'This code demonstrate how to find the highest number in a numaric array.
Dim num, i, Length1

Length1 = UBound(num)    'Find the length of array

For i= 1 to Length1
 If (num(i) < num(0)) Then  'to find lowest number, just change it to >
 End If

MsgBox num(0) 'Highest Number

Count number of rows in Excel without opening it.

'Following code demonstrate how to count number of rows in Excel without opening it - using vbscipt in QTP.

Set objExcel=CreateObject("Excel.Application")
Set objWB=objExcel.WorkBooks.Open("C:\abc.xls")
Set objSheet=objWB.WorkSheets(1)
msgbox objSheet.usedrange.rows.count
Set objExcel=Nothing

How "On Error Resume Next" can be a problem in QTP?

In this post, we will look into the use of Error Handling in QTP.

'"On Error Resume Next" is used to handle errors in vbscript/QTP and usually very helpful. But many times, it might give you  unexpected outcomes. Let's see how..

Example 1:

Function Example(var1 , var2)
On Error Resume Next
Example = var1/var2
On Error GOTO 0
End Function
msgbox Example(2, 0)

Run this code and see the result.

Result - Blank value is returned because of  'On Error Resume Next', which is incorrect! If  'On Error Resume Next' was not there, it would have return an error code - 11, as division by zero.

Consider the situation where you are passing the above output as an input is some other function as input! What'll happen? Whole your test will be doing something unexpected and you will end up with nothing other then confusions and looking in the code for What went wrong..... :)

Example 2:

Assume either because of some issue or unexpected behavior of the application, 'Login' button is not displayed.

Now, if you run below code--

On Error Resume Next
Browser("mybrowser").Page("mypage").WebEdit("loginname").Set "abhikansh"
Browser("mybrowser").Page("mypage").WebEdit("password").SetSecure "mypass"
wait 2

Expected Result: When you click on Login button, it should navigate to next page, where it will click on NEXT link.

Actual Result : Even though the Login button is not displayed on the page, there will be no runtime error and because steps inside the 'On error resume next'. It will try to click on NEXT link, which is not appeared.

It will keep executing all the following steps of the script without any error. But actually it will not achieve anything because application is still stuck on first page.

So what's the lesson? Shall I avoid to use 'On error resume next'?

No. Not at all! But be very careful while using.

Remember.. "On Error Resume Next" is useful when you intentionally don't want to let errors occur i.e. any temporary browser specific error or printer error which is not about AUT (application under test), but as explained in above examples, it may work in wrong direction if not used properly.

In case of any queries, please leave your comments.

Tuesday, March 1

How to extract a number from alphanumeric text string?

Dim mystring, myLength
mystring = "abhikansh567st1239test"
myLength = Len(mystring)

For i = 1 To myLength
    If Asc(Mid(mystring, i, 1)) <> 32 Then
        If Asc(Mid(mystring, i, 1)) >= 48 And Asc(Mid(mystring, i, 1)) <= 57 Then
            myNumber = myNumber & Mid(mystring, i, 1)
        End If
        msgbox("no numeric")
    End If

Launch QTP with QC Connection and Add-ins using vbscript

Suppose you are working on an Java application and you are using Java add-in and say Oracle add-in. Also, you are running your test from QC. One way to do this is simply open QTP, select required add-ins, connect with QTP manually and then open your test by browsing to its location. This'll take about 10 mins, i beleive.
Yeah...!!! But what can I do?

Well, you can do a lot! In this post we'll see how to launch qtp with all required settings, add-ins, and connection with QC, and even open a particular test by default.

Everything is done in just one click... Sounds great??  Okie... here we go...!

Set App = CreateObject("QuickTest.Application") ' Create the Application object
App.SetActiveAddins Array("Web", "Java", "Oracle") 'Set the required Add-Ins
App.Launch ' Start QuickTest
App.Visible = True ' Make the QuickTest application visible
App.New ' Open a new test
'App.Open "D:\John\" '-  use this if you want to open existing test
If Not App.TDConnection.IsConnected Then
    App.TDConnection.Connect "http://<server url>","<domain name>","<project name>","<user name>","<password>",False ' remove <> brackets
End If
App.Options.Run.ViewResults = False
App.Test.Actions("Action1").ObjectRepositories.Add "[QualityCenter] Subject\john\Repository\Rep.tsr"
App.Test.Settings.Resources.Libraries.Add "[QualityCenter] Subject\john\Repository\Lib.vbs"
'App.Test.Actions("Action1").SetScript "'TestCaseId:  "&vbCrlf&"'TestCaseName:  "&vbCrlf&"'Description:  "&vbCrlf&"'Created By:  John"&vbCrlf&vbCrlf&vbCrlf&"'*******************************Prerequisites********************************"&vbCrlf &"'Application should be open and login"&vbCrlf &"'*******************************************************************************"

Set App = Nothing ' Release the Application object

In case of any queries, please leave your comments.