Thursday, December 29, 2011

VBScript Passing Values ByVal ByRef

In VBScript, there are two ways values can be passed to functions: by value or by reference.

Lets see a quick example to see how parameters are passed by value.

Function func_Value( ByVal var)
var = var + 1
End Function

Dim x
x = 10

func_Value x

When you run the above code in your QTP editor, you will get the output as 10. What has actually happened is when you have passed the argument by value, a copy of the variable x is passed to the variable "var". Inside the function, this "var" variable gets incremented to 1 and when the function ends, this variable gets destroyed as it was a local variable. So no change is being done to our global variable "x".

In order to increment the global variable x, we need to make a very small change in our VBScript code. Instead of the ByVal keyword, all we need to do is to change it to ByRef keyword.

The modified code would be:

Function func_Value( ByRef var)
var = var + 1
End Function

Dim x
x = 10

func_Value x

Now on executing the above code, the output would be 11. The reason being, the local variable "var" is pointing to the same location in memory as the variable x. So whatever changes we will make through the variable "var", they will be reflected in variable "x" also. This technique is called passing values by reference.

In the above code, if we omit the ByRef keyword, still the arguments would be passed by reference.

For example:

Function func_Value(var)
var = var + 1
End Function

Dim x
x = 10

func_Value x

Wednesday, December 28, 2011

VBScript GetRef Function

VBScript GetRef function returns a reference to a sub procedure or a function.

Copy the below VBScript code in QTP editor and see the output:

Function ShowMsg(ByVal sName)
ShowMsg = "Hello, " + sName
End Function

Set fnPtr = GetRef("ShowMsg")

After using GetRef, fnPtr actually contains a reference of our function "ShowMsg". It means, now onwards both the function and its reference will do the same thing.

Example, see the below code

Msgbox fnPtr("HP_QTP")

Wednesday, August 3, 2011

QTP Compare Two Dictionary Objects

The following function compares two Dictionary objects. This function assumes that the two dictionary objects hold simple values for example String, Date, Integer etc.

The code goes here:

###########################################################

Function CompareDictionary(oDict1, oDict2)

Dim i, arrKeys

'Check the most basic criteria - do the two Dictionary objects have the same number of items?

If oDict1.Count <> oDict2.Count Then
CompareDictionary = False
Exit Function
End If

'Compare all keys and their values

arrKeys = oDict1.Keys
For i = 0 to uBound(arrKeys)
'Compare keys
If Not oDict2.Exists(arrKeys(i)) Then
'oDict1 has a key which oDict2 doesn't have
CompareDictionary = False
Exit Function

End If

'Compare values
If oDict1(arrKeys(i)) <> oDict2(arrKeys(i)) Then
'oDict1 value for arrKeys(i) differs from oDic2
CompareDictionary = False
Exit Function
End If

Next

'No need to check if oDict2 has values and keys that oDic1 doesn't have,
'since oDict2 and oDict1 have the same number of values.
'So if oDict2 has every value & key oDict1 has, it can't have any extra values and keys

CompareDictionary = True 'If this executes, both Dictionaries match

End Function

###########################################################

------------------------------------------------------------------------------------------------------------------------------------
Have questions on this article? Feel free to ask me in the comments section below.

If you like this post, I would suggest you to subscribe my RSS feed to have future articles delivered to your email address directly.
----------------------------------------------------------------------------------------------------------------------------------

QTP Select Complete Text

In our previous article, we have discussed two powerful utilities : Mercury DeviceReplay and Sendkeys.

Here we will discuss a quick tip using Mercury DeviceReplay which will simulate "Control-A" through the keyboard.

The code goes here:

Const VK_CONTROL = 29
Const VK_A = 30

Set DeviceReplay = CreateObject("Mercury.DeviceReplay")
DeviceReplay.KeyDown VK_CONTROL
DeviceReplay.PressKey VK_A
DeviceReplay.KeyUp VK_CONTROL

------------------------------------------------------------------------------------------------------------------------------------
Have questions on this article? Feel free to ask me in the comments section below.

If you like this post, I would suggest you to subscribe my RSS feed to have future articles delivered to your email address directly.
----------------------------------------------------------------------------------------------------------------------------------

Sunday, July 31, 2011

QTP Multiple Choice Questions Part4

1. To modify a called external action, you may or may not open the test with which the action is stored and make your modifications there.

A) True
B) False

2. Input values for an action parameter in QTP can be retrieved from any of the following:

A) the test (for a top-level action)
B) the parameters of the parent action that calls it (for a nested action)
C) the VBScript Engine
D) the output of a previous action call (for a sibling action)

3. Action parameters in Quicktest enable you

A) to transfer input values from your test to a top-level action,
B) to transfer input values from a parent action to a nested action,
C) to transfer input values from an action to a sibling action that occurs later in the test.
D) to transfer output values from a step in an action to its parent action,
E) to transfer output values from a top-level action back to the script or application that ran (called) your test.

4. The actual value specified for an input action parameter and the location specified for action output parameter cannot be different for each call to the action.

A) True
B) False

5. You can share a value that is generated in one action with other actions in your test by storing the value in the global data table. Other actions can then use the value in the data table as an ..... parameter.

A) input
B) output
C) both
D) none

6. As an alternative to using environment variables to share values between actions, you can use the Dictionary object.

A) True
B) False

7. An action call in the Expert View of QTP can define

A) the action iterations,
B) inputparameter values,
C) output parameter storage locations,
D) an action return values.
E) Both A & B

8. An action call with parameters has the following syntax:

A) RunAction ActionCall, IterationQuantity, Parameters
B) RunAction ActionName, IterationQuantity, Parameters, Time
C) RunAction ActionName, IterationQuantity, Parameters,
D) RunAction ActionName, IterationQuality, Parameters

9. If you expect other users to open your tests and all actions in your tests are stored in the same drive, you should use ....... paths for your reusable actions so that other users will be able to open your tests even if they have mapped their network drives differently.

A) Relative
B) Absolute
C) Any
D) None

10. If a test contains a call to an action from another test, and that other test
was renamed in Quality Center, the original test name still appears (in
square brackets) in the Test Flow pane.

A) True
B) False



Answers:

1)b, 2)a,b,d 3) a,b,c,d,e 4) b, 5)a, 6) a, 7)a,b,c,d 8) c 9)a, 10) a

You can view other questions here:

QTP Multiple Choice Questions in QTP Part1
QTP Multiple Choice Questions in QTP Part2
QTP Multiple Choice Questions in QTP Part3
QTP Multiple Choice Questions in QTP Part4

QTP Multiple Choice Questions Part3

1. You can use the Keyword View to add new steps to your test and but you cannot view and modify existing steps.

A) True
B) False

2. In the keyword view, in a Value cell, press ....... to add line breaks (multi-line arguments) to your argument value.

A) CTRL+ENTER
B) SHIFT+ENTER
C) ALT+ENTER
D) F12+ENTER

3. In a Value cell (keyword view),if you enter quotation marks as part of the argument value, they are included in the argument value used during the run session.

A) True
B) False

4. You can copy or cut a parent object together with only some of its child objects.

A) True
B) False

5. In case of Keyboard Shortcuts in the Keyword View, Press.... to add a new step below the currently selected step.

A) F9
B) F11
C) F8
D) F12

6. ....... tool enables you to encode passwords so that you can use the resulting strings as method arguments or data table parameter values (enabling you to place secure values into the data table).

A) Password Tool
B) Password coder Tool
C) Password decoder Tool
D) Passworder Tool

7. IntelliSense information works in the QTP keyword view.

A) True
B) False

8. A test comprises calls from actions.

A) True
B) False

9. An action consists of its own test script, including all of the steps in that action, and any objects in its shared object repository.

A) True
B) False

10. An action in HP QTP can correspond to more than one DataSheet.

A) True
B) False



Answers:

1)b, 2)b, 3) a, 4) b, 5)c, 6) b, 7)a, 8) b, 9)a, 10) a

You can view other questions here:

QTP Multiple Choice Questions in QTP Part1
QTP Multiple Choice Questions in QTP Part2
QTP Multiple Choice Questions in QTP Part3
QTP Multiple Choice Questions in QTP Part4

QTP Multiple Choice Questions Part2

1. The automation infrastructure usually includes ...................

A) one or more shared object repositories
B) one or more function libraries
C) Both A & B
D) None

2. HP QTP provides support for development environments using add-ins.

A) True
B) False

3. While you record your test steps, QuickTest Professional creates test objects representing the objects in your application on which you perform operations. This enables QuickTest to identify the objects in your application both while and .

A) creating a test
B) during a run session
C) Both A & B
B) None

4. By default, each test includes a single action, but can include multiple
actions.

A) True
B) False

5. By default, QuickTest records in the ............ recording mode.

A) Analog
B) Standard
C) Normal
D) Low Level

6. This method enables you to record the exact mouse and keyboard operations you perform in relation to either the screen or the application window.

A) Analog
B) Standard
C) Normal
D) Low Level

7. When you record in Analog Recording mode, QuickTest adds to your test a .......... statement that calls the recorded analog file.

A) RunTime
B) RunAnalog
C) RunAction
D) None

8. You can switch to either Analog Recording or Low Level Recording in the middle of a recording session for specific steps.

A) True
B) False

9. QuickTest can record only on Web browsers that were opened after QuickTest.

A) True
B) False

10. QuickTest records the visual relation identifier property when recording steps.

A) True
B) False



Answers:

1)c, 2)a, 3) c, 4) a, 5)c, 6) a, 7)b, 8) a, 9)a, 10) b

You can view other questions here:

QTP Multiple Choice Questions in QTP Part1
QTP Multiple Choice Questions in QTP Part2
QTP Multiple Choice Questions in QTP Part3
QTP Multiple Choice Questions in QTP Part4

Saturday, July 30, 2011

QTP Multiple Choice Questions Part 1

1. You can create tests using the …...

A) keyword-driven methodology
B) Step recording
C) Stop recording
D) Both A & B

2. ...... enables you to record the operations you perform on your application.

A) keyword-driven methodology
B) Step recording
C) Stop recording
D) Both A & B

3. Keyword-driven testing enables you to design your tests at a business level rather than at the object level.

A) True
B) False

4. As you navigate through your application, HP QTP graphically displays each step you perform as a …... in the Keyword View.

A) row
B) Column
C) Cell
D) None

5. After creating an initial test in Quicktest Professional, you can further enhance it by adding and modifying steps in the or .

A) Keyword View
B) Expert View
C) Both A & B
D) You cannot enhance it.

6. You can also use the CheckProperty method, which enables you to verify the property value of an object without using the checkpoint interface.

A) CheckpointProperty
B) CheckProperty
C) VerifyProperty
D) CheckingProperty

7. While parameterizing tests, you can supply data from …..

A) data table
B) environment variables
C) values that QuickTest generates during the run session
D) All of above
E) None

8. QTP enables you to define the path to a resource that you are adding to the file system or to Quality Center, as only a relative path.

A) True
B) False

9. Using relative paths means that the paths remain valid when files or folders containing files are moved or copied to other locations or computers, provided that they are moved within the same folder structure.

A) True
B) False

10. QuickTest resource files can be locked by QuickTest to protect the information in the file from being overwritten.

A) True
B) False



Answers:

1)d, 2)b, 3) a, 4) a, 5)c, 6) b, 7)d, 8) b, 9)a, 10) a

You can view other questions here:

QTP Multiple Choice Questions in QTP Part1
QTP Multiple Choice Questions in QTP Part2
QTP Multiple Choice Questions in QTP Part3
QTP Multiple Choice Questions in QTP Part4

Thursday, July 28, 2011

QTP Menu bar items missing

Very recently, I found a very weird QTP issue that all menu items went missing. I kept on trying all menu bar items but most of the items went missing. I thought my QTP 11 software got corrupt and I reinstalled it.

After a fresh installation, the same issue was there. I did a lot of hit and trials and finally got the solution. Sometimes the issue comes when we use RestoreLayout method from Automation Object Model. Then unpredictable errors may occur while the script execution is in process including these menu items missing from "File", "Edit", "View" menus etc.

The solution I got is to right click anywhere on the toolbar area, click Customize, choose toolbars tab and click on the Restore all button. This should definitely fix this.

------------------------------------------------------------------------------------------------------------------------------------
Have questions on this article? Feel free to ask me in the comments section below.

If you like this post, I would suggest you to subscribe my RSS feed to have future articles delivered to your email address directly.
----------------------------------------------------------------------------------------------------------------------------------

Saturday, July 23, 2011

VBScript Coding Guidelines

When you first start writing code, you have to concentrate so hard on just getting the syntax correct for the computer that it may be easy for you to forget about all the things you need to do in order to make sure your code is human friendly as well. However, attentiveness early on will pay huge dividends in the long run.

Expect the Unexpected

Always remember that anything that can happen probably will happen. The idea here is to code defensively — preparing for the unexpected. You don’t need to become totally fixated on preparing for all contingencies and remote possibilities, but you can’t ignore them either. You especially have to worry about the unexpected when receiving input from the user, from a database, or from a file.

Whenever you’re about to perform an action on something, ask yourself questions such as:

  • What could go wrong here?
  • What happens if the file is flagged read-only?
  • What happens if the file isn’t there?
  • What happens if the user doesn’t run the program from the right folder?
  • What happens if the database table doesn’t have any records?
  • What happens if the registry keys I was expecting aren’t there?
  • What happens if the user doesn’t have the proper permission to carry out the operation?
If you don’t know what might go wrong with a given operation, find out through research or trial and error. Get others to try out your code and get their feedback on how it worked for them, on their system configuration, and on their operating system. Don’t leave it up to your users to discover how well (or not) your script reacts to something unexpected.

Always Favor the Explicit over the Implicit

When you are writing code, constantly ask yourself: Is my intent clear to someone reading this code? Does the code speak for itself? Is there anything mysterious here? Are there any hidden meanings? Are the variable names too similar to be confusing? Even though something is obvious in your mind at the moment you are typing the code, it doesn’t mean it will be obvious to you six months or a year from now — or to someone else tomorrow. Always endeavor to make your code as self-documenting as possible, and where you fall short of that goal (which even the best programmers do — self-documenting code can be an elusive goal), use good comments to make things clearer.

Be wary of using too many generics in code, such as x, y, and z as variable names and Function1, Function2, and Function3 as function names. Instead, make them explicit. Use variable names such as UserName and TaxRate. When naming a variable, use a name that will make it clear what that variable is used for. Be careful using abbreviations. Don’t make variable names too short, but don’t make them too long either (10–16 characters is a good length, but ideal length is largely a matter of preference). Even though VBScript is not case-sensitive, use mixed case to make it easier to distinguish multiple words within the variable name (for example, UserName is easier to read than username).

When naming procedures, try to choose a name that describes exactly what the procedure does. If the procedure is a function that returns a value, indicate what the return value is in the function name (for example, PromptUserName). Try to use good verb–noun combinations to describe first, what action the procedure performs, and second, what the action is performed on (for example, SearchFolders, MakeUniqueRegistryKey, or LoadSettings).

Good procedure names tend to be longer than good variable names. Don’t go out of your way to make them longer, but don’t be afraid to either. Fifteen to thirty characters for a procedure name is perfectly acceptable (they can be a bit longer because you generally don’t type them nearly as much). If you are having trouble giving your procedure a good name, that might be an indication that the procedure is not narrow enough — a good procedure does one thing, and does it well.

That said, if you are writing scripts for web pages to be downloaded to a user’s browser, it is sometimes necessary to use shorter variable and procedure names. Longer names mean larger files to download. Even if you sacrifice some readability to make the file smaller, you can still take time to create descriptive names. With web scripts, however, you may encounter instances where you don’t want the code to be clear and easy to understand (at least for others).

Modularize Your Code into Procedures, Modules, Classes, and Components

As you write code, you should constantly evaluate whether any given code block would be better if you moved it to its own function or sub procedure:
  • Is the code rather complex? If so, break it into procedures.
  • Are you using many Ands and Ors in an If...End If statement? Consider moving the evaluation to its own procedure.
  • Are you writing a block of code that you think you might need again in some other part of the script, or in another script? Move it to its own procedure.
  • Are you writing some code that you think someone else might find useful? Move it.
This isn’t a science and there are no hard and fast rules for code — after all, only you know what you want it to do. Only you know if parts are going to be reused later. Only you know how complex something will turn out. However, always keep an eye out for possible modularization.

Use the “Hungarian” Variable Naming Convention

You might hear programmers (especially C++ programmers) mention this quite a bit. While this is a bit out of scope of this introductory discussion, it is still worth mentioning nonetheless. The Hungarian naming convention involves giving variable names a prefix that indicates what the scope and data type of the variable are intended to be. So as not to confuse matters, the Hungarian convention was not used in this chapter, but you will find that most programmers prefer this convention. Properly used, it makes your programs much clearer and easier to write and read.

Don’t Use One Variable for More Than One Job

This is a big no-no and a common mistake of both beginner and experienced programmers alike (but the fact that experienced programmers might have a bad habit does not make it any less bad). Each variable in your script should have just one purpose.

It might be very tempting to just declare a bunch of generic variables with fuzzy names at the beginning of your script, and then use them for multiple purposes throughout your script — but don’t do it. This is one of the best ways to introduce very strange, hard to track down bugs into your scripts. Giving a variable a good name that clearly defines its purpose will help prevent you from using it for multiple purposes. The moral here is that while reusing variables might seem like a total time saver, it isn’t and can lead to hours of frustration and wasted time looking for the problem.

Always Lay Out Your Code Properly


Always remember that good code layout adds greatly to readability later. Don’t be tempted to save time early on by writing messy, hard to follow code because as sure as day turns to night, you will suffer if you do.

Without reading a single word, you should be able to look at the indentations of the lines to see which ones are subordinate to others. Keep related code together by keeping them on consecutive lines. Also, don’t be frightened of white space in your code. Separate blocks of unrelated code by putting a blank line between them. Even though the script engine will let you, avoid putting multiple statements on the same line. Also, remember to use the line continuation character (_) to break long lines into multiple shorter lines.

The importance of a clean layout that visually suggests the logic of the underlying code cannot be overemphasized.

Use Comments to Make Your Code More Clear and Readable, but Don’t Overuse Them

When writing code, strive to make it as self-documenting as possible. You can do this by following the guidelines set out earlier. However, self-documenting code is hard to achieve and no one is capable of 100% self-documenting code. Everyone writes code that can benefit from a few little scribbles to serve as reminders in the margins. The coding equivalents of these scribbles are comments. But how can you tell a good comment from a bad comment?

Generally speaking, a good comment operates at the level of intent. A good comment answers the questions:
  • Where does this code block fit in with the overall script?
  • Why did the programmer write this code?
The answers to these questions fill in the blanks that can never be filled by even the best, most pedantic self-documenting code. Good comments are also generally “paragraph-level” comments. Your code should be clear enough that you do not need a comment for each and every line of code it contains, but a comment that quickly and clearly describes the purpose for a block of code allows a reader to scan through the comments rather than reading every line of code. The idea is to keep the person who might be reading your code from having to pore over every line to try and figure out why the code exists. Commenting every line (as you probably noticed with the earlier examples) makes the code hard to follow and breaks up the flow too much.

Bad comments are generally redundant comments, meaning they repeat what the code itself already tells you. Try to make your code as clear as possible so that you don’t need to repeat yourself with comments. Redundant comments tend to add clutter and do more harm than good. Reading the code tells you the how; reading the comments should tell you the why.

------------------------------------------------------------------------------------------------------------------------------------
Have questions on this article? Feel free to ask me in the comments section below.

If you like this post, I would suggest you to subscribe my RSS feed to have future articles delivered to your email address directly.
------------------------------------------------------------------------------------------------------------------------------------

VBScript Event Driven Code Example

In our previous article, we have discussed Top Down vs Event Driven approach in programming. In this example, I am going to present a very simple example for Event driven approach.

Type the following code into your text editor, save the file with a .HTM or .HTML extension, and then load it into Internet Explorer 6 (if you are running Internet Explorer 6/7 and you are running this file off your desktop, you might have to dismiss some security warnings and allow ActiveX).

The code goes here:


The below figure shows the result of clicking the button on the page. In this case it’s only a message box but it could be much more.

------------------------------------------------------------------------------------------------------------------------------------
Have questions on this article? Feel free to ask me in the comments section below.

If you like this post, I would suggest you to subscribe my RSS feed to have future articles delivered to your email address directly.
------------------------------------------------------------------------------------------------------------------------------------

VBScript Top-Down versus Event-Driven Approach

There are two different models of programming: top-down approach and event-driven approach.

Understanding Top-Down Programming

In simple top-down programming, the approach is very simple:

  • Write the code.
  • Save the code in a script file.
  • Use Windows Script Host to execute the script.
  • The Script Host starts executing at the first line and continues to the last line.
  • If a script file contains some procedure definitions (such as any user defined function), then the Script Host only executes those procedures if some other code calls them.
  • Once the Script Host reaches the last line of code, the lifetime of the script ends.
Top-down programs are very useful for task-oriented scripts. For example, you might write a script to search your hard drive for all the files with the extension .htm and copy all the names and file locations to a file, formatted in HTML to act as a sitemap. Or you might write a script that gets executed every time Windows starts and which randomly chooses a different desktop wallpaper bitmap file for that session of Windows. Top-down programming is perfect for these kinds of scripts.

Understanding Event-Driven Programming

Event-driven approach is quite different, and is useful in different contexts. As the name implies, event-driven code only gets executed when a certain event occurs. Until the event occurs, the code won’t get executed. If a given event does not occur during the lifetime of the script, the code associated with that event won’t be executed at all. If an event occurs, and there’s no code associated with that event, then the event is essentially ignored.

Event-driven programming is the predominant paradigm in Windows programming. Most of the Windows programs you use every day were written in the event-driven model. This is because of the graphical nature of Windows programs. In a graphical user interface (GUI), you have all sorts of buttons, drop-down lists, fields in which to type text, and so on. For example, the word processor program Microsoft Word is totally jam-packed with these. Every time a user clicks a button, chooses an item in a list, or types some text into a field, an event is “raised” within the code. The person who wrote the program may or may not have decided to write code in response to that event. However, if the program is well written, an item such as a button for saving a file, which the user expects to have code behind it, will indeed have code behind it.

How Top-Down and Event-Driven Work Together

When a GUI-based program starts, there is almost always some top-down style code that executes first. This code might be used to read a setting stored in the registry, prompt the user for a name and password, load a particular file at startup or prompt to take the user through setup if this is the first time the application has been run, and so on. Then a form typically comes up. The form contains all the menus, buttons, lists, and fields that make up the user interface of the program. At that point, the top-down style coding is done, and the program enters what is known as a wait state. No code is executing at this point and the program just waits for the user to do something. From here on, it’s pretty much all about events.

When the user begins to do something, the program comes to life again. Suppose the user clicks a button. The program raises the Click event for the button that the user clicked. The code attached to that event starts to execute, performs some operations, and when it’s finished, the program returns to its wait state.

As far as VBScript is concerned, the event-driven model is used heavily in scripting for the Web. Scripts that run inside of HTML web pages are all based on events. One script may execute when the page is loaded, while another script might execute when the user clicks a link or graphic.

------------------------------------------------------------------------------------------------------------------------------------
Have questions on this article? Feel free to ask me in the comments section below.

If you like this post, I would suggest you to subscribe my RSS feed to have future articles delivered to your email address directly.
------------------------------------------------------------------------------------------------------------------------------------

Friday, July 22, 2011

Variables and Data Types Basics

In simple terms, a variable is a place in the computer memory where your script holds a piece of information, or data. The data stored in a variable can be pretty much anything. It may be something simple, like a small number, like 5, or even complex, like a floating-point number such as 4.3, or a much bigger number like 971.123432434. Or it might not be a number at all and could be a word or a combination of letters and numbers. In fact, a variable can store pretty much anything you want it to store.

Behind the scenes, the variable is a reserved section of the computer’s memory for storing data. Memory is temporary — things stored there are not stored permanently like they are when you use the hard drive. Because memory is a temporary storage area, and variables are stored in the computer’s memory, they are therefore also temporary. Your script will use variables to store data temporarily that the script needs to keep track of for later use. If your script needs to store that data permanently, it would store it in a file or database on the computer’s hard disk.

To make it easier for the computer to keep track of the millions of bits of data that are stored in memory at any given moment, the memory is broken up into chunks. Each chunk is exactly the same size, and is given a unique address. Don’t worry about what the memory addresses are or how you use them because you won’t need to know any of that to use VBScript, but it is useful to know that a variable is a reserved set of one or more chunks. Also, different types of variables take up different amounts of memory.

In your VBScript program, a variable usually begins its life cycle after it is being declared before use.

It is not required to declare all variables before using. By default, VBScript allows you to use undeclared variables. However, it’s strongly recommended that you should declare the variables before you start using them in your scripts. Declaring variables before use makes code easier to read and to debug later. Just go for it!

Here goes an example for the same:

Dim VariableName

The above code is instructing your computer to reserve some memory space for you and to name that chunk VariableName. From now on, your computer (or, more accurately, the VBScript engine) keeps track of that memory for you, and whenever you use the variable name VariableName, it will know what you’re talking about.

Variables are very important in programming. Without them, there is no way to hold all the data that your script will be handling. Every input to the script, output from the script, and process within the script uses variables. They are the computer’s equivalent of the sticky notes that you leave all over the place with little bits of information on them. All the notes are important (otherwise why would you write them?) but they are also temporary. Some might become permanent (so you take a phone number and write it down in your address book or contact list), while others are thrown away after use (say, after reminding you to do something). This is how it works with variables, too. Some hold data that you might later want to keep, while others are just used for general housekeeping and are disposed of as soon as they’re used.

In VBScript, whenever you have a piece of information that you need to work with, you declare a variable using the exact same syntax you saw a moment ago. At some point in your script, you’ll need to do something with the memory space you’ve allocated yourself (otherwise, what would be the point of declaring it?). And what you do with a variable is place a value in it. This is called initializing the variable. Sometimes you initialize a variable with a default value. Other times, you might ask the user for some information, and initialize the variable with whatever the user enters. Alternatively, you might open a database and use a previously stored value to initialize the variable.

Initializing the variable gives you a starting point. After it has been initialized, you can begin making use of the variable in your script.

Here goes a simple VBScript example:

Dim strName
' Above we dimensioned the variable
str = "
Value stored inside variable"

Using Comments

You already know what the first line of code in the previous block does. It declares a variable for use called strName

The second line in the code is a comment. In VBScript, any text preceded by the single quote character (') is treated as a comment, which means that the VBScript engine completely ignores the text, which begs the question why bother typing it in at all? It doesn’t contribute to the execution of the script, right? This is absolutely correct, but don’t forget one of the most important principles of programming: It is not just computers that may have to read script. It is equally important to write a script with human readers in mind as it is to write with the computer in mind.

Of course, none of this means you should for one moment forget that when you write scripts, you must do so with the computer (or, more specifically, the script engine) in mind. If you don’t type the code correctly (that is, if you don’t use the proper syntax), the script engine won’t be able to execute the script. However, once you’ve written some useful scripts, you’ll probably need to go back to make some changes to a script you wrote six months or a year ago. If you didn’t write that code with human readers, as well as computers, in mind it could be pretty difficult to figure out what you were thinking and how you decided to solve the problems at the time you wrote the script. Things can get worse. What happens when you or one of your coworkers has to make some changes to a script you wrote many months ago? If you did not write that script to be both readable and maintainable, others who use your code will encounter difficulties deciphering it — no matter how well written the actual computer part of the code is.

Adding comments to your code is just one part of making sure code is clear and readable. There are many other things that you can do:

  • Choose clear, meaningful variable names.
  • Indent code for clarity.
  • Make effective use of white space.
  • Organize the code in a logical manner.
All of these aid human-readability and are covered later, but clear, concise comments are by far the most important. However, too much of a good thing is never good and the same is true for comments. Over-burdening code with comments doesn’t help. Remember that if you are scripting for the Web that all the code, including the comments, are downloaded to the browser, so unnecessary comments may adversely affect download times.

You have learnt about some good commenting principles, but for now just be aware of the fact that the comment in line 2 of the script is not really a good comment for everyday use. This is because, to any semi-experienced programmer, it is all too obvious that what you are doing is declaring the strName variable on the code line above. This is because the point of the code is to instruct the reader in how a particular aspect of VBScript programming works, and the best way to do that is to add comments to the code directly. It removes ambiguity and keeps the code and comments together.

Also worth noting is that comments don’t have to be on a separate line. Comments can also follow the code, like so:

Dim strName ' Initialize the variable
strName = InputBox("Hey! What is your name?") ' Ask for the user's name
MsgBox "Hello " & strName & "! Nice to meet you." ' Display a greeting in a popup

------------------------------------------------------------------------------------------------------------------------------------
Have questions on this article? Feel free to ask me in the comments section below.

If you like this post, I would suggest you to subscribe my RSS feed to have future articles delivered to your email address directly.
------------------------------------------------------------------------------------------------------------------------------------

Saturday, June 4, 2011

General Run Error on using Browser.Back

I got a question from one of my esteemed reader which I am posting below:

Issue:
I am trying to use 'Browser("Browser").Back' but I always General Run Error. I am using QTP 9.5 and IE7. I have tried uninstalling/reinstalling QTP but the issue is still not fixed. It also seems to fail when I try Browser methods (I have also tried Browser("Browser").Refresh and it came up with the same error).

Possible Solution:

1. In IE settings, go to Tools -> Manage Add-ons
2. Select the BHOManager Class
3. Click the Enable button

If the above solution doesnt work, you can also try the below code:

Set oWshShell = CreateObject("WScript.Shell")
oWshShell .SendKeys "{BS}"

QTP Tip | Check Status of WebEdit

The following QTP code will check if a textbox is enabled or not

If Not oWebEdit.Object.Disabled Then
Msgbox "Object is Enabled"
Else
Msgbox "Object is Disabled
End If

QTP Mercury DeviceReplay vs SendKeys

Mercury DeviceReplay is a powerful utility to simulate keyboard input and also for simulating mouse clicks and movements. Under Java Add-in, you can find the DeviceReplay property. At times, Object.Set and Object.Type doesnt help in QTP for some applications. You can use Mercury DeviceReplay to type Non English symbols and letters even without changing the keyboard layout or installing the special fonts.

In Order to use the DeviceReplay methods, you need to create DeviceReplay object.

Set objDeviceReplay = CreateObject("Mercury.DeviceReplay")

We use SendKeys method to send keyboard input/keystrokes to applications that dont have automation interface. We can also send more than one keystroke at a time using Sendkeys method. To send keystrokes x,y and z, you would send the string argument "xyz".

Note: You cannot send Print Screen key to an application.

So, the difference between Mercury DeviceReplay and Sendkeys is

SendKeys -> Support only Keyboard Operations
DeviceReplay-> Support Keyboard + Mouse Operations like Drag Drop too.

In addition to that DeviceReplay supports sending multilingual characters and symbols, while sendkeys support limited keyboard operations.

The other operational difference is dependency on QTP software.

Mercury.DeviceReplay :- It comes with QTP as a module, so you need QTP on the system and only from QTP action you can use it.
SendKeys :- It could be used in VBS script to simulate keyboard inputs with native windows shell commands. It has no dependency on QTP as such.

Out of Mercury DeviceReplay and SendKeys, which one should I use for Automation testing with QTP?

1. Depends on your objective like mouse operations & multilingual testing required.
2.In case of normal keyboard operations supported by both, SendKeys is easy to use due to English like syntax for keyboard input. Whereas for devicereplay you need to define user friendly names/constants (like VK_SHIFT etc) to numeric keycodes.

Friday, June 3, 2011

QTP 11 patch Slow Results Viewer

I have recently upgraded from QTP10 to QTP11 and after running a sample script in QTP11, I found that it took ages to open Results Viewer. Fortunately, there is a solution for this issue as well. HP has provided a hotfix RRV_00013. This patch will resolve the following issues:

1. Reduce the time to open large results in QTP11.
2. Reduce the time to export large run results in QTP11.
3. Fixed the issue where run results where not displayed correctly.
4. Fixed the issue when sometimes the run results viewer gets crashed.
5. Displays the data table in results for business process tests created using Quality Center 10.00.
6. This hotfix provides the support for multiple icon file types other than the standard .ico files. It supports *.jpg, *.gif and *.png.

Tuesday, February 8, 2011

QTP Web Services

What are web services?

Web Services: A vague term that refers to distributed or virtual applications or processes that use the internet to link activities or software components.

With the use of Web services, an application can publish its function or message to the rest of the world.

For example a travel website that takes a reservation from a customer, and then sends a message to a hotel application, accesses via the web, to determine if a room is available, books it, and then tells the customer he or she has a reservation is an example of a web services application. [Real world web services By Will Iverson]

Why web services are important when we have other technologies like RMI, CORBA etc.?

Web Services are platform-independent and language-independent, since they use standard XML languages. This means that my client program can be programmed in C++ and running under Windows, while the Web Service is programmed in Java and running under Linux.

Most Web Services use HTTP for transmitting messages (such as the service request and response). This is a major advantage if you want to build an Internet-scale application, since most of the Internet's proxies and firewalls won't mess with HTTP traffic.

One of the oft-cited advantages of web services is the fact that they lend themselves naturally to build loosely coupled systems. These types of systems are more scalable than strongly coupled systems, and impose fewer architectural requirements on the actual implementation of the web services. Suffice it to say that the reason why web services are ideal to build loosely coupled systems is because they are message-oriented and rely on language-neutral XML dialects to send messages, to specify interfaces, etc.

What are the disadvantages of web services?

Overhead: Transmitting all your data in XML is obviously not as efficient as using a proprietary binary code. What you win in portability, you lose in efficiency. Even so, this overhead is usually acceptable for most applications, but you will probably never find a critical real-time application that uses Web Services.

Lack of maturity: Web Services are relatively new and, though the core specifications that deal with fundamental languages (XML, WSDL,..) and protocols (HTTP, SOAP,…) are pretty stable the world of web services is still evolving at a fast pace. Standards dealing with more advanced capabilities expected from distributed systems, such as transactions, security, etc. are either very new or still in the works. [Globus Toolkit 4: programming Java Services By Borja Sotomayor, Lisa Childers]

Some Definitions:

Web Services Description Language (WSDL)

WSDL (Web Services Description Language) is an XML-based language for describing Web services and how to access them. You can see more on it here.

SOAP (Simple Object Access Protocol, or Service Oriented Architecture Protocol)
SOAP is a simple XML-based protocol to let applications exchange information over HTTP. You can see more on it here.

UDDI (Universal Description, Discovery and Integration)

Universal Description, Discovery and Integration (UDDI) is a directory service where businesses can register and search for Web services.

UDDI is a platform-independent framework for describing services, discovering businesses, and integrating business services by using the Internet.

UDDI stands for Universal Description, Discovery and Integration
UDDI is a directory for storing information about web services
UDDI is a directory of web service interfaces described by WSDL
UDDI communicates via SOAP
UDDI is built into the Microsoft .NET platform
You can see more on it here.

A small example of Web Service (invocation) to make it even more understandable:

1. A client may have no knowledge of what Web Service it is going to invoke. So, our first step will be to discover a Web Service that meets our requirements. For example, we might be interested in locating a public Web Service which can give me the weather forecast in US cities. We'll do this by contacting a discovery service (which is itself a Web service).

2. The discovery service will reply, telling us what servers can provide us the service we require.

3. We now know the location of a Web Service, but we have no idea of how to actually invoke it. Sure, we know it can give me the forecast for a US city, but how do we perform the actual service invocation? The method I have to invoke might be called "string getCityForecast(int CityPostalCode)", but it could also be called "string getUSCityWeather(string cityName, bool isFarenheit)". We have to ask the Web Service to describe itself (i.e. tell us how exactly we should invoke it).

4. The Web Service replies in a language called WSDL.

5. We finally know where the Web Service is located and how to invoke it. The invocation itself is done in a language called SOAP. Therefore, we will first send a SOAP request asking for the weather forecast of a certain city.

6. The Web Service will kindly reply with a SOAP response which includes the forecast we asked for, or maybe an error message if our SOAP request was incorrect.
For more on web services you can read [Globus Toolkit 4: programming Java Services By Borja Sotomayor, Lisa Childers]