You are on page 1of 222

QTP Complete Reference QTP Guide

Step by Step QTP Guide for beginners as well as advanced learners. It explains QTP Tool fundamentals and features in detailed manner. It covers QTP tool window keyelements, QTP test process, Recording and Running tests,Enhancing tests, Debugging Tests, Analyzing Test Results and Reporting Defects. It describes QTP important features like Step Generator, Sychronization, Parameterization, Recovery scenarios and Object Identification Configuration.

An overview on Test Automation QTP Basic features Add-in Manager Key elements of QTP Test Pane QTP Commands QTP Test Process Recording Tests

Keyword Driven Methodology Test Object Model

Object Repository Object Identification Configuration QTP Test Methods Data Table Methods Descriptive Programming Enhancing Tests Inserting Checkpoints Inserting Output values Parameterization Synchronization Inserting Transaction Points Step Generator Adding Comments Inserting Flow Control Statements Debugging Tests Running/Executing Tests Analyzing Test Results & Reporting

Reporting Defects Actions Functions Environment Variables Regular Expressions Virtual Object Configuration Batching Testing Recovery Scenarios File System Operations Database connections Automation Object Model Dynamic Handling of Object Repositories QTP Performance Tips
****************************************

QTP Scripting
QTP Tests in VB Script orientation provides a real-time approach on Scripting. It explains Flat file scripts, Excel Scripts, GUI Scripts, Web scripts, Database scripts and xml scripts with syntax and examples.

****************************************

File System Scripts Flat File Scripts Database Scripts-I Database Scripts-II Excel Scripts GUI Scripts Web Scripts Web Scripts -II QTP Real-time Script Examples Network Administration System Administration Power point Scripts Word Scripts XML Scripts

QTP Skills Error Handling in QTP ****************************

VB Script for QTP


It explains VB Script in QTP orientation, It covers all most all VB Script Fundamentals and Features. It describes, Variables, constants declarations, usage of operators, VB Script flow control statements, Procedures, Coding conventions, Regular Expressions, File system Operations, Database Operations etc.. ****************************************

Scripting Languages Vs Programming Languages VB Script Fundamentals & Features Comments VB Script Variables VB Script Data Types VB Script Operators Input/Output Operations VB Script Constants VB Script Conditional Statements

Loop through Code VB Script Statements VB Script Procedures VB Script Errors VB Script Built-In Functions User Defined Functions Regular Expressions VB Script Methods VB Script Objects VB Script Coding Conventions VB Script Classes VB Script Keywords VB Script syntax rules and guidelines VB Script General Examples VB Script General Examples-II VB Script Glossary
******************************************

QTP Framework
This section provides concepts on How to implement Automation Framework. It explains about Automation Infrastructure development, Resources creation, Driver script creation, Initialization script creation etc. It describes data driven framework, keyword driven framework and Hybrid framework in detailed manner. It also provides Test estimations, Approvals, Reporting, Organizing and maintaining frameworks. **********************************************

QTP Interview Questions QTP Model Resumes


This

section provides, Resume preparation guidelines for fresher as well

as experienced. It provides some model QTP Resumes for reference.

QTP Job News


This section Provides QTP Job news weekly. Information can be collected by Employers, Consultants and employees. QTP Professionals can use this information and their resumes directly to Employer's and consultants mail ids.

QTP Certification
This section provides HP QTP Certification guidelines and model Questions, It useful for QTP test professionals for preparing Certification exam.

QTP Training Programs


This section provides information on variou QTP Training programs like QTP Basics program for beginners, Advanced program for working people, QTP Framework, and VB Script for QTP that conducted by gcreddy.com

Manual Testing Documents


This section Provides link to our another website gcreddy.net, there you can get Manual Testing Information like, Software Testing Guide, Manual Testing Interview question and answers, Test management guidelines, Test planning, Test design and other documents. *******************************************

Quality Center

This Section Provides Quality Center Fundamentals and features; Site Administration, Creating Domains, Projects, and Users. Creating Requirements, Designing Manual & Automated Tests, Executing Manual and Automated Tests and Entering defects. Sending Defects directly from QTP Result window. **********************************************************

LoadRunner
This section provides LoadRunner tool Fundamentals and Features; Vuser generator, Controller, Load Generator, Analysis and LoadRunner Interview Questions. *********************************************************

QTP Other Topics


This section provides QTP Related articles and other information like, challenges in Test Automation using QTP, Migrating Test scripts from old version to New version, QTP trends, enhancements, New release information, Browser compatibility issues etc..

QTP Software Download Link SQL Server Guide Software Testing Documents
Documents on Unit Testing, Web Testing, Software Testing Artifacts, Software Test Process Etc..

QTP Basic Features

QTP was Launched in 2002 (Nov). By Mercury Interactive. Later taken over by HP, in 2007. QTP is an Object Based Testing Tool.

(Object based means; QTP Follows Test Object Model for Performing Testing operations. Based on either Test Objects or Automation Objects or Utility Objects only, we can automate test operations) (LoadRunner is a Protocol based Test Tool) QTP is for Functional and Regression Testing. (Basically QTP is a Functional and Regression Test tool but we can use it for little bit Compatibility Testing and Performance Testing)

It follows Keyword Driven Approach.

(Keyword Driven Approach means; Keywords, example: Commands, functions, methods, statements etc.. are used for creating Test scripts) It supports Windows Operating Environment only. (QTP basically depends on User Interface to automate test operations and it is not depends on server side interactions, where as LoadRunner depends on server side Operations, so HP developed LoadRunner for Windows as well as UNIX versions) It supports GUI based (Graphical user interface) and Web based Applications Automation, does not support CUI (Command user interface) Applications. It has multilingual support. (It supports English, Chinese, Japanese, Korean, etc languages with respect to license.) It has adapted Microsoft Visual Basic Scripting edition for programming and Excel like spread sheet for Data driven testing. Tools support for QTP: ----------------------------- VB Script for Scripting (for implementing programming logic) VB Script engine integrated in QTP, so apart from scripting features we can use File system, Excel, word, Adodb etc. Object models from QTP. SQL (Structured query language) engine integrated in QTP, so we can use SQL Statements in QTP to perform Database Operations Excel like spread sheet integrated in QTP for performing Data driven Testing We can install MS Script Debugger with QTP for Debugging Test scripts. QTP uses XML format for Test results, Environment variables and for exporting object repositories. ------------------------------------------------------ QTP can be integrated with other Tools like WinRunner and Quality Center. QTP can be used for user interface (UI) test case automation and some limited (Non UI) Test case automation like File system operations

and Data base operations. It was derived from Astra QuickTest (mother tool of QTP).

It supports IE (Internet Explorer) only for recording tests, for execution it supports other browsers like Mozilla and AOL, opera Etc apart from IE. QTP is a Desktop Application (I-Tier/Stand alone). QTP developed in .NET Technology.

Since it is Stand-alone Application, It doesn't have Database, It stores resources as files (Internal and External). We can't share qtp services from one machine to another, but we can share resources(Ex: Object Repository files, Function Libraries, Environment variable files, Recovery scenario files etc...) QTP has two types of License; Seat or Node locked License, Concurrent or float license.

We have to use Seat license from fixed system/machine and Concurrent License, we can use from any system but one user at a time. If we want multiple concurrent licenses that we can purchase. QTP has UNI code support.

Version History of QuickTest Professional Astra QuickTest (Mother tool of QTP) 1.0 to 5.0 * QTP derived from Astra QuickTest and influenced by WinRunner. Quick Test Professional 5.6 Nov 2002 6.5 2003

8.0 2004 8.2, 8.3 2005 9.0,9.1-2006

9.2- 2007 Mercury Interactive 9.5 2008 H.P 10.00 2009 January 11.00 2010** (It is Latest Version) Overview ---------------------------------------------------------------a) Disadvantages of Manual Testing 1) Huge Amount of Human Resources as well as Environment (Test lab) 2) Time taking process 3) Less Accuracy 4) Tideness

b) Advantages of Test Automation 1) 2) 3) 4) 5) 6) Fast Reliable Accurated Reusable Repeatable Comprehensive

c) Draback of Test Automation 1) Expensive 2) Technical expertise 3) 100% Automation not Posible

d) Types of Test Tool Business cla Technical cla -------------------------------------Vendor Tools Functional & Regression Test tools Opensource Performance/Load/stress Test tools

In-House Test Management Tools Defect Management Tools Security Unit Test tools Etc... -----------------------------------------------------------------------I) Basic Features of QTP ------------------------------------------------------------------------a) QTP Supporting Environments 1) UI (GUI/Windows and Web) 2) Only Windows (Clien side and Server side) b) Version History QTP derived from Astra QuickTest(1.0....5.0) 5.6 2002 (Nov) 6.5 2003 8.0 2004 8.2 2005 9.0, 9.1 2006 9.2 2007 9.5 2008--------HP 10.0 2009 (Jan)

c) QTP License(Seat/Node Locked and Concurent/Float) c) QTP IDE 1) QTP Features Ex: Recording, Checkpoints, Object Repository etc... 2) Integrated Tools (HP) Ex: Password Encoder, Test Batch Runner, Test Result Dletion Tool etc.. 3) Integrated Tools (Others) Ex: Spread sheet, VB Script Engine, SQL Engine, MS Script Debugger d) Key elements of QTP 1) Test Pane 2) Active Screen 3) Data Table 4) Debug Viewer 5) Information Pane 6) Missing Resources 7) QTP Commands

--------------------------------------------------------------------------II) QTP Test Process --------------------------------------------------------------------------Manual Test Process (STLC) Vs QTP Test Process ----------------------------------------------------------------I) Planning I) Planning a) Analyzing Requirements a) Analyzing the AUT b) Test Strategy Implentation b) selecting/Creating Test case for Automation c) Test estimations c) Test Estimations & Approvals d) team formation d) Automation framework Implementation e) Risk Analysys e) QTP Tool Settings Configuration f) Configuration management g) Defining Test Environment h) Test Plan Documentation -------------------------------------------------------------------------------II) Test Design IIA) Creating the Basic Tests a) Understanding & Analyzing Reqs b) Generating Test Scenarios c) Test case Documentation a) Repository based Test creation 1) Recording (Local Repository) 2) Keyword driven methodology (Shared Repository) b) Descriptive Programming 1) Static Programming 2) Descriptive Programming

IIB) Enhancing Tests a) Adding Comments b) Inserting Checkpoints c) Inserting Output values d) Inserting Transaction points e) Generating steps thru Step Generator f) Inserting Flow Control Statements g) Synchronization h) Parameterization i) Calling Functions / Actions j) Using Regular expressions k) Using Environment Variables l) Using Automation Objects (using Object Models)

---------------------------------------------------------------------------------III) Test Execution IIIA) Debugging Tests (Optional) ---------------------------------------------------------------------------------a) Forming Test Batches/suites a) Step by step execution b) Test Environment setup b) Watching Variables c) Test Execution c) Locating & Isolating Errors d) Analyzing Test Results d) Defect Reporting e) Defect Tracking III B) Running Tests f) Re & Regression Testing a) Single Test Run g) Test status Reporing b) Batch Testing h) Test Logs c) Executing Tests thru Framework i) Final Regression d) Scheduled execution e) Analyzing Results f) Result Reporing g) Defect Reporing h) Regression Testing -----------------------------------------------------------------------------------------IV) Test Closure IV) Test Closure ----------------a) evaluating Exit Criteria a) Sending Test scripts & Resources to Customer b) Collecting all facts from Test Activities b) Maintaning Tests & Resouce files c) sending Test Delivarables to Customer c) Improvement Suggessions d) Improvement Suggessions for QA Process -------------------------------------------------------------------------------------------III) Creating Tests / Test Scripts ----------------------------------------------------------------------------------------1) Repository based Test Design a) Recording (Local repository) b) Keyword Driven methodology (Shared repository) 2) Descriptive Programming a) Static Programming b) Dynamic programming

Recording Tests ---------------a) Recording Process b) Recording Modes i) Normal Recording ii) Analog Recording iii) Low Level Recording c) Running Process Object Repository: -----------------a) Object and Types of Object i) Run-time Objects ii) Test Object Model iii) Utility Objects iv) Automation Objects

b) Types of Object Repository i) Local Repository ii) Shared Repository c) Operations on Object Repository i) Adding Objects ii) Renaming Objects iii) Deleting Objects iv) Exporting Local Objects v) Merging Repositories vi) Associating Repositories to an Action vii) View Options viii) Exporting Objects to XML/Importing Objects from XML iX) Defining New Test Objects X) Spying Objects

d) Object Identification Configuration

i) Normal identification 1) Mandatory properties 2) Assistive properties ii) Smart Identification (Optional) 1) Base Filter properties 2) Optional Filter properties iii) Ordinal Identifier 1) Location 2) Index 3) Creation Time (Only for web Application) Keyword driven methodoly: ------------------------a) Creating Shared Object Repositories b) Associating Repositories to an Action c) Creating tests manually i) Thru Expert View ii) Keyword View iii) generate steps thru Step Generator

Descriptive programming: -----------------------a) Static programming i) identifying Unique Properties for Objects ii) Creating Constants iii)Creating Library file for constants iv) associating Library files / loading Library files during run-time v) Using Constants, generating Tests b) Dynamic Programming i) Creating Collection Objects ii) Entering Properties Information into Collection Objects iii) Using Collection Objects, generating tests c) Handling Dynamic Objects using Regular expressions

d) Handling Duplicate/Similar Objects using Index property ------------------------------------------------------------------------------------------------------

Key Elements of QTP Tool Window


1) Test Pane: It is programming interface of QTP, used for creating, editing, viewing and deleting test scripts. Test: It is a set of statements or set of one or more actions. (It is a local concept) Action: It is a set of Statements. (It is a local concept) Statement: A minimal executable unit. Statements may have keywords. (Keyword such as function, method, statement etc). It is a global concept.

Test pane has 2 views. Expert view- Test in VB script format. Key word view- Test in Icon based GUI format.

Note1: Here in test pane Test is same but views are different, if you perform anymodifications in one view those automatically reflects in another view. Note 2: Technical users use expert view and business user use key word view. Note 3: User can customize Test pane view options. Navigation: Tools Menu> view options> we can use font size and colors etc. 2) Active Screen It has an optional element of QTP, it takes snap shots of every statement that user performed action or operation on AUT. It can be used for understanding and editing the test easily. Navigation: View menu>active screen (for launching and closing)

Configuring Active Screen: view>options>active screen tab>increase /Decrease capture level, apply and okay. Note 1: Generally novice testers use this feature but it occupies lot of memory space on QTP. 3) Data Table

It has an integrated spread sheet (Excel like), used for Data driven testing. Navigation: View menu>Data table (for launching and closing)

Data driven Testing: Testing the same task(S) or same operation with multiple sets of test data. It can be used in two ways. 1. Enter test data directly into Data Table and use. 2. Importing data from external files (Flat files, excel sheets, etc) and Data bases (MS access, Sql Server, oracle, etc.) It has two types of sheets. 1). Global Sheet- for entire Test /used for all actions in the Test. 2). Action Sheets- for specific Action only. Data table available in 2 ways: 1). Design time data table. (Attached with every test) 2). Run time data table. (Available in result window) Run time is a carbon copy of design time data table. QTP has Data table methods for performing operations on data table.

4) Debug Viewer It is used for locating and rectifying or fixing errors. It can be used for debugging the tests by step-by-step execution. We use Step into, Step over and Step out commands for debugging. (debug commands) Navigation: View menu>debug viewer (for launching and closing)

Through Debug viewer user can watch variables and change values of variables temporarily. 5) Missing Resources It can be used for showing missing resources that attached to current test such as (Recovery Scenarios, Library files etc). Navigation: View menu >missing resources (for launching and closing) 6) Information This pane shows syntax errors automatically during saving the test. Navigation: view menu> information

7) QTP Commands QTP Commands are available in 3 ways. 1). Menu options 2). Tool Bar options 3). Short cut keys (for Some important operations only)

QTP Tool Window Menus

File menu: Through file menu user can create, save tests, open existing tests, export tests in zip format.

Edit Menu: It provides editing options and renaming, deleting and splitting actions. View menu: Through this menu we can launch and close, active screen, Data Table, Debug viewer, information, missing resources etc. Insert Menu: Through this menu user can inserting check points, out put values,synchronizing points. In this menu step generator available, using this user can generate recordable and non-recordable scripts. Through insert menu user can insert VB Script conditional and loop statements and transaction points (Start and End). Through insert menu user can create new actions, call existing actions and copy existing actions. Automation Menu: This menu provides Record, Run options and Run setting options Through this menu we can start normal recording, analog recording and Low level recording. Through this menu we can stop recoding, running and also we run tests. Resources Menu: This menu provides object repository and recovery scenarios options. Through this menu we can create /modify/delete objects information and we can associate repositories. Through this menu we can create, modify and delete recovery scenarios. Debug Menu: This menu provides debug commands for step by step execution. Through this menu we can insert/remove/break points.

Tools Menu: This menu provides Tools settings option, view options and object identification configuration. Through this menu we can set tool options as well as test pane view options. In this menu object spy option available, through this we can get objects information.(Properties and values) In this menu Virtual object option available; through this option we can create virtual objects. Window Menu: This menu provides QTP tool window style settings. Help Menu: This menu provides QTP help as well as VB Script help. Through this menu we can contact technical support people and we can send feedback. Through this menu we can check for updates and download or install directly.

QTP Commands
QTP Commands are available in 3 ways. 1.Menu options 2.Tool Bar options 3.Short cut keys (for Some important operations only) File menu: Through file menu user can create, save tests, open existing tests, export tests in zip format.

Command New > Test Creates a new test.

Function

New > Business Component Creates a new business component. New > Scripted Component Creates a new scripted component. New > Application Area New > Function Library Creates a new application area. Creates a new function library.

Open > Test Open > Business/Scripted Component Open > Application Area Open > Function Library Close Close All Function Libraries

Opens an existing test. Opens an existing business or scripted component. Opens an existing application area. Opens an existing function library. Closes the active function library. Closes all open function libraries.

Quality Center Connection Opens the Quality Center Connection dialog box, enabling you to connect to a Quality Centerproject. Quality Center Version Control Provides a sub-menu of options for managing versions of QuickTest assets in Quality Center. The sub-menu is available only when you are connected to version-control enabledQuality Center project. Saves the active document. Opens the relevant Save dialog box so you can save the open document. Saves a standalone copy of the current test together with its resource files. Saves all open documents. Makes read-only function libraries editable. Creates a zip file of the active document. Imports a document from a zip file. Converts a business component to a scripted component. Prints the active document. Displays the Keyword View as it will look when printed and enables you to modify the page setup.

Save Save As Save Test with Resources Save All Enable Editing Export Test to Zip File Import Test from Zip File Convert to Scripted Component Print Print Preview

Settings

Opens the Settings dialog box, enabling you todefine settings for the open document. (Not relevant for function libraries) Opens the Process Guidance Management dialog box, enabling you to manage the list of processes that are available in QuickTest.

Process Guidance Management

Associate Library Associates the active function library with the '<Function Library Name>' open document. (Available only from function with '<Document Name>' libraries) Recent Files Exit Lists the recently viewed files. Closes the QuickTest session.

Edit Menu: It provides editing options and renaming, deleting and splitting actions.

Command Undo Redo Cut Copy Paste Delete Copy Documentation to Clipboard Action > Split Action Action > Rename Action Action > Delete Action

Function Reverses the last command or deletes the last entry you typed. Reverses the most recent operation of the Undo command. Removes the selection from your document. Copies the selection from your document. Pastes the selection to your document. Deletes the selection from your document. Copies the content of the Documentation column of the Keyword View, enabling you to paste it in an external application. Separates an action into two sibling actions or into parent-child nested actions. Changes the name of an action. Enables you to remove the selected call to the action, or delete the action and its calls from the active test.

Action > Action Properties Enables you to specify options, parameters, and associated object repositories for a stored action. Action > Action Call Properties Enables you to specify the number of run iterations according to the number of rows in the Data Table, and to define the values of input parameters and the storage location of output parameters.

Step Properties > Comment Opens the Comment Properties dialog box for a Properties comment step. Available only when the selected step is a comment. Step Properties > ObjectProperties Step Properties > Checkpoint Properties Step Properties > Output Value Properties Step Properties > Report Properties Find Replace Go To Bookmarks Advanced > Comment Block Advanced > Uncomment Block Advanced > Indent Advanced > Outdent Opens the Object Properties dialog box for a selectedobject. Available only when the selected step contains a test object. Opens the relevant Checkpoint Properties dialog box for a selected object. Available only when the selected step is a checkpoint step. Opens the relevant Output Value Properties dialog box for a selected object. Available only when the selected step is an output value step. Displays the Report Properties dialog box for a report step. Available only when the selected step is aReporter.ReportEvent step. Searches for a specified string. Searches and replaces a specified string. Moves the cursor to a particular line in the test. Creates bookmarks in your script for easy navigation. Comments out the current row, or selected rows. Removes the comment formatting from the current or selected rows. Indents the step according to the tab spacing defined inthe Editor Options dialog box. Outdents the step (reduces the indentation) according to the tab spacing defined in the Editor Options dialog box.

Advanced > Go to Function Navigates to the definition of the selected function.

Definition Advanced > Complete Word Completes the word when you type the beginning of a VBScript method or object.

Advanced > Argument Info Displays the syntax of a method. Advanced > Apply "With" Generates With statements for the action displayed in to Script the Expert View, and enables IntelliSense within Withstatements. Advanced > Remove "With" Statements Optional Step Converts any With statements in the action displayed in the Expert View to regular (single-line) VBScript statements. Inserts an optional step (a step that is not required to successfully complete a run session).

View menu: Through this menu we can launch and close, active screen, Data Table, Debug viewer, information, missing resources etc. Insert Menu: Through this menu user can inserting check points, out put values, synchronizing points. In this menu step generator available, using this user can generate recordable and non-recordable scripts. Through insert menu user can insert VB Script conditional and loop statements and transaction points (Start and End). Through insert menu user can create new actions, call existing actions and copy existing actions. Automation Menu: This menu provides Record, Run options and Run setting options Through this menu we can start normal recording, analog recording and Low levelrecording. Through this menu we can stop recoding, running and also we run tests.

Command Record

Function Starts a recording session.

Run Stop Run Current Action Run from Step Maintenance Run Mode

Starts a run session from the beginning or from the line at which the session was paused. Stops the recording or run session. Runs only the active action. Starts a run session from the selected step. Starts a run session during which the Maintenance Run Mode wizard opens for steps that failed because an object was not found in the application(if applicable). Starts a run session to update test objectdescriptions and other options (if applicable). Starts recording in Analog Recording mode. Starts recording in Low Level Recording mode.

Update Run Mode

Analog Recording Low Level Recording

Record and Run Settings Opens the Record and Run Settings dialog box, enabling you to define browser preferences for recording and running your test. Process Guidance List Lists the processes that are available for the current document type and for the currently loaded QuickTest add-ins, enabling you to open them. Enables you to view results for a test run session.

Results
Resources Menu:

This menu provides object repository and recovery scenarios options. Through this menu we can create /modify/delete objects information and we can associate repositories. Through this menu we can create, modify and delete recovery scenarios.

Command Object Repository

Function Opens the Object Repository window, which displays a tree containing all objects in the current test or component. Opens the Object Repository Manager dialog box,

Object Repository Manager

enabling you to open and modify multiple sharedobject repositories. Associate Repositories Opens the Associate Repositories dialog box, enabling you to manage the object repository associations for the test. Opens the Map Repository Parameters dialog box, enabling you to map repository parameters, as needed. Opens the Recovery Scenario Manager dialog box.

Map Repository Parameters

Recovery Scenario Manager

Associated Function Libraries Lists the function libraries associated with the active document, enabling you to open them.
Debug Menu: This menu provides debug commands for step by step execution. Through this menu we can insert/remove/break points. Tools Menu: This menu provides Tools settings option, view options and object identification configuration. Through this menu we can set tool options as well as test pane view options. In this menu object spy option available, through this we can get objects information.(Properties and values) In this menu Virtual object option available; through this option we can create virtual objects.

Command Options View Options

Function Opens the Options dialog box, enabling you to modify global testing options. Opens the Editor Options dialog box, enabling you to customize how tests and function libraries are displayed in the Expert View and Function Library windows. Checks the syntax of the active document. Opens the Object Identification dialog box, enabling you to specify how QuickTest identifies a particular test object. Opens the Object Spy dialog box, enabling you to view the native properties and operations of any object in an open

Check Syntax Object Identification Object Spy

application, as well as the test object hierarchy, identification properties, and operations of the test object that QuickTest uses to represent that object. Web Event Recording Configuration Data Driver Change Active Screen Virtual Objects > New Virtual Object Opens the Web Event Recording Configuration dialog box, enabling you to specify a recording configuration level. (Relevant for tests only) Opens the Data Driver dialog box, which displays the default Constants list for the action. (Relevant for tests only) Replaces the previously recorded Active Screen with the selected Active Screen. (Relevant for tests only) Opens the Virtual Object Wizard, enabling you to teach QuickTest to recognize an area of your application as a standard test object.

Virtual Objects > Virtual Opens the Virtual object Manager, enabling you to manage all Object Manager of the virtual object collections defined on your computer. Customize Opens the Customize dialog box, which enables you to customize toolbars and menus, and create new menus.

Window Menu: This menu provides QTP tool window style settings. Help Menu: This menu provides QTP help as well as VB Script help. Through this menu we can contact technical support people and we can send feedback. Through this menu we can check for updates and download or install directly.

QTP Test Process


1) Planning o o o o o o

7 Stages of QTP Testing Process

Analyzing the AUT Automation Test Plan Generation Automation Framework Implementation Generating/Selecting Test cases for Automation Collecting Test Data QTP Tool Settings Configuration

2) Generating Tests o Recording o Keyword driven methodology o Descriptive Programming 3) Enhancing Tests o o o o o o o o o o Inserting Checkpoints Inserting Output values Adding Comments Synchronization Parameterization Inserting Flow Control Statements Calling User defined functions and/or Reusable Actions Generating Steps though Step Generator Inserting Transaction Points Regular Expressions

4) Debugging Tests o o o o Debug Commands & Break Points Step by step execution Watching Variables Changing values of variables

5) Running Tests o o o o o Normal Execution Batch Execution Through AOM Scripting Tests Running through framework Scheduled Execution

6) Analyzing Results o o o o QTP Result window Defining our own Results Exporting Results Deleting Results

7) Reporting Defects o Manual Defect Reporting o Tool based Defect Reporting

o Working with Quality Center ----------------------------------------------------------Types of Statements in QTP Test / Test Script i) Declarations (Variables and constants) Dim x, y, z Const City, Price ii) Object calls Ex1: Dialog("Login").WinEdit("Agent Name:").Set "gcreddy" Ex2: Browser("Google").Page("Google").Link("Gmail").Click iii) Comments iv) Flow Control Statements (Conditional & Loop) Ex:) If Total=Tickets*Price Then Msgbox "Test Passed" Else Msgbox "Test Failed" End If v) Function / Action calls Ex: Call Login("gcreddy","mercury") vi) Utility Statements Ex1: SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" **It launche the Application Ex2: SystemUtil.Run "C:\Program Files\Internet Explorer\IEXPLORE.EXE","http://www.icicibank.com/" vii) VB script other statements Examples: Option Explicit Wait (14)

Recording Tests

Recording and Running


a) Test Recording Process

It is a Process of Recording user operations on AUT (Application Under Test). During Recording QTP Creates steps in Keyword view, and generates them in a script in the Expert view. Simultaneously it adds Objects information into ObjectRepository. b) Running /Execution Process During Running QTP reads statements one by one and gets Object Information from the Object Repository, based on that Information performs operations on AUT. c) Recording Modes QTP has 3 Recording Modes to generate Tests / Test Scripts i) Normal Recording It records User Mouse and Keyboard operations on AUT with respect to objects, but unable to record continuous mouse operations like Digital Signatures, graphs, paints etc. During recording QTP generates VbScript statements in Test Pane, Simultaneously it stores objects information into object repository. Navigation: Automation>Record Or Select Record option on automation toolbar Or Use short cut key (F3) Steps for preparing a Test (through Recording): 1.Put AUT in base state 2.Select Record Option 3.It shows Record and Run Settings, Select type of Environment (Windows or Web) 4.Select Record Option (It shows two Options : 1.Record and Run Test on any open window based applications 2.Record and Run only on) If we select first option it records on any opened application on Desktop. If we select Second option, it asks for the path of the AUT, After Providing the path it records only on that particular application.)

5.Click OK 6.Perform actions on AUT 7.Stop recording. 8.Save the Test ii) Analog Recording: It records the exact mouse and keyboard operations. We can use this mode for recording continuous mouse operations. It is not useful for recording normaloperations why because it does not generate steps for each operation, generates total user actions in a Track File. The Track file is not editable. Navigation: 1.Keep tool under recording mode 2.Automation >Analog Recording OR Use Short cut Key (Shift + ALT+F3) Steps for preparing a Test (through Analog Recording): 1.Launch AUT (or we can launch AUT through QTP) 2.Select Record option 3.Automation>Analog Recording 4.Analog Recording Settings Dialog box opens (In this Dialog box two options available. 1.Record relative to the screen 2.Record relative to the following window) (If we select first option QTP records User operations with respect to Desktop co-ordinates. If we select Second option, we have to show the window (AUT), after showing the Window it records with respect to that window co-ordinates.) 5.Select any one option in the dialog box and click Start Analog record. 6.It records User actions 7.Stop Recording iii) Low Level Recording It records some operations on Non-supported environments apart from Normaloperations.

This mode records at the object level and records all run time objects as window or winobject Test objects. Use Low Level Recording for recording in an environment not recognized by QTP. Navigation: 1.Keep tool under recording mode 2.Automation >Low Level Recording Steps for preparing a Test (through Low Level Recording): 1)Launch AUT (or we can launch AUT through QTP) 2)Select Record option 3)Automation> Low Level Recording 4)Perform options on AUT 5)Stop Recording 6)Save the Test d) Disadvantages of Recording It occupies a lot of memory space(due to duplicate objects), So QTP performance will be reduced No Centralized Maintenance mechanism , So Modifications are very difficult User may not have command on the Recorded script, So locating errors is difficult Recorded scripts are QTP internal files, they may corrupt. e) Advantages of Recording/ Where Applicable It is used for Analyzing the AUT in the initial stage to find out weather the QTP tool is Recognizing all of our Application Objects or not It is easy to create Tests / Test Scripts It is used for frequently changing UI (User Interface) It takes less time to create Tests

Keyword Driven Methodology

Keyword-Driven Methodology
By creating our tests with a keyword-driven methodology in mind, our tests become more modular, focusing on the operations to test using both QuickTest built-in keywords and your own user-defined keywords. Additionally, because it is possible to add objects to the object repository before they exist in an application, it is possible to begin preparing our automated keyword-driven tests even before a software build containing the new objects is available. Setting up Object Repositories In this step, we build one or more object repositories and ensure that all objects have clear names that follow any predetermined naming conventions defined by ourorganization. We can create object repositories using QuickTest functionality to recognize and learn the objects in your application, or we can manually define objects. By creating and populating shared object repositories that can be associated with multiple actions, we can use the same object repository in multiple tests. Add (learn) objects from our application. We instruct QuickTest to learn the objects in our application according to filters that we define. Ensure that objects in the object repository have names that are easy for applicationtesters to recognize and that follow any established object naming guidelines. This helps make both test creation and maintenance easier over time. Configuring QuickTest According to our Testing Needs After we set up the test automation infrastructure, we need to configure QuickTest to use this infrastructure: Define your global testing preferences.

We need to specify configuration settings that affect how we create and run tests in generalthese settings are not test-specific. Building our Tests We can create tests that are as simple or complex as needed. In general, it is best to create tests and actions that check just one or a few simple functions or complete atransaction rather than creating long tests and actions that perform several complex tasks or that perform many tasks. We may perform the following tasks when creating tests and test steps: Create new tests, if needed. To do so, select File > New > Test. Create the required actions. Associate our object repositories with the relevant actions This enables us to insert steps that perform operations on those objects. Associate our function libraries with the relevant tests. This enables us to use our special keywords in any of the associated tests.

Object Repository

Object Repository: It is a storage place of QTP where objects information can be stored and it also acts as interface between the Test script and the AUT in order to identify the objects during execution. Object: Object is something, which has structure and properties. Software objects: We call Windows, Web Pages, Buttons, Edit boxes, Check boxes etc.. as software objects. Types of Object in QTP: There are four types of object available in QTP. 1. 2. 3. 4. Run time objects Test objects Utility objects Automation objects/User defined objects.

Run time objects: The objects present in the AUT. Ex: Buttons, Links, etc Test Objects: References of Run time objects. Ex: WinEdit, WinButton, WebButton, Link, etc Note: Test objects names vary from one environment to another. Utility objects They are QTP reserved objects used for Testing and Result reporting. Ex: 1. SystemUtil for launching/closing the application. 2. Reporter for defining results. 3. Services for inserting transaction points 4. Environment for using environment variables Automation objects/User defined objects User can create objects; those can be used for performing specific operations. Ex: Creating objects in filesystemobject class, adodb.connection class, dictionaryobject class, Excel. Application class etc. There are two types of repository available in QTP. 1. Local repository (.MTR extension) 2. Shared repository(.TSR extension) Local Repository: QTP creates a Local Repository for every Action automatically during Recording. That cannot be shared among tests. User can add some more objects to Local repository User can perform rename, delete operations on local repository. As it is QTP internal file user no need to save modifications.

Shared Repository: User (Test Engineer) creates the Shared Repository by adding objects. That can be shared among number of tests. Using this method user can perform modifications on objects easily.

Operations on Object Repository


Adding objects a. Local Repository: Navigation: open Local Repository (Resource Menu > Object Repository) objects>Add objects to Local> Show the Object>Click Ok (No need to save separately, it saves automatically) B. Shared Repository: Navigation: Resource menu>object repository manager>object>Add objects>show the window/object>click ok o o o o Selected object only Default object types All objects types Selected object types

(If we select first option it stores Selected objects only, if we select second option it stores all default objects, if we select third option it stores All objects including static objects, if we select fourth option, we

have to select objectclasses then it stores that class objects, we can select more than one class also.) Renaming Objects a. Local Repository: Resources > object repository >select object and right click >choose rename option >modify the name>release the mouse.>close repository b. Shared Repository: Resources >object repository manager>file>open>browse path of the repository file >file>enable editing>select object &Right click>choose rename option>modify the name > release mouse>save the file & close repository manager. Deleting Objects a. Local Repository: Resources > object repository >select object and right click >choose delete option >confirm deletion>. >close repository b. Shared Repository: Resources >object repository manager>file>open>browse path of the repository file >file>enable editing>select object &Right click>choose delete option>confirm the deletion >save the file & close repository manager. Associating Object Repositories to an Action/Test Resources>Associate repositories>click add icon (+)>browse path of the repository>Associate with an action>click ok Merging Repositories Resources > object repository manager>tools>object repository merge tool >browse path of the first repository> browse path of the second repository>click ok>click close>save the merged repository>close the repository manager. Note: After merging also, source repository files will be available, if we do not want source files we can delete.

Defining New Test Objects Navigation: Object>Define new test object >Select Environment>Select Class ofthe object>Enter name of the object>Click Add>click close>Select object>select property name>enter value (like this select one by one properties and enter values)>save Note: This feature can be used for preparing tests before the AUT is ready. Spying Objects For getting objects information, (Test objects names, property & Values) QTP isproviding a feature called Object Spy, using this we can get objects information. Navigation>Tools>object spy>take hand icon & Show the object>get information (Object Spy shows the specific objects all available properties with their values) Note: As Object spy is an important feature, it can be available in 3 Areas.(1. In tools Menu 2. In local repository 3. In Repository manager) View Options Locate in Repository This feature can be used for identifying objects from application to repository. Navigation: View>Locate in repository >show the object>click Ok>it locates specified object in the repository. Highlight in Application This feature can be used for identifying objects from repository to application. Navigation: Select object in the repository >view>highlight in application>it highlights specified objects in the application. Exporting Repository to an XML file We can export our repository file to an xml file.

Navigation: File >export Test objects to XML Enter the file name and Save with xml extension. Importing Repository from XML file. We can import XML file to our repository. Navigation: File>import from XML >browse path of the XML file >it loads objects. Note: The purpose of this feature is Editing objects information outside of the QTP Navigation: Resource menu>object repository (Short cut key Ctrl+R)

Object Identification Configuration


Overview:

Object Identification Configuration

Generally for every object 20-25 properties information available, qtp recognizes object using 2 0r 3 important properties. Qtp has default object identification configuration for every environment, if we feel that config is not sufficient for recognizing objects in our application, we can configure some more Object Identification Types a) 1) 2) b) 1) 2) c) 1) 2) 3) Normal identification Mandatory properties Assistive properties Smart identification base filter properties optional filter properties Ordinal identifier location index creation time(only for web)

QTP learns information in the following in case of

normal identification: First of all the qtp learns all the mandatory properties at a time and thinks whether theseproperties sufficient to identify the object uniquely. if it feels sufficient then it stops learning otherwise, It learns first assistive property and once again stops and thinks, like this qtp learns one by one. At the end of assistive properties list also if it feels not satisfied and it finally goes to Ordinal Identifier. QTP learns information in the following in case of Smart Identification: Smart identification is an optional feature, if we feel normal identification is not sufficient for any object, and then we configure Smart Identification for that object, in order to avoid Ordinal Identifier. After normal identification if qtp feels not satisfied then it goes to smart identification. in smart identification 2 types of properties available, first qtp learns all base filter propertiesat a time and thinks whether these properties are sufficient for identifying the object uniquely. If it feels sufficient, then it stops learning otherwise it goes Optional FilterProperties and learns one by one. Still it feels not satisfied finally it goes to Ordinal Identifier. Ordinal identifiers: There are 3 types of ordinal identifiers available 1) Location: is based on object location in the AUT ,location starts from zero. 2) index: it is based on sequence of the programs, index starts from zero 3) Creation time: it is based on loading time of the web objects. qtp generates 0,1,2 like numbers. Tool Settings Globalization: As QTP is a I-tier(Stand-alone) application,making Tool settings globally is not possible.

For making tool settings global, QTP is providing a special feature called "Generate Script". STEPS: 1) Settings available in 3 areas. a) File->Settings b) Tools->Options c) Tools->Object Identification 2) Perform required settings and generate Scripts 3) Share Script files to team members and ask them to execute those scripts. NOTE: After executing these scripts all team members can get same settings.

QTP Methods

QTP Methods / Operations


1) Activate Method It activates dialog boxes/Windows Syntax: Object hierarchy. Activate Ex: Dialog(Login).Activate Window(Flight Reservation).Activate 2) Click Method It clicks on an object (Buttons) Syntax: Object hierarchy. Click Ex: Dialog(Login).Winbutton(ok).click 3) Close Method It closes the window,Dialog box, Browser window etc. Syntax: Object hierarchy. Close Ex: Window(Flight Reservation).Close Browser(Browser).Close 4) Dblclick

It Double clicks the object. 5) Set Method It can be used in three ways. a. For setting the value of an edit box Syntax: Object Hierarchy. SET Value Ex: Dialog (Login).WinEdit(Agent Name).Set asdf b. Selecting a Radio Button Syntax: Object Hierarchy. Set Ex: Window("Flight Reservation").WinRadioButton("Business").Set c. Selecting/Deselecting check boxes Syntax:object Hierarchy.Set ON/off Ex: Window ("Flight Reservation"). Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 6) Select Method: It is used for selecting an item from a combo box or list box. Syntax: Object hierarchy.select item Ex: Window("Flight Reservation").WinComboBox("Fly From:").Select "London" Window("Flight Reservation").Dialog("Flights Table").WinList("From").Select "12572 7) GetVisibletext: It returns Text from the specified area. Syntax: Variable =object hierarchy.getvisibletext Ex: x=Window("Flight Reservation").WinComboBox("Fly From:").GetVisibleText msgbox x 8) GetRoproperty: It returns current object property value. It can be used for getting any objects, any property value. Syntax: Variable = object hierarchy.getroproperty (property name) Ex: x=Window("Flight Reservation").WinEdit("Tickets:").GetROProperty ("width") msgbox x 9) Navigate Method: It opens a specified URL in the Browser. Syntax: object hierarchy.navigate URL Ex: Browser("Yahoo!").Navigate http://www.google.co.in/ 10) Getitemscount: It returns number of items in a combobox.

Syntax: Variable=object hierarchy.getitemscount Ex: x=Window("Flight Reservation").WinComboBox("Fly From:").GetItemsCount msgbox x 11) Getcontent: It returns all items from a combobox. Syntax: variable=object hierarchy.GetContent Ex: x=Window("Flight Reservation").WinComboBox("Fly From:").GetContent msgbox x 12) Exist property: It checks whether the object is available or not. Syntax: Object hierarchy.exist(time in seconds) Ex: Window("Flight Reservation").Exist(5)

Data Table Methods

QTP Data Table Methods

(1) Add Sheet: We can use this method to add one new sheet to the run time data table. Syntax: DataTable.AddSheet "sheet name" Ex: DataTable.AddSheet "gcreddy" (2) Delete Sheet: We can use this method to delete one specified sheet from the Run Time Data table. Syntax: datatable.DeleteSheet (Sheet_ID) Ex: datatable.DeleteSheet (3) (3) GetSheetCount We can use this method to count number of sheets in the run time data table. Syntax: datatable.GetSheetCount msgbox datatable.GetSheetCount (4) GetRowCount

We can use this method to count number of rows in the 1st sheet (longest column) of the Run time data table. Syntax: datatable.GetRowCount Ex: msgbox datatable.GetRowCount (5) GetSheet We can use this method to return a specified sheet from the Run Time data table. Syntax: datatable.GetSheet(SheetID) Ex: msgbox datatable. GetSheet(1).GetRowCount (6) Value We can use this method to set or get value of cell in the specified parameter and the current row of the Rum time data table. To set data Syntax: datatable.Value(Parameter_Name, Sheet_Name) = Value / variable Or datatable(Parameter_Name, Sheet_Name) = Value / variable To get data Syntax: Variable = datatable.Value(Parameter_Name, Sheet_Name) Or Variable = datatable(Parameter_Name, Sheet_Name) Ex:

Option explicit Dim a, b, c a=datatable.Value (1,1) b=datatable.Value (2,1) c=cint(a)+cint(b) datatable.Value (3,1) = c Note: Default property of Datatable is value (7) SetCurrentRow We can use this method to take a specified row as current row in the Run Time Datatable (By default it is 1st Row of 1st Sheet) Syntax: datatable.SetCurrentRow(Row_Number) g="gcreddy" datatable.SetCurrentRow (3) datatable.Value (1,1) = g (8) SetNextRow We can use this method to take the row after the current Row as New Current Row in the Run time data table. Syntax: datatable.SetNextRow Ex: g="gcreddy" datatable.SetCurrentRow (3) datatable.SetNextRow datatable.Value (1,1) =g (9) SetPrevRow We can use this method to take the row before the current Row as New Current Row in the Run time data table. Syntax: datatable.SetPrevRow Ex: g="gcreddy"

datatable.SetCurrentRow (3) datatable.SetPrevRow datatable.Value (1,1) =s (10) Import We can use this method to import Microsoft Excel File to the Runtime Data Table(Including all sheets) Syntax: datatable.Import Path of File Ex: datatable.Import F:\Inputdata.xls 11) ImportSheet We can use this method to import a specified sheet of Microsoft Excel Sheet to the Runtime Data table. Syntax: datatable.ImportSheet Path of File, Source Sheet, DestinationSheet Ex: datatable.ImportSheet E:\gcreddy.xls,3,1 (12) Export We can use this method to export a copy of Run Time Data table to another location (Including all sheets) Syntax: datatable.Export Path of File Ex: datatable.Export F:\gcreddy.xls 13) ExportSheet We can use this method to export a copy specified sheet of Run Time Data tableto the existing or new Excel File. Syntax: datatable.ExportSheet Path of File, Sheet Name / Source Sheet

Ex: datatable.ExportSheet F:\gcreddy.xls, 2 ********************** Data Driven Testing for Login Operation using Data Table methods Datatable.AddSheet "Login" Datatable.ImportSheet "C:\Documents andSettings\gcr\Desktop\gcreddy.xls",1,3 Rows_count=Datatable.GetSheet(3).GetRowCount For i= 1 to Rows_count Datatable.SetCurrentRow(i) SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set Datatable("Agent",3) Dialog("Login").WinEdit("Password:").Set Datatable("Pwd",3) Dialog("Login").WinButton("OK").Click If window("Flight Reservation").exist(10) Then Login="Login Operation Successful" Datatable("Result",3)=Login Reporter.ReportEvent micPass,"res","Passed" else Reporter.ReportEvent micFail,"res","Failed" Login="Login Operation Failed" Datatable("Result",3)=Login Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click Dialog("Login").WinButton("Cancel").Click End If If Window("Flight Reservation").Exist(3)Then Window("Flight Reservation").Close End if Next

Descriptive Programming

Descriptive Programming
Entering / Providing objects information directly into the test script is called Descriptive Programming.

In this method of script creation, we no need to have Object Repositories. Advantages: a) Descriptive Programming based Test scripts are faster in execution than Repository based Test scripts. b) Scripts are portable (we can run these scripts from any machine easily) c) Maintenance is easy (less amount of resources) d) We can start Test Execution process even though Application is not ready. Descriptive programming is basically 2 types. 1. Static Programming 2. Dynamic Programming

Static Programming
In this style of script generation, we provide objects information directly into the script. Example: 1) Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" 2) dialog("text:=Login").Activate 3) dialog("text:=Login").Winedit("attached text:=Agent Name:").Set "gcreddy" 4) dialog("text:=Login").Winedit("attached text:=Password:").Set "mercury" 5) dialog("text:=Login").Winbutton("text:=OK","width:=60").Click Note: 1. Dialog, WinEdit and WinButton Test Objects 2. text, attached text - Property names 3. Login, Agent Name:, Password:, OK - Property values or Logical Names of the Object 4. Activate, Set, Setsecure, Click - Methods Note2:

If we feel one property information is not sufficient for recognizing the object uniquely, then we can provide more properties information by separating with commas. Note 3: If we want to get objects information (Test objects, properties and values), we can use object spy feature. This feature is available in Tools Menu, in local repository and in repository manager. Example 2: SystemUtil.Run "C:\Program Files\Internet Explorer\IEXPLORE.EXE","","C:\Program Files\Internet Explorer","open" Browser("title:=Google").Page("title:=Google").Sync Browser("title:=Google").Navigate "http://www.icicibank.com/"

------------------------------------------------------------------If we want maintain Objects information in centralized location then we can use Constants. Steps: Creating Constants: Const Login="text:=Login", Agent="attached text:=Agent Name:" Const Pwd ="attached text:=Password:", Ok="text:=OK" Note: we can declare no of Constants in a line by separating with Camas (,), if we take other line then we have to use Const Statement again. Creating a Library file Place Constants in Notepad and save as .vbs file Associate the Library file to QTP (File->Settings->Resources-> Click add (+) icon-> Browse path of the Library file->Click Apply and click Ok buttons Otherwise, we can load the library file during run-time Syntax: ExecuteFile Path of the Library file(.vbs)

After that create the Test Script using Constants Creating the Test Script using Constants: Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog(Login).Activate Dialog(Login).Winedit(Agent).Set "asdf" Dialog(Login).Winedit(Pwd").Set "mercury" Dialog(Login).Winbutton(Ok).Click Advantages: If we maintain Object Information in the centralized location, then we can handle modifications easily. -------------------------------------------------------------------

Dynamic Programming
In this style of script generation, first we create description objects, provide properties information and use description objects in the test script. Creating Properties Collection Objects Set Set Set Set oLogin=description.Create oAgent=description.Create oPassword=description.Create oOk=description.Create

Entering Properties Information into Objects oLogin("text").value="Login" oLogin("width").value=320 oLogin("height").value=204 oAgent("attached text").value="Agent Name:" oPassword("attached text").value="Password:" oOk("text").value="OK" Generating Tests using Properties collection Objects Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog(oLogin).Activate

Dialog(oLogin).Winedit(oAgent).Set "gcreddy" Dialog(oLogin).Winedit(oPassword).Set "mercury" Dialog(oLogin).Winbutton(oOK).Click Note1: Create Description objects and put into one library file, by associating that library file, we can generate tests. Note2: Dynamic programming is some difficult in preparation than static programming but maintenance is very easy. ------------------------------------------------------

Examples:
Handling similar/Duplicate Objects using Index Property SystemUtil.Run "C:\Program Files\Internet Explorer\IEXPLORE.EXE" Browser("name:=Google").Page("title:=Google").Sync Browser("name:=Google").Navigate http://www.jjperfumes.com/ Browser("name:=JJ Perfumes-Discount perfume cheap brand name perfumes,fragrance & cologne online").page("title:=JJ Perfumes-Discount perfume cheap brand name perfumes, fragrance & cologne online").Link("innertext:=Register","index:=0").Click

Inserting Checkpoints

Inserting Checkpoints
Check point is a verification point, it takes expected result from the user and compares with actual results during execution and provides test results.

There are 11 Checkpoints available in QTP:


1. 2. 3. 4. 5. 6. 7. 8. 9. Standard check point Text check point Text area check point Bit map check point Data base check point Accessibility check point XML Check point (from Application) XML Check point (from Resource) Page check point 10. Image checkpoint 11. Table checkpoint

Note 1: From 6 to 11 checkpoints are only for Web. Note 2: From 9 to 11 checkpoints are hidden checkpoints, we can insert thesecheckpoints through standard checkpoint.

1. Standard Checkpoint:
It checks object property values. We can use this checkpoint for checking anyproperty value. Navigation for Inserting standard checkpoint Keep tool under recording mode > place cursor in desired location > Insert > check point > Standard checkpoint > Show the object > click okay > select property and enter expected results & click Ok and stop Recording. Navigation for Editing standard checkpoint Select Checkpoint statement and right click > choose checkpoint properties option > modify the value > click Ok. Navigation for Deleting standard checkpoint: Select Checkpoint statements and right click > choose delete option. Inserting Standard check points through active screen: View > Active Screen >place cursor in desired location >Place mouse pointer on active screen & right click> choose insert standard checkpoint option > click ok > enter expected result > click ok Note: Inserting Standard check points through keyword view same as in expert view. Note: We can insert standard checkpoints in 3 ways.

a. Through expert view, b. Through keyword view, c. Through Active screen. 2) Text Checkpoint:
It Checks objects text property value in different ways. Navigation: Keep tool under Recording mode >Insert menu > checkpoint > Text checkpoint > Show the object > click ok > Select options

(Match case; ignore spaces, exact match, text not displayed.) We can select one or more options > click ok & stop Recording.

3) Text Area Checkpoint:


It checks the text area present in the application. Navigation: Keep tool under Recording mode > Insert menu> Checkpoint > Text area checkpoint > Mark the area of text > select one or more options (Match case, ignore spaces, exact match, text not displayed.) Click ok and stop recording.

4. Bitmap checkpoint:
It compares bitmaps; we can compare complete bitmaps as well as part of the bitmaps. Navigation: Keep tool under Recording mode > Insert menu > Checkpoint > Bitmap checkpoint > show the Bitmap >click ok >select check only selected area option if we want to compare part of the bitmap > click ok >stop recording.

5. Database checkpoint:
It checks Content of the back end Database. Navigation: Insert > checkpoint > Database checkpoint >choose specify SQL statement manually option >click next > click create > select machine data source > Select DSN (QT_flight32) > click ok > enter SQL statement (select * from orders) > finish > click ok. Note: here we do not need to put tool under Recording mode and we do not need AUT since data is from backend.

6. Accessibility check point:


It checks whether the webpage in our web application is developed according to W3C (World Wide Web consortium) Rules and Regulations or not. It is a configurable checkpoint, according to our requirements, we can customize. Configuring accessibility checkpoint:

Tools menu> options >web > advanced > check/uncheck items > click apply > click ok Invigilation: Keep tool under recording mode with web environment >insert>checkpoint>accessibility checkpoint>show the webpage>click ok>click ok>stop recording. Result Criteria: a) If item is available but not according to W3C rules then fail. b) If an item is available, according to W3C rules then Pass. c) If an item is not available then result would be pass

7. XML Check point (from Application)


It checks content of the XML file. Navigation: Keep tool under Recording mode in web environment > insert menu > checkpoint (fromapplication)> show the xml pages >click ok > stop Recording.

8. XML Check point (from Resource)


It checks content of the XML file. Navigation: Insert menu > checkpoint >xml checkpoint (from resource) > browse path of the XML File > click ok > click ok. Note: 1. If XML file is an individual and path available, and then we can go for inserting xml checkpoint from resource. Note: 2. If XML file is part of web application, separate path is not available then we can choose inserting XML checkpoints from application.

9. Page checkpoint:
It checks number of Links, Images and Loading time in a web page. It is a hidden checkpoint; we can insert this through standard checkpoint. Navigation: Keep tool under Recording mode with web environment > Insert menu > checkpoint > Standard checkpoint >show the web page > click ok > click ok > stop recording.

10. Image checkpoint:


It checks Image property values.

Navigation: Keep tool under Recording mode with web environment > Insert menu > checkpoint >standard checkpoint > show the image > select image > click ok > click ok >stop recording.

11. Table checkpoint:


It checks content of the web tables. Navigation: Keep tool under Recording mode under web environment > Insert menu > checkpoint > standard checkpoint >show the web table > click ok >stop recording.

Inserting Output Values


It is a step in which one or more values are captured during test execution. The values can later be used as input at a different point in the run session or we can use as input for another test. It is stored in run time data table; it is located in QTP result window and can be retrieved later.

Types of Output Values:


1. 2. 3. 4. 5. 6. Standard output value Text output value Text area output value Database output value XML output value (From Application) XML output value (From Resource)

1) Standard output value:


We can use standard output values to output the properties values of most objects. Navigation: Keep tool under Recording mode > Insert menu >output value> standard output value > show the object > click ok > select property > modify the column name (if required) > click ok >click ok >stop recording.

2) Text output value:


We can use Text output values to output text strings displayed in an application. When creating a text output value we can output a part of the objects text and we can also specify text before and after options. Navigation: Keep tool under recording mode> Insert menu> output value > text output value > show the text >select one of the option(output text/text before/text after) > click modify if you want to change the column name > click ok > click ok.> check in runtime table after running it.

3) Text Area output value:


We can use text area output values to output text strings displayed within a definedarea of the screen. Navigation: Keep tool under recording mode > insert menu >output value > text area output value >Mark the text area >click modify the column name if necessary > click ok > again click ok > check in run time table after running it..

4) Database output value:


We can use Database output values to output the value of the contents of database cells. Navigation: Insert menu> output value > Database output value> choose specify SQL statementsmanually >click next >click create >Select Machine Data source > Select Driver(QT_flight32) > click ok > enter SQL statement (select *from orders) > click finish > select data cells > click ok > Run and it will capture and see the results in run time table.

5) XML output value (from application):


we can use XML output values to output the values of XML elements in XMLdocuments.

Navigation: Keep tool under recording mode with web environment > Insert menu > output value > XML output value from application > Show the XML document > select elements > click ok >stop recording.

6) XML output Value (From Resource):


We can use XML output values to output the values of XMLdocuments. Navigation: Insert menu >output value> XML output value from resource > browse path of the XML file > click ok > select elements >click ok. XML elements in

Parameterization

Passing parameters, through this we can pass multiple values. We use parameterization in Data Driven Testing. Data Driven Testing: Testing the Same operation with multiple sets of test data. Types of Parameterization: We can parameterize tests in several ways in QTP 1. Through Loop Statements 2. Dynamic Test Data Submission 3. Through Data Table 4. Fetching Test Data directly from External files (Flat files & Spreadsheets) 5. Fetching Test Data directly from Databases (MSAcess, Oracle etc). 6. Getting Test Data from front end objects. 1. Through Loop Statements: We can use loop statements for passing sequential numbers & Logical Numbers. Note: We cant generate Strings. For orderno=1 to 10 step 1 ' for one increment step keyword is not mandatory Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("Button").Click Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"

Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set orderno Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click Next 2.Dynamic Test Data Submission: Through Loop Statements we can give strings also but every time user has to enter data. For x=1 to 3 Agent =inputbox("enter an Agent Name") Password=inputbox("enter a password") invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set Agent Dialog("Login").WinEdit("Agent Name:").Type micTab Dialog("Login").WinEdit("Password:").SetSecure password Dialog("Login").WinButton("OK").Click Window("Flight Reservation").Close Next 3. Through Data Table: QTP adds one data table (Spreadsheet) for every test, we can use Data Table for Data Driven Testing. It has 3 types of usage . a. Entering test data directly into data table and use b. Importing test data from external Flat files c. Importing test data from external Spread sheets d. Importing test data from Data bases. a. Entering test data directly into data table and use. Steps: i) Generate the basic test>open data table(View>Data Table) ii) Click on column header>enter the name of the field (like this we can create number of columns) > Enter Data>connect the data to test

(variable=datatable(column name, Sheet id) Example: agent=datatable(agent,1) Pass parameters.) iii) Run the test. Example: Agent = Datatable("Agent",1) pwd=Datatable ("Password",1) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set Agent Dialog("Login").WinEdit("Agent Name:").Type micTab Dialog("Login").WinEdit("Password:").SetSecure pwd Dialog("Login").WinButton("OK").Click Window("Flight Reservation").Close b. Importing test data from external files: Open Data Table (view>Data table)>place mouse pointer on data table and right click>file>import from file>Click ok>Browsw path of the file(it imports data from the flat file) Connecting Test Data to QTP Test as above and run the test. c. Importing test data from external Spread sheets: Open Data Table (view>Data table)>place mouse pointer on data table and right click>file>import from file>Click ok>Browse path of the excel sheet (it imports data from the excel sheet) Connecting Test Data to QTP Test as above and run the test. d. Importing test data from Data bases:

Through Data table we can import Test Data from Data bases, but first we have to create /get the DSN(Data source Name)& we have to use SQL Commands. i). Creating a Test Database: open MS Access (or we can use any other database). ii) Start programs>MS Office>MS Access>file >new>Select blank Database>enter name of the database>Save with mdb extension. iii) Creating Tables: Select Create table in design view>Enter field name(Agent)and Select data type(text) Like this we can create number of fields>save&enter table name. iv) Entering Data into Tables: Select table>enter the data. v) Creating DSN & importing data Navigation: view>data table>Place mouse pointer on Data table>sheet>import>from database(Database query wizard opens)>choose specify SQL statements manually>click next >click create>click new>select driver type>click next >browse path to store> enter DSN Name>Click Save>click next>click finish>select>browse the database& select>click ok>click ok>select DSN>click ok>enter SQL statement (select *from login)>click finish. Note: DSN Creation is one time activity, by using the DSN we can get data for number of tests. 4. Fetching Test Data directly from Flat files Dim fso, myfile Set fso=createobject("scripting.filesystemobject") Set myfile=fso.opentextfile("d:\trigun.txt",1) myfile.skipline While myfile.atendofline <> true x=myfile.readline S=split(x,"@")

SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set s(0) Dialog("Login").WinEdit("Agent Name:").Type micTab Dialog("Login").WinEdit("Password:").SetSecure S(1) Dialog("Login").WinEdit("Password:").Type micReturn Window("Flight Reservation").Close Wend Fetching Test Data directly from Excel Sheets Fetching Test Data directly from Databases Option explicit Dim con,rs Set con=createobject("adodb.connection") Set rs=createobject("adodb.recordset") con.provider=("microsoft.jet.oledb.4.0") con.open "C:\Documents and Settings\pooja\My Documents\trigun.mdb" rs.open "select * from login",con do until rs.eof=true SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set rs.fields ("agent") Dialog("Login").WinEdit("Agent Name:").Type micTab Dialog("Login").WinEdit("Password:").SetSecure rs.fields("password") Dialog("Login").WinEdit("Password:").Type micReturn Window("Flight Reservation").Close rs.movenext loop -------------------------------------Using Dictionary Object for Parameterization Set inputdata=CreateObject("Scripting.Dictionary") inputdata.Add "Agent","gcreddy"

inputdata.Add "Password","mercury" SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set inputdata("Agent") Dialog("Login").WinEdit("Password:").Set inputdata("Password") Dialog("Login").WinButton("OK").Click

Synchronization

It is a process of matching the speeds of both QTP and AUT in order to get proper execution and results. Where Synchronization is required: During test execution QTP gives instructions one by one with same speed, but AUT takes less time for some operations execution and more time for some operations execution, that time we may not get proper execution and results. In order to get proper results inbetween QTP & AUT synchronization is required. There are several methods available in QTP for synchronization. 1. 2. 3. 4. 5. Inserting Wait statements. Inserting Synchronization points. Increasing Tool default synchronization time. Sync Method (Only for WEB) Exist Property

Inserting Wait Statements: We can insert wait statements in our test in order to make QTP to wait until AUT completes current operation. Syntax: Wait(time in seconds) Note: If we insert wait statements QTP waits up to maximum time even though operation is completed. Inserting Synchronization points: Place cursor in desired location>keep tool under recording mode>Insert menu>Synchronization point >show the object >click ok>select property name & Value(True)>enter time in Milli seconds>click ok>Stop recording.

Note: if we insert Synchronization points, it does not wait up to maximum time, after completion of the current operations, it goes to next step immediately. Syntax: object hierarchy.waitproperty property name,value,time in milli seconds. Increasing Tool default synchronization time: Navigation: File>settings>run tab>increase object synchronization time out>apply>ok Note: If we increase QTP tool default time that can be applied for all statements in the test, but QTP does not wait up to maximum time unnecessarily, After completion of one statement execution it goes to next statement immediately. Sync Method: (only for WEB) Waits for the browser to complete current navigation. Syntax: Object Hirearchy.Sync Ex: Browser("Yahoo! Toolbar").Page("Yahoo! Toolbar").Sync Selecting an appropriate Method: 1. Suppose in our test one or more statements only are taking more time for execution then selecting Inserting synchronization method is better. 2. Suppose in our test more statements are taking more time for execution then selecting increasing tool time out . 3. Above two are local features but wait statement is Vbscript feature, even though some drawbacks are there in using wait statement, it is better to use wait statement in functions.
Advantages of Wait Statement: 1) It is a VBScript statement, we can use this globally 2) It is recommended, whenever we want to observe the Test Execution process 3) No object reference required to insert wait statements

4) It is useful to make QTP capture values and screen shots during test execution

Inserting Transaction Points


QTP is providing a Utility object called Services for measuring transaction time Suppose, we want to measure how much time that one test or part of the test is taking for execution/running, we can measure using these transaction point (Start and End) Syntax: Services.StartTransaction Transaction Name Statements -----------Services.EndTransaction Transaction Name Note: these options (Start and End Transactions) available in QTP tool Insert menu Example: services.StartTransaction "Login" SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "naga" Dialog("Login").WinEdit("Password:").SetSecure "4baf50f18b0ae0d5f5425fe760653e96da50bde7" Dialog("Login").WinButton("OK").Click Window("Flight Reservation").Activate services.EndTransaction "Login" Note: We can insert number of transaction points in a test

Using Timer Function Timer is a VB Script Built-in function, that can be used for measuring transaction time.
ST=Timer It returns elapsed time since 12:00 AM Mid night in seconds Example: SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "naga" Dialog("Login").WinEdit("Password:").SetSecure "4baf50f18b0ae0d5f5425fe760653e96da50bde7"

Dialog("Login").WinButton("OK").Click Window("Flight Reservation").Activate ET=Timer TT=ET-ST msgbox TT

Note: ST for ET for TT for

here ST, ET and TT are variables, you can take any variable, I used: Start Transaction End transaction Transaction Time

Step Generator (F7)


Step Generator is a feature of QTP, Library of Functions, used for generating the Recordable and Non-Recordable steps. Navigation: Insert menu->Step Generator Or Use Shortcut key F7 The Step Generator enables us to add steps by selecting from a range of context-sensitive options and entering the required values. In the Step Generatordialog box we can define steps that use: Test object operations (tests only) Utility object operations Calls to library functions (tests only), VBScript functions, and internal script functions For example, we can add a step that checks that an object exists, or that stores the returned value of a method as an output value or as part of a conditionalstatement. We can parameterize any of the values in our step. Note: we can use the Step Generator to insert steps in tests and function libraries. Hover, in function libraries, we cannot use the Step Generator to access test object names or collections, or to access the list of library functions. Before we open the Step Generator to define a new step, we first select where inour test the new step should be inserted.

After we open the Step Generator, we first select the category for the step operation (test object, Utility object or function) and the required object or the function library. We can then select the appropriate operation (method, property, or function) and define the arguments and return values, parameterizing them if required. The Step Generator then inserts a step with the correct syntax into y test. We can continue to add further steps at the same location without closing the StepGenerator. We can open the Step Generator from the Keyword View, Expert View, or Active Screen.

Debugging Tests
Debugging is a process of executing the script or a program in a User designed fashion with some temporary break points in order to identify the errors. For debugging, QTP is providing debug commands and breakpoints. Debug Commands:

1) Step Into (short cut key F11):


a. It starts execution

b. It executes one statement at a time. c. If it is function call, it opens the function, after that it executes
one statement at a time.

2) Step Over (Short cut key F10):

a) It executes one statement at a time after execution starts b) It executes all functions statements at a time Note: After opening the function, if we use step over it executes one statement at a time only.

3) Step Out (shift +F11):

It executes all remaining statements in a function at a time. Ex: Dim a,b,c a=100 b=200 c=a+b msgbox c msgbox "hello" Call hyderabad msgbox "bye bye" Note: Create a script and work on it

Break Point:
This feature is used for breaking the execution temporarily. Navigation: Place cursor in desired location >Debug menu>Insert/Remove break point Or Use short cut key (F9) Or Place mouse pointer before the statement and click. Note: If we want to execute Some part of the Test Script at a time and some other part of the test script step by step, there we can use breakpoints.

Debug viewer Pane:


It is used for viewing, modifying or setting the value of the variables during the execution break with the help of 3 Tabs. 1. Watch 2. Variables 3. Command

Note: Through Debug Viewer Pane, We can watch variables whether the variables aretaking correct values or not at a specific point of time. We can change Values of Variables temporarily. Ex : Dim x,y,z x=10 y=20 z=x+y msgbox z msgbox "Hello" x=35 y=67 z=x*y msgbox z msgbox "bye bye" Navigation: View menu > Debug Viewer > Use step into feature.

Analyzing Test Results & Reporting


Analyzing the Test Result is not a responsibility of QTP. After Running Tests, User (Test Engineer) has to analyze the test result. and send defect reports. QTP Result Window: After Running/Executing a test, then QTP Provide result window. we export test result from result window in Document (.Doc), HTML, XML and PDF formats. Note: QTP doen't provide batch wise test result, if we execute test batches. It provides test wise result only. Status of the Result: QTP has 4 types of result status a) Pass b) Fail c) Done d) Warning

Defining our own Result: Generally QTP provides, test results, if we use qtp tool features like checkpoints. suppose if we use flow control statements (conditional and Loop statements), then we have to define our own result. For defining our own results, QTP is providing an utility object called "Reporter" by using reporter, we can define our own results. Syntax: Reporter.ReportEvent status of the Result,"Result Step","message" Example" Reporter.ReportEvent micPass,"Res","Login operation Successful" exaplanation: Reporter- Utility object ReportEvent-Method micPass-Status of the Result. Res-Result step "Login operation Successful"- Message Status of the Result: 1) Pass -micPass or 0 2) Fail -micPass or 1 3) Done- micDone or 2 4) Warning- micDone or 3

Reporting Defects

QTP is an Object based Test tool. We can create and execute tests using QTP. QTP Provides, various methods for crating and enhancing Tests. After Running Tests, QTP provides result in Result window and also provides a facility to define our own Results. Result Exporting facility also available in QTP Result window. Any how Analyzing Results is the Responsibility of Test Engineer after running tests.

After analyzing results, we can report defects in various methods. If we are using QTP for Functional Test Automation and Defect managementmanual, then entering defect details in company prescribed format and sending. If we are using Bugzilla or Zera or PR-Tracker like Bug Tracking tool, then after analyzing results, if we find any mismatches sending defects through the Bug tracking tool (Every Bug Tracking tool has its own defect report template) If we are using Quality center for Test management, then we can send defects directly from QTP result window. In between QTP and Quality Center back to back integration is available.

Actions
Action: Set of Statements for perfoming a Task(s) We divide our test into actions to streamline the process of testing. Purpose of Actions: For understandability For reusing components Types of Actions: 1) Non Re usable actions 2) Re usable actions 3) External actions Operations on Actions: Creating Actions Splitting Actions Renaming Actions Deleting Actions Calling an Action Copying an Action

Making an Action Reusable/Non Reusable Creating an Action: Insert>call to new action>enter name of the action>click ok Steps: 1. Create required actions(ex login, insert,delte) 2. Prepare Scripts for those actions. Splitting an action: Navigation: Place cursor in desired location>Edit menu>action>split action>Enter Action 1 name & action 2 name. Steps: 1. Generate total test in the default action 2. Split into meaningful actions. Note: At a time we can split one actions into 2 actions. Renaming actions: Select desired action in action drop down box> edit menu>action>rename action>modify the name>click ok. Deleting Actions: Select desired action in action drop down box>edit menu>action>delete action>confirm deletion. Calling an action: Insert>call to existing action>browse path of the test>select desired action>click ok. Note: U cant edit Copying an action: Insert>call to copy of action>browse path of the test>select desired action>click ok. Note: we can edit this action. Making an action reusable: Select Non Reusable action >edit >action>action properties>check reusable action check box >click ok.

VB Script String Functions


1) Left Function

String Functions

Returns a specified number of charectors of a given string from left side Syntax: variable=Left(string,Lengh) Example: Dim val,x val="Hyderabad" x=Left(val,3) msgbox x ' Output: Hyd val="9247837478" x=Left(val,1) msgbox x ' Output: 9 val="H92yderabad" x=Left(val,3) msgbox x ' Output: H92 x=Left(9247837478,5) msgbox x ' Output: 92478 val=#10-10-10# x=Left(val,3) msgbox x ' Output: 10/ 2) Right Function Returns a specified number of charectors of a given string from Right side Example: Dim val,x val="Hyderabad" x=Right(val,3) msgbox x ' Output: bad

val="9247837478" x=Right(val,1) msgbox x ' Output: 8 val="H92yderabad" x=Right(val,3) msgbox x ' Output: bad x=Right(9247837478,5) msgbox x ' Output: 37478 val=#10-10-10# x=Right(val,5) msgbox x ' Output: /2010 3) Mid function Returns a specified number of charectors of a given string Example: Dim val,x val="Hyderabad" x=Mid(Val,5,3) msgbox x ' Output: rab val="Hyderabad" x=Mid(Val,5) msgbox x ' Output: rabad val="9247837478" x=Mid(val,6,5) msgbox x ' Output: 37478 val="H92yderabad" x=Mid(val,1) msgbox x ' Output: H92yderabad x=Mid(9247837478,5) msgbox x ' Output: 837478

val=#10-10-10# x=Mid(val,5) msgbox x ' Output: 0/2010 4) StrReverse retuns reverse value of a string Example: Dim val,x val="Hyderabad" x=StrReverse(val) msgbox x 'Output dabaredyH val="001" x=StrReverse(val) msgbox x 'Output: 100 val=1002 x=StrReverse(val) msgbox x 'Output: 2001 val=#10-10-10# x=StrReverse(val) msgbox x 'Output: 0102/01/01 x=StrReverse("Hyderabad") msgbox x 'Output: dabaredyH x=StrReverse(100) msgbox x 'Output: 001 5) StrComp Function It compares two string (Binary and textual) if a) Both are equal, returns 0(zero) b) String 1 greater than string 2, returns 1(one)

b) String 2 greater than string 1, returns -1 Example: Dim str1,str2,x str1="India" str2="India" x=StrComp(str1,str2,1) msgbox x 'Output 0 str1="india" str2="INDIA" x=StrComp(str1,str2,1) msgbox x 'Output 0 str1="India" str2="Indian" x=StrComp(str1,str2,1) msgbox x 'Output -1 str1="Indian" str2="Ndia" x=StrComp(str1,str2,1) msgbox x 'Output -1 str1="Indian" str2="India" x=StrComp(str1,str2,1) msgbox x 'Output 1 str1=100 str2=100 x=StrComp(str1,str2,1) msgbox x 'Output 0 str1=100 str2=101 x=StrComp(str1,str2,1) msgbox x 'Output -1 6) Lcase function Coverts Upper case values into Lower case

Dim val,x val="HYDERABAD" x=Lcase(val) msgbox x 'Output hyderabad val="Hyderabad" x=Lcase(val) msgbox x 'Output hyderabad val="HederabaD" x=Lcase(val) msgbox x 'Output hyderabad val="hyderabad" x=Lcase(val) msgbox x 'Output hyderabad x=Lcase("HYDERABAD") msgbox x 'Output hyderabad 7) Ucase function Coverts Lower case values into Upper case Example: Dim val,x val="HYDERABAD" x=Ucase(val) msgbox x 'Output HYDERABAD val="Hyderabad" x=Ucase(val) msgbox x 'Output HYDERABAD val="HederabaD" x=Ucase(val) msgbox x 'Output HYDERABAD val="hyderabad" x=Ucase(val) msgbox x 'Output HYDERABAD

x=Ucase("HYDERABAD") msgbox x 'Output HYDERABAD 8) LBound, UBound Functions


Example: Dim x(3), y(4,5) Msgbox Lbound(x) '0 Msgbox UBound(x)'3 'Find size of the Array Msgbox UBound(x)+1 Msgbox Lbound(y,1) '0 Msgbox Lbound(y,2) '0 Msgbox UBound(y,1) '4 Msgbox UBound(y,2) '5

Environment Variables in QTP


These are global variables; if you want to use some variables globally (Fromnumber of tests) declaring as global variables is better. If we declare as local variables in number of tests, modifications are difficult. Types of Environment variables:

1. Built in variables: These are system defined variables, we can access from all tests but these are designed as read only. 2. User defined variables: Variables that we predefine in the active external environment variables file. We can create as many files as we want and we can change values of variables. Usage of environment variables: Syntax: Variable = Environment(environment variable name) Ex: X=Environment (ActionName) Msgbox x Example Script: ProductDir =environment ("ProductDir") app= "\samples\flight\app\flight4a.exe" Systemutil.Run ProductDir & app Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "kajal" Dialog("Login").WinEdit("Password:").SetSecure "4b3c86f2107ff565cc195ba6c24739091b656407" Dialog("Login").WinButton("OK").Click Creating user defined environment variables: Navigation: File > settings > Environment > select variable type as user defined > click addicon (+) > enter variable name & Value > click ok (like this we can create numberof variables) > click export > browse path & enter file name, save with xml extension > click ok. Associating environment variable file: Navigation: File > settings >Environment > select variable type as user defined > check load variables and values from the external file > browse path of the xml file > click apply & ok.

Or We can load environment file directly Environment.loadfromfilepath of the xml file Usage of user defined Environment variables: Associate environment file to current test: Variable = Environment (Variable Name) X=environment (city) Msgbox x Modifying Environment files: Select XML file>open with notepad>modify the values>Save.

Regular Expressions in QTP


What is Regular Expression? It is a way of representing data using symbols. They are often used within matching, searching or replacing algorithms. Regular Expressions in QTP: Regular expressions can be used in QTP for identifying objects and text strings with varying values. Where we use: o Defining the property values of an object in Descriptive programming for handling dynamic objects o For parameterizing a step o creating checkpoints with varying values Using Regular Expressions in QTP: We can define a regular expression for a constant value, a Data Table parameter value, an Environment parameter value, or a property value in Descriptive programming.

We can define a regular expression in standard checkpoint to verify the property values of an object; we can set the expected value of an object's property as aregular expression so that an object with a varying value can be verified. We can define the text string as a regular expression, when creating a text checkpoint to check that a varying text string is displayed on our application, For XML checkpoints we can set attribute or element values as regular expressions. Ways of Regular Expressions: a) Backslash Character: A backslash (\) can serve two purposes. It can be used in conjunction with a special character to indicate that the next character be treated as a literal character. Alternatively, if the backslash (\) is used in conjunction with some characters that would otherwise be treated as literal characters, such as the letters n, t, w, or d, the combination indicates a special character. b) Matching Any Single Character: A period (.) instructs QTP to search for any single character (except for \n). Ex: welcome. Matches welcomes, welcomed, or welcome followed by a space or any other single character. c) Matching Any Single Character in a List: Square brackets instruct QTP to search for any single character within a list of characters. Ex: To search for the date 1867, 1868, or 1869, enter: 186[789] d) Matching Any Single Character Not in a List:

When a caret (^) is the first character inside square brackets, it instructs QTP to match any character in the list except for the ones specified in the string. Example: [^ab] Matches any character except a or b. e) Matching Any Single Character within a Range: To match a single character within a range, we can use square brackets ([ ]) with the hyphen (-) character. Example: For matching any year in the 2010s, enter: 201[0-9] f) Matching Zero or More Specific Characters: An asterisk (*) instructs QTP to match zero or more occurrences of the preceding character. For example: ca*r Matches car, caaaaaar, and cr g) Matching One or More Specific Characters: A plus sign (+) instructs QTP to match one or more occurrences of the preceding character. For example: ca+r Matches car and caaaaaar, but not cr. h) Matching Zero or One Specific Character: A question mark (?) instructs QTP to match zero or one occurrences of the preceding character. For example: ca?r Matches car and cr, but nothing else. i) Grouping Regular Expressions:

Parentheses (()) instruct QTP to treat the contained sequence as a unit, just as in mathematics and programming languages. Using groups is especially useful for delimiting the argument(s) to an alternation operator ( | ) or a repetition operator ( * , + , ? , { } ). j) Matching One of Several Regular Expressions: A vertical line (|) instructs QTP to match one of a choice of expressions. k) Matching the Beginning of a Line: A caret (^) instructs QTP to match the expression only at the start of a line, or after a newline character. l) Matching the End of a Line: A dollar sign ($) instructs QTP to match the expression only at the end of a line, or before a newline character. m) Matching Any AlphaNumeric Character Including the Underscore: \w instructs QTP to match any alphanumeric character and the underscore (A-Z, a-z, 0-9, _). n) Matching Any Non-AlphaNumeric Character: \W instructs QTP to match any character other than alphanumeric characters and underscores. o) Combining Regular Expression Operators: We can combine regular expression operators in a single expression to achieve the exact search criteria we need. For example, start.* Matches start, started, starting, starter, and so forth. we can use a combination of brackets and an asterisk to limit the search to a combination of non-numeric characters. For example: [a-zA-Z]* To match any number between 0 and 1200, we need to match numbers with 1 digit, 2 digits, 3 digits, or 4 digits between 1000-1200.

The regular expression below matches any number between 0 and 1200. ([0-9]?[0-9]?[0-9]|1[01][0-9][0-9]|1200)

RegExp object
VB Script is providing RegExp object for defining Regular expressions, It provides simple support for defining regular expressions. Regular Expression Object Properties and Methods: Properties: a) Global Property b) IgnoreCase Property c) Pattern Property Methods: a) Execute Method b) Replace Method c) Test Method

Regular Expressions Examples:


1) Match File Names in a Directory against Regular Expression Set objFS = CreateObject("Scripting.FileSystemObject") Set objShell = CreateObject("WScript.Shell") strCurrentDirectory = objShell.CurrentDirectory Set objFolder = objFS.GetFolder(strCurrentDirectory) Set colFiles = objFolder.Files Set objRE = New RegExp objRE.Global = True objRE.IgnoreCase = False objRE.Pattern = WScript.Arguments(0) For Each objFile In colFiles

bMatch = objRE.Test(objFile.Name) If bMatch Then WScript.Echo objFile.Name End If Next 2) Match Content in a File against a Regular Expression strFileName = "E:\gcreddy.txt" Set objFS = CreateObject("Scripting.FileSystemObject") Set objTS = objFS.OpenTextFile(strFileName) strFileContents = objTS.ReadAll WScript.Echo "Searching Within: " WScript.Echo strFileContents objTS.Close Set objRE = New RegExp objRE.Global = True objRE.IgnoreCase = False objRE.Pattern = WScript.Arguments(0) Set colMatches = objRE.Execute(strFileContents) WScript.Echo vbNewLine & "Resulting Matches:" For Each objMatch In colMatches WScript.Echo "At position " & objMatch.FirstIndex & " matched " & objMatch.Value Next

Virtual Object Configuration


Virtual Object Configuration:
Virtual Object Configuration is a process of making the QTP to treat a specified area or a user defined object as Virtual Object. Virtual objects enable us to create and run tests on objects that are not normally recognized by QTP. We can manage the virtual objects defined on our computer using the Virtual Object Manager.

Navigation:

o o

Select Tools Menu Go to Virtual objects Select New Virtual Object option Click Next Mark the area in the Application with help of mark object button Click next Select one of the following options Entire Parent hierarchy Parent only Click on Next Specify the Desired object name Specify the Desired collection name Click finish

Virtual Object Manager: Virtual object Manager feature enable us to create and manage Virtual Objects

Batch Testing or Batch Execution


Executing a group of Tests or series of tests at a time is known as Batch Testing or Batch Execution. For performing Batch Testing, QTP is providing a separate Tool called Test Batch Runner. Steps for Batch Testing: 1). Create Individual Tests and Run once. 2). Open 'Test batch Runner' Tool and Form Batches. 3) Provide permission to 'Test batch Runner' to run tests 4). Run or Execute Test Batches from Test Batch Runner. 5) View Test wise Result in 'Test Result Viewer'. Note: QTP doesnt provide Batch wise result. Forming a Test Batch: Launch Test Batch Runner.

Navigation: Start>program>quicktest professional>Tools>Test Batch Runner>File>new>batch>add>browse path of the test (like this add number of tests)>save with MTB extension (Module test batche)>close test batch runner. Running or Executing a Test Batch Open Test Batch Runner Tool Navigation: File>open>browse path of the test batch>batch>run Note: Test Batch Runner launches QTP Tool, QTP runs Tests one by one. Note: Allowing other products to Run Tests. Navigation: Tools>Options>Run>check allow other mercury products>apply & Ok Executing partial Test Batch Open Test Batch Runner >open Test Batch>Select or deselect tests>run test batch. Recovery Scenario Manager To recover from unexpected events and errors that are occurred in the test environment during run session, we can use Recovery Scenario Manager. For good recovery, error must be known the occurrence is unknown. There are (4) Types of events such as: (i) Application Crash An open application fails during Test Run. Navigation: Resources Menu -> Recovery Scenario Manager- > Click New- > Click Next - > Select Application Crash as Trigger event->Next - >Select selected executable application->Next ->Select Recovery Operation [Keyboard, Mouse Operation,

Close Application Process, function Call, Restart, Microsoft Windows] ->Next - >If you want to check Add another operation else uncheck->Next - >Next - >Enter Scenario Name ->Next- >Select Option - >Finish - >Close - >Save the scenario in specified location with .qrs (qrs stands for QuickTest Recovery Scenario.) (ii) Popup Window. To handle unwanted popups. Navigation: Resources Menu ->Recovery Scenario Manager ->New - >Next - >Select Popup Window as Trigger event ->Next - >Click on Hand Icon - >Show unwanted window with Hand icon ->Next - >Next - >Select function call as Recovery Operation ->Next [Open Notepad - >Save empty file with .vbs extension] - >Browse the .vbs fie path ->Next - >Uncheck Add another Recovery Operation - >Next - > Select Post-Recovery Test Run Option [Repeat current step and continue, Proceed to Next step, Proceed to Next Action, Proceed to next test iteration, Restart current test run, Stop the Test Run] ->Next - >Enter Scenario Name ->Next - >Select Option - > Finish ->Save the scenario with .qrs ->Record required Recovery Operation [Click ok, Click Cancel] take the script into function ->Save the library file ->Click Run (iii) Test Run Error. A step in your test does not run successfully then Test Run Error can be raised. Navigation :

Resources Menu ->Recovery Scenario Manager - >New - >Next - >Select Testrunerror Window as Trigger event ->Next ->select any error o - >Next - >Next - >Select function call as Recovery Operation ->Next [Open Notepad - >Save empty file with .vbs extension] ->Browse the .vbs fie path ->Next - >Uncheck Add another Recovery Operation - >Next -> Select Post-Recovery Test Run Option [Repeat current step and continue, Proceed to Next step, Proceed to Next Action, Proceed to next test iteration, Restart current test Select Option ? Next ? Enter Scenario Name ? Next ? run, Stop the Test ? ? ? ? Run] ? ? Record required Recovery Operation [Click Save the scenario with .qrs ? Finish ? ? ? Click Run Save the library file ? ok, Click Cancel] take the script into ? function ? ? (iv) Object State. The property values of an object in your application match specified values. You can specify property values for each object in the hierarchy. Navigation: Resources Menu -> Recovery Scenario Manager -> New -> Next -> Select Object state Window as Trigger event -> Next -> Click on Hand Icon -> Show object with hand icon -> Next -> Next->select object property with value (enabled ,false)>click next -> Select function call as Recovery Operation -> Next [Open Notepad -> Save empty file with .vbs extension] -> Browse the .vbs fie path -> Next -> Uncheck Add another Recovery Operation -> Next -> Select Post-Recovery Test Run Option [Repeat current step and continue, Proceed to Next step, Proceed to Next Action, Proceed to next test iteration, Restart current test run, Stop the Test Run] -> Next-> Enter Scenario Name -> Next -> Select Option ->

Finish -> Save the scenario with .qrs -> Record required Recovery Operation [Click ok, Click Cancel] take the script into function -> Save the library file -> Click Run

File System Operations


File System: Its an operating system feature, it allows users to create, modify, view and delete; drives,folders and files VB Script is providing an object called scripting.filesystemobject and some methods for performing file systems operations File System Object Model: The File System Object (FSO) model provides an object-based tool for working with folders and files. It allows us to use the familiar object.method syntax with a rich set of properties, methods, and events to process folders and files. We can also employ the traditional Visual Basic statements and commands. The FSO model gives our application the ability to create, alter, move, and delete folders, or to determine if and where particular folders exist. It also enables us to get information about folders, such as their names and the date they were created or last modified. The FSO model makes processing files much easier as well. When processing files, our primary goal is to store data in an efficient, easy-toaccess format. We need to be able to create files, insert and change the data, and output (read) the data. Although we can store data in a database, doing so adds a significant amount of overhead to our application. We may not want to have such overhead, or our data access requirements may not call for the extra functionality associated with a full-featured database. In this case, storing our data in a text file or binary file is the most efficient solution. The FSO model, contained in the Scripting type library (Scrrun.dll), supports the creation and manipulation of text files through the TextStream object; however, the FSO model does not support binary

files. To manipulate binary files, use the FileOpen Function with the Binary keyword. Examples: 1) Create a folder Dim fso, strFolder strFolder="D:\Documents and Settings\gcreddy\Desktop\Dibyalok" Set fso=createobject("scripting.filesystemobject") fso.CreateFolder(strFolder)

2) Create a folder Dim fso, strFolder strFolder="D:\Documents and Settings\gcreddy\Desktop\Dibyalok" Set fso=createobject("scripting.filesystemobject") If fso.FolderExists(strFolder) Then msgbox "Folder already exists" else fso.CreateFolder(strFolder) End If 3) Data Driven Testing by fetching Test data directly from a Text file. '********************************************************* 'Test Requirement: Data Driven Testing by Fetching Test data directly from a Text file. 'Author: G C Reddy 'Date of Creation: 13-08-2010 'Pre-requisites: 'vinod.txt (Test Data) 'Test Flow: 'Creating an Automation Object in FileSystem class 'Opening the External Test Data file using the Object 'Read the Data & Split the Data 'Generating the Login Operation 'Pass Parameters '********************************************************

Dim objFso, myFile, myLine, myField Set objFso=CreateObject("Scripting.FileSystemObject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr.GCRC9A12FBD3D9\Desktop\vindod.txt",1) '1 for Read, 2-Write & 8-Append myFile.SkipLine Do Until myFile.AtEndOfStream myLine=myFile.ReadLine myField=Split(myLine,",") SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("text:=Login").Activate Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set myField(0) Dialog("text:=Login").WinEdit("attached text:=Password:").Set myField(1) wait 2 Dialog("text:=Login").WinButton("text:=OK").Click Window("text:=Flight Reservation").Close Loop myFile.Close Set objFso=Nothing for more Examples visit:

File System Scripts Flat File Scripts

Database connections
Database connection is a facility in computer science that allows client software to communicate with database server software, whether on the same machine or not.

SQL Server connection strings SQL ODBC connection strings Standard Security: "Driver={SQLServer};Server=Your_Server_Name;Database=Your_Database_Name;

Uid=Your_Username;Pwd=Your_Password;" Trusted connection: "Driver={SQLServer};Server=Your_Server_Name;Database=Your_Database_Name; Trusted_Connection=yes;" SQL OLE DB connection strings Standard Security: "Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;" Trusted connection: "Provider=SQLOLEDB;Data Source=Your_Server_Name;InitialCatalog=Your_Datab ase_Name;Integrated Security=SSPI;" SQL OleDbConnection .NET strings Standard Security: "Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;" Trusted connection: "Provider=SQLOLEDB;Data Source=Your_Server_Name;InitialCatalog=Your_Datab ase_Name;Integrated Security=SSPI;" SQL SqlConnection .NET strings Standard Security: 1. "Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;" < br>2. "Server=Your_Server_Name;Database=Your_Database_Name;UserID=Your_Usern ame;Password=Your_Password;Trusted_Connection=False" Trusted connection: 1. "Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=SSPI;" 2."Server=Your_Server_Name;Database=Your_Database_Name;Trusted_Connecti on=True;" MS Access connection strings MS Access ODBC connection strings Standard Security:

"Driver= {MicrosoftAccessDriver(*.mdb)};DBQ=C:\App1\Your_Database_Name.mdb;Uid=You r_Username;Pwd=Your_Password;" Workgroup: "Driver={Microsoft Access Driver (*.mdb)}; Dbq=C:\App1\Your_Database_Name.mdb; SystemDB=C:\App1\Your_Database_Name.mdw;" Exclusive "Driver={Microsoft Access Driver (*.mdb)}; DBQ=C:\App1\Your_Database_Name.mdb; Exclusive=1; Uid=Your_Username; Pwd=Your_Password;" MS Access OLE DB & OleDbConnection (.NET framework) connection strings Open connection to Access database: "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb; User Id=admin; Password=" Open connection to Access database using Workgroup (System database): "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.m db; Jet OLEDB:System Database=c:\App1\Your_System_Database_Name.mdw" Open connection to password protected Access database: "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb; Jet OLEDB:Database Password=Your_Password" Open connection to Access database located on a network share: "Provider=Microsoft.Jet.OLEDB.4.0; DataSource=\\Server_Name\Share_Name\Shar e_Path\Your_Database_Name.mdb" Open connection to Access database located on a remote server: "Provider=MS Remote; Remote Server=http://Your-Remote-Server-IP; Remote Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb"

MySQL connection strings MySQL ODBC connection strings Open connection to local MySQL database using MySQL ODBC 3.51 Driver "Provider=MSDASQL; DRIVER={MySQL ODBC 3.51Driver}; SERVER= localhost; DATABASE=Your_MySQL_Database; UID= Your_Username; PASSWORD=Your_Password; OPTION=3"

MySQL OLE DB & OleDbConnection (.NET framework) connection strings Open connection to MySQL database: "Provider=MySQLProv;Data Source=Your_MySQL_Database;User Id=Your_Username; Password=Your_Password;"

Oracle connection strings Oracle ODBC connection strings Open connection to Oracle database using ODBC "Driver= {Microsoft ODBCforOracle};Server=Your_Oracle_Server.world;Uid=Your_Username;Pwd=Your _Password;" Oracle OLE DB & OleDbConnection (.NET framework) connection strings Open connection to Oracle database with standard security: 1. "Provider=MSDAORA;Data Source= Your_Oracle_Database;UserId=Your_Username;Password=Your_Password;" 2. "Provider= OraOLEDB.Oracle;Your_Oracle_Database;UserId=Your_Username;Password=Your _Password;" Open trusted connection to Oracle database "Provider= OraOLEDB.Oracle;DataSource=Your_Oracle_Database;OSAuthent=1;"

AOM Scripting (Automation Object Model)


Object Model: An object model is a structural representation of software objects (classes) that comprise the implementation of a system or application. An object model defines a set of classes and interfaces, together with their properties, methods and events, and their relationships. We can use QTP Automation object Model to write scripts, that automate our QTP operations. QTP Automation object model provides objects, methods and properties that enable us to control QTP from another application. We can use Scripting languages or programming languages such as VBscript, Java script or VC++, .Net for automating QTP operations.

Example:

1) Write an AOM Script to launch QTP Tool, Execute Tests and to close the QTP Tool option explicit Dim qtApp Set qtApp=createobject ("Quicktest.Application") qtApp.Launch qtApp.visible=True qtApp.open "C:\Documents and Settings\admin\My Documents\login" qtApp.Test.Run qtApp.Test.Close qtApp.open "C:\Documents and Settings\admin\My Documents\open order" qtApp.Test.Run qtApp.Test.Close qtApp.quit Set qtApp=Nothing Note: AOM Script can be used in Automation framework as an Initialization script. '-----------------------------------------------------------------2) Write an AOM script to execute series of tests Dim objFso,objQtp,myFile,i,gcreddy Set objQtp = CreateObject("Quicktest.Application") objQtp.Visible = True objQtp.Launch Set objFso =CreateObject("Scripting.FileSystemObject") Set myFile = objFso.OpenTextFile("C:\Users\Chinni\Desktop\Test\gcreddy.txt") i =1 Do Until myFile.AtEndOfStream =True testurl = myFile.ReadLine objQtp.Open gcreddy objQtp.Test.Run objQtp.Test.Close i = i+1 Loop

objQtp.Quit Set objQtp = Nothing

Dynamic handling of object Repositories


Loading repositories during running, finding path of the repositories and removing repositories is called Dynamic Handling of Object Repositories. Using this feature we can increase QTP performance. To do this, QTP is providing an object called RepositoriesCollection. Syntax for Loading a Repository: RepositoriesCollection.Add Path of the Repository File Syntax for finding Position of the Repository: Variable=RepositoriesCollection.Find(Path of the Repository) Syntax for Removing the Repository: RepositoriesCollection.Remove(position) Syntax for Removing All Repositories: RepositoriesCollection.RemoveAll Example: RepPath="C:\Documents and Settings\Administrator\My Documents\Logi n.tsr" RepositoriesCollection.Add (RepPath) systemutil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "sudhakar" Dialog("Login").WinEdit("Password:").Set "mercury" Dialog("Login").WinButton("OK").Click pos=RepositoriesCollection.Find(RepPath) RepositoriesCollection.Remove(pos) RepositoriesCollection.RemoveAll

QTP Scripting

QTP Tests in VB Script orientation provides a real-time approach on Scripting. Itexplains Flat file scripts, Excel Scripts, GUI Scripts, Web scripts, Database scripts and xml scripts with syntax and examples.

File System Scripts


1) Create a Folder Option Explicit Dim objFSO, objFolder, strDirectory strDirectory = "D:\Gcreddy" Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFolder = objFSO.CreateFolder(strDirectory) 2) Delete a Folder Set oFSO = CreateObject("Scripting.FileSystemObject") oFSO.DeleteFolder("E:\Gcreddy") 3) Copying Folders Set oFSO=createobject("Scripting.Filesystemobject") oFSO.CopyFolder "E:\gcr", "C:\jvr", True 4) Checking weather the folder available or not, if not creating the folder Option Explicit Dim objFSO, objFolder, strDirectory strDirectory = "D:\Gcreddy" Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.FolderExists(strDirectory) Then Set objFolder = objFSO.GetFolder(strDirectory) msgbox strDirectory & " already created " else Set objFolder = objFSO.CreateFolder(strDirectory) end if 5) Returning a collection of Disk Drives Set oFSO = CreateObject("Scripting.FileSystemObject") Set colDrives = oFSO.Drives For Each oDrive in colDrives MsgBox "Drive letter: " & oDrive.DriveLetter Next 6) Getting available space on a Disk Drive Set oFSO = CreateObject("Scripting.FileSystemObject")

Set oDrive = oFSO.GetDrive("C:") MsgBox "Available space: " & oDrive.AvailableSpace

Flat File Scripts

Computer File System It is a feature of the Operating System, used to Create/Modify/view/delete Drives, Folders and Files OS Distribution Operating System and Other Utilities FileSystemObject VBScript has Provided FileSystemObject to perform file system operations through scripting Dim objFso 'Creating an Automation Object in File System class, that can be used to performOperations on Computer File System Set objFso=CreateObject("scripting.FileSystemObject") 1) Creating a File Dim objFso Set objFso=CreateObject("scripting.FileSystemObject") objFso.CreateTextFile ("E:\Gcreddy.txt") objFso.CreateTextFile ("E:\Gcreddy.doc") objFso.CreateTextFile ("E:\Gcreddy.xls") objFso.CreateTextFile ("E:\Gcreddy.pdf") Note: We can Create other files also, but they act as Text/Flat Files Set objFile = objFSO.CreateTextFile("E:\Gcreddy.txt") 2) Checking weather the File is available or not, if not creating the File strDirectory="E:\" strFile="Gcreddy.txt" Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.FileExists(strDirectory & strFile) Then Set objFolder = objFSO.GetFolder(strDirectory) Else Set objFile = objFSO.CreateTextFile("E:\Gcreddy.txt") End if 3) Reading Data character by character from a Flat File

Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("E:\Gcreddy.txt", 1) Do Until objFile.AtEndOfStream strCharacters = objFile.Read(1) msgbox strCharacters Loop 4) Reading Data line by line from a Flat File Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("E:\Gcreddy.txt", 1) Do Until objFile.AtEndOfStream strCharacters = objFile.Readline msgbox strCharacters Loop 5) Data Driven Testing by fetching Test data directly from a Text file. ************************************************** 'Test Requirement: Data Driven Testing by Fetching Test data directly from a Text file.

'Author: G C Reddy 'Date of Creation: 13-08-2010 'Pre-requisites: 'gcr.txt (Test Data) 'Test Flow: 'Creating an Automation Object in FileSystem class 'Opening the External Test Data file using the Object 'Read the Data & Split the Data 'Generating the Login Operation 'Pass Parameters '************************************************* Dim objFso, myFile, myLine, myField Set objFso=CreateObject("Scripting.FileSystemObject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr.GCRC9A12FBD3D9\Desktop\vindod.txt",1) '1 for Read, 2-Write & 8-Append

myFile.SkipLine Do Until myFile.AtEndOfStream myLine=myFile.ReadLine myField=Split(myLine,",") SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("text:=Login").Activate Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set myField(0) Dialog("text:=Login").WinEdit("attached text:=Password:").Set myField(1) wait 2 Dialog("text:=Login").WinButton("text:=OK").Click Window("text:=Flight Reservation").Close Loop myFile.Close Set objFso=Nothing
6) Writing data to a text file Dim Stuff, myFSO, WriteStuff, dateStamp dateStamp = Date() Stuff = "I am Preparing this script: " &dateStamp Set myFSO = CreateObject("Scripting.FileSystemObject") Set WriteStuff = myFSO.OpenTextFile("e:\Gcreddy.txt", 8, True) WriteStuff.WriteLine(Stuff) WriteStuff.Close SET WriteStuff = NOTHING SET myFSO = NOTHING 7) Delete a text file Set objFSO=createobject("Scripting.filesystemobject") Set txtFilepath = objFSO.GetFile("E:\gcr.txt") txtFilepath.Delete() 8) Checking weather the File is available or not, if available delete the File strDirectory="E:\" strFile="gcr.txt" Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.FileExists(strDirectory & strFile) Then Set objFile = objFSO.Getfile(strDirectory & strFile)

objFile.delete () End if 9) Comparing two text files Dim f1, f2 f1="e:\Gcreddy1.txt" f2="e:\Gcreddy2.txt" Public Function CompareFiles (FilePath1, FilePath2) Dim FS, File1, File2 Set FS = CreateObject("Scripting.FileSystemObject") If FS.GetFile(FilePath1).Size <> FS.GetFile(FilePath2).Size Then CompareFiles = True Exit Function End If Set File1 = FS.GetFile(FilePath1).OpenAsTextStream(1, 0) Set File2 = FS.GetFile(FilePath2).OpenAsTextStream(1, 0) CompareFiles = False Do While File1.AtEndOfStream = False Str1 = File1.Read Str2 = File2.Read CompareFiles = StrComp(Str1, Str2, 0) If CompareFiles <> 0 Then CompareFiles = True Exit Do End If Loop File1.Close() File2.Close() End Function Call Comparefiles(f1,f2) If CompareFiles(f1, f2) = False Then MsgBox "Files are identical." Else MsgBox "Files are different." End If 10) Counting the number of times a word appears in a file sFileName="E:\gcr.txt" sString="gcreddy" Const FOR_READING = 1 Dim oFso, oTxtFile, sReadTxt, oRegEx, oMatches Set oFso = CreateObject("Scripting.FileSystemObject") Set oTxtFile = oFso.OpenTextFile(sFileName, FOR_READING) sReadTxt = oTxtFile.ReadAll

Set oRegEx = New RegExp oRegEx.Pattern = sString oRegEx.IgnoreCase = bIgnoreCase oRegEx.Global = True Set oMatches = oRegEx.Execute(sReadTxt) MatchesFound = oMatches.Count Set oTxtFile = Nothing : Set oFso = Nothing : Set oRegEx = Nothing msgbox MatchesFound 11) Read a CSV File Using Database Techniques On Error Resume Next Const adOpenStatic = 3 Const adLockOptimistic = 3 Const adCmdText = &H0001 Set objConnection = CreateObject("ADODB.Connection") Set objRecordSet = CreateObject("ADODB.Recordset") strPathtoTextFile = "C:\Databases\" objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & strPathtoTextFile & ";" & _ "Extended Properties=""text;HDR=YES;FMT=Delimited""" objRecordset.Open "SELECT * FROM PhoneList.csv", _ objConnection, adOpenStatic, adLockOptimistic, adCmdText Do Until objRecordset.EOF Wscript.Echo "Name: " & objRecordset.Fields.Item("Name") Wscript.Echo "Department: " & _ objRecordset.Fields.Item("Department") Wscript.Echo "Extension: " & objRecordset.Fields.Item("Extension") objRecordset.MoveNext Loop 12) Read a Text File into an Array Const ForReading = 1 Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTextFile = objFSO.OpenTextFile _ ("e:\gcreddy.txt", ForReading) Do Until objTextFile.AtEndOfStream

strNextLine = objTextFile.Readline arrServiceList = Split(strNextLine , ",") Wscript.Echo "Server name: " & arrServiceList(0) For i = 1 to Ubound(arrServiceList) Wscript.Echo "Service: " & arrServiceList(i) Next Loop 13) 'Calculate size of a Text file Dim objFso, File1,File2 File1="C:\Documents and Settings\1 RIGHATWAY\Desktop\xyz.txt" Set objFso=CreateObject(" Scripting.FileSystemObject") x= objFso.GetFile(File1).Size Msgbox x& " Bytes" 14) 'Test Requirement: Open 1 to 10 orders in Flight Reservation , Capture Customer names and Export into a Text file 'Test Flow: 'Login Operation 'Open Order Operation and form the Loop to open 1 to 10 Orders 'Capture Cusomer names using GetROProperty Method 'Create File system Object and Open the Text file using the Object and Export Cusomer names '---------------------------------------------------------------------------Option Explicit Dim Order_Number, Customer_Name, objFso, myFile Set objFso=CreateObject("Scripting.FileSystemObject") Set myFile= objFso.CreateTextFile ("C:\Documents and Settings\1 RIGHATWAY\Desktop\abcNew.txt",2) myFile.WriteLine "Cusomer Names" myFile.WriteLine "--------------------" If Not Window("Flight Reservation").Exist(3) Then SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "asdf" Dialog("Login").WinEdit("Password:").SetSecure "4c48590870466b8dc050bbd24e816890c747ccf8" Dialog("Login").WinButton("OK").Click End If For Order_Number= 1 to 10 step 1 Window("Flight Reservation").Activate

Window("Flight Reservation").WinButton("Button").Click Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set Order_Number Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click Customer_Name = Window("Flight Reservation").WinEdit("Name:").GetROProperty("text") wait (2) myFile.WriteLine Customer_Name Next myFile.Close Set objFso=Nothing 15) '****************************************************** 'Test Requirement: Capturing all Buttons Names from the Login Dialog box and exporting to a Text file 'Author: G C Reddy 'Date of Creation: 13-08-2010 'Pre-requasites: 'gcr.txt 'Test Flow: 'Creating an Automation Object in FileSystem class 'Opening the External Test Data file using the Object 'Creating Collection object and Capturing Button Names using the Object 'Writing Button Names to an External Text file '******************************************************** Dim objFso, myFile, oButton, Buttons, TotButtons Set objFso=CreateObject("Scripting.FileSystemObject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr.GCRC9A12FBD3D9\Desktop\vindod.txt",2) '1 for Read, 2-Write & 8-Append myFile.WriteLine "Button Names" myFile.WriteLine "----------" Set oButton=Description.Create oButton("micclass").value="WinButton" SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Set Buttons=Dialog("text:=Login").ChildObjects(oButton) TotButtons=Buttons.Count

For i= 0 to TotButtons-1 myButton=Buttons(i).GetRoProperty("text") myFile.WriteLine myButton Next myFile.Close Set objFso=Nothing 16) Delete a Text file if it is an empty file Dim objFso, FilePath FilePath="C:\Documents and Settings\gcreddy\Desktop\abc.txt" Set objFso=CreateObject("Scripting.FileSystemObject") FileSize=objFso.GetFile(FilePath).Size 'Msgbox FileSize If FileSize=0 Then objFso.DeleteFile(FilePath) End If Set objFso=Nothing

Database Scripts-I
1) Get Test Data From a Database and use in Data Driven Testing (through Scripting) Dim objCon, objRs 'Creating an automation object in database connection class, it is used forconnecting to databases. Set objCon=CreateObject("Adodb.Connection") 'Creating an automation object in database record set class, it is used forperforming operations on database tables(records). Set objRs= CreateObject("Adodb.Recordset") 'Establishing connection string for Ms-Access database. objCon.Provider=("Microsoft.Jet.oledb.4.0") objCon.Open "C:\Documents and Settings\gcr.GCRC9A12FBD3D9\Desktop\Flights.mdb" objRs.Open "Select * from Login", objCon Do Until objRs.EOF=True SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program

Files\HP\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set objRs.Fields("Agent") Dialog("Login").WinEdit("Password:").Set objRs.Fields("Pwd") Dialog("Login").WinButton("OK").Click Window("Flight Reservation").Close objRs.MoveNext Loop objRs.Close objCon.Close Set objCon=Nothing Set objRs=Nothing 2) Exporting Data from a Database to an Excel Sheet 1) Dim con,rs 2) Set con=createobject("adodb.connection") 3) Set rs=createobject("adodb.recordset") 4) con.provider="microsoft.jet.oledb.4.0" 5) con.open"C:\Documents and Settings\admin\My Documents\Gcreddy.md b" 6) rs.open"select*from Login",con 7) Set ex=createobject("Excel.Application") 8) Set a=ex.workbooks.open("C:\Documents and Settings\admin\MyDocuments \Gcreddy.xls") 9) Set b=a.worksheets("sheet1") 10) i=1 11) Do While Not rs.EOF 12) b.cells (i,1).value=rs.fields("agent") 13) b.cells(i,2).value=rs.fields("password") 14) rs.movenext 15) i=i+1 16) Loop 17) a.save 18) a.close 3) Exporting Data from a Database to a Text file Dim objCon,objRs,ObjFso,myFile,myData,rc,r Set objCon=createobject("Adodb.connection") Set objRs=createobject("Adodb.Recordset")

set objFso=createobject("Scripting.Filesystemobject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr\MyDocume nts\gcreddy.txt",8) objcon.provider=("Microsoft.jet.oledb.4.0") objcon.open"C:\Documents and Settings\gcr\My Documents\gcreddy.mdb " objrs.open "select * from login",objCon r=1 Do until objRs.EOF a=objRs.Fields ("Agent") b=objRs.Fields ("Pwd") myFile.Writeline a &","& b r=r+1 objRs.MoveNext Loop myFile.Close objCon.Close 4) Connecting to a SQL Sever database Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB.Connection") Set objRecordSet = CreateObject("ADODB.Recordset") objConnection.Open _ "Provider=SQLOLEDB;Data Source=atl-sql-01;" & _ "Trusted_Connection=Yes;Initial Catalog=Northwind;" & _ "User ID=fabrikam\kenmyer;Password=34DE6t4G!;" objRecordSet.Open "SELECT * FROM Customers", _ objConnection, adOpenStatic, adLockOptimistic objRecordSet.MoveFirst Wscript.Echo objRecordSet.RecordCount 5) Open a Database Using a DSN Const adOpenStatic = 3 Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection") Set objRecordSet = CreateObject("ADODB.Recordset") objConnection.Open _ "Northwind;fabrikam\kenmyer;34ghfn&!j" objRecordSet.Open "SELECT * FROM Customers", _ objConnection, adOpenStatic, adLockOptimistic objRecordSet.MoveFirst Wscript.Echo objRecordSet.RecordCount

6) Open Two Recordsets

Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB.Connection") Set objRecordSet = CreateObject("ADODB.Recordset") Set objRecordSet2 = CreateObject("ADODB.Recordset") objConnection.Open _ "Provider= Microsoft.Jet.OLEDB.4.0; " & _ "Data Source=inventory.mdb" objRecordSet.Open "SELECT * FROM GeneralProperties Where ComputerName = 'Computer1'", _ objConnection, adOpenStatic, adLockOptimistic objRecordSet.MoveFirst

objRecordSet2.Open "SELECT * FROM Storage Where ComputerName = 'Computer1'", _ objConnection, adOpenStatic, adLockOptimistic objRecordSet2.MoveFirst Do Until objRecordset.EOF

Wscript.Echo objRecordset.Fields.Item("ComputerName") Wscript.Echo objRecordset.Fields.Item("OSName") objRecordSet.MoveNext Loop Do Until objRecordset2.EOF Wscript.Echo objRecordset2.Fields.Item("DriveName"), _ objRecordset2.Fields.Item("DriveDescription") objRecordSet2.MoveNext Loop objRecordSet.Close objRecordSet2.Close objConnection.Close

7) Searching a Database Using String Criteria Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB.Connection") Set objRecordSet = CreateObject("ADODB.Recordset") objConnection.Open _ "Provider = Microsoft.Jet.OLEDB.4.0; " & _ "Data Source = eventlogs.mdb" objRecordSet.Open "SELECT * FROM EventTable " & _ "WHERE Type = 'Error'", objConnection, adOpenStatic, _ adLockOptimistic objRecordSet.MoveFirst Wscript.Echo "Number of records: " & objRecordset.RecordCount objRecordSet.Close objConnection.Close

Database Scripts-II

1) Insert Data into a database table using Database Command Object Dim objCon,objCom Set objCon=Createobject("ADODB.connection") objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\gcreddy.mdb;" Set objCom=Createobject("ADODB.Command") objCom.ActiveConnection=objCon objCom.CommandText="insert into Emp values('G C Reddy',88233,30000)" objCom.Execute objCon.Close Set objCom=Nothing Set objCon=Nothing 2) Insert multiple sets of Data (using Excel sheet) into a database table using Database Command Object Dim objCon,objCom,strEmpName,intEmpNo,intEmpSal,intRowcount,i Set objCon=Createobject("ADODB.connection") objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\gcredd y.mdb;" Set objCom=Createobject("ADODB.Command") objCom.ActiveConnection=objCon Datatable.AddSheet("input") Datatable.ImportSheet "C:\gcreddy.xls",1,"input" intRowcount=Datatable.GetSheet("input").GetRowCount Msgbox intRowcount For i=1 to intRowcount step 1 DataTable.SetCurrentRow(i) strEmpName= DataTable.Value(1,"input") intEmpNo= DataTable.Value(2,"input") intEmpSal= DataTable.Value(3,"input") objCom.CommandText="insert into Emp values( '"&strEmpName&" ',"&intEmpNo&","&intEmpSal&")"

objCom.Execute Next objCon.Close Set objCom=Nothing Set objCon=Nothing 3) Fetch data from a database, and compare with expected data in Excel file. ---------Dim objCon, objRs, objExcel, myFile, mysheet Set objCon=CreateObject("Adodb.Connection") Set objRs= CreateObject("Adodb.Recordset") Set objExcel=CreateObject("Excel.Application") Set myFile=objExcel.Workbooks.Open ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\TestData2.xls") Set mySheet=myFile.Worksheets("Sheet1") Rc=mySheet.usedrange.rows.count 'Msgbox Rc objCon.Provider=("Microsoft.Jet.oledb.4.0") objCon.Open "C:\Documents and Settings\gcr.GCRC9A12FBD3D9\Desktop\Comp.mdb" objRs.Open "Select EMPName from Employee", objCon

Do Until objRs.EOF=True x=objRs.Fields("EMPName") For j= 2 to Rc y=mySheet.cells(j,"A") If x=y Then Reporter.ReportEvent micPass,"Res","Name: "& y &" Available" ' Else 'Reporter.ReportEvent micFail,"Res","Name: "& y &" Not Available" End If Next objRs.MoveNext Loop objExcel.Quit

Set objExcel=Nothing objRs.Close objCon.Close Set objRs=Nothing Set objCom=Nothing

QTP Database Script Examples


----------------------------------------------------------------------------1) Data Driven Testing for Login Operation by Fetching Test Data directly From a Database Option Explicit Dim objConnection, objRecordSet 'Creating an Automation Object in Database Connection Class, that can be used to connect to Databases Set objConnection=CreateObject("Adodb.Connection") 'Creating an Automation Object in Database RecordSet Class, that can be used to Perform Operations on Database Tables (Records) Set objRecordSet=CreateObject("Adodb.RecordSet") 'Establishing Connection String for MS Access Database objConnection.Provider=("Microsoft.Jet.OLEDB.4.0") objConnection.Open "C:\Documents and Settings\bannu\Desktop\gcreddy.mdb" 'Fetching Test Data using RecordSet Object objRecordSet.Open "Select * From Login",objConnection Do Until objRecordSet.EOF=True SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("text:=Login").Activate Dialog("text:=Login").Winedit("attached text:=Agent Name:").Set objRecordSet.Fields("Agent") Dialog("text:=Login").Winedit("attached text:=Password:").Set objRecordSet.Fields("Password") Wait 2 Dialog("text:=Login").Winbutton("text:=OK","width:=60").Click Window("text:=Flight Reservation").Close objRecordSet.MoveNext Loop objRecordSet.Close objConnection.Close

Set objRecordSet=Nothing Set objConnection=Nothing 2) Write Data to a Database Table Dim objConnection, objCommand Set objConnection=CreateObject("Adodb.Connection") Set objCommand=CreateObject("Adodb.Command") objConnection.Provider=("Microsoft.ACE.OLEDB.12.0") objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb" objCommand.ActiveConnection=objConnection objCommand.CommandText ="Insert into Login values (8,'Chennai','Mercury')" objCommand.Execute objConnection.Close Set objCommand=Nothing Set objConnection=Nothing ----------------------------------------------------3) Write Multiple Sets of Data to a Database Table Dim objConnection, objCommand Dim objExcel, objWorkBook, objWorksheet Set objExcel=CreateObject("Excel.Application") Set objWorkBook=objExcel.Workbooks.Open ("C:\Documents and Settings\Test class\Desktop\data1.xls") Set objWorkSheet=objWorkBook.Worksheets("Sheet1") Set objConnection=CreateObject("Adodb.Connection") Set objCommand=CreateObject("Adodb.Command") objConnection.Provider=("Microsoft.ACE.OLEDB.12.0") objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb" objCommand.ActiveConnection=objConnection Rows_Count=objWorkSheet.Usedrange.Rows.Count

For i= 2 To Rows_Count Step 1 SNO=objWorkSheet.Cells(i,"A") Agent=objWorkSheet.Cells(i,"B") Password=objWorkSheet.Cells(i,"C") objCommand.CommandText ="Insert into Login values ('"&SNO&"','"&Agent&"','"&Password&"')" objCommand.Execute Next objWorkBook.Close objExcel.Quit Set objExcel=Nothing objConnection.Close Set objCommand=Nothing Set objConnection=Nothing --------------------------------------------------------4) Export Data from a Database Table to an Excel file (2nd Sheet) Option Explicit Dim objConnection, objRecordset Dim objExcel, objWorkbook, objWorksheet, i Set objConnection = Createobject ("Adodb.Connection") Set objRecordset = Createobject ("Adodb.Recordset") Set objExcel = CreateObject("Excel.Application") Set objWorkbook = objExcel.Workbooks.Open("C:\Documents and Settings\Test class\Desktop\data1.xls") Set objWorksheet = objWorkbook.Worksheets("Sheet2") objWorksheet.cells(1,"A") = "Agents" objWorksheet.cells(1,"B") = "Password" objConnection.Provider = ("Microsoft.ACE.OLEDB.12.0") objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb" objRecordset.Open "Select Agent, Password from Login", objConnection i = 2 'Rows Do Until objRecordset.EOF objWorksheet.cells(i, "A") = objRecordset.Fields("Agent")

objWorksheet.cells(i, "B") = objRecordset.Fields("Password") i=i+1 objRecordset.MoveNext Loop objWorkbook.Save objWorkbook.Close objExcel.Quit Set objExcel = Nothing objRecordset.Close objConnection.Close Set objRecordset = Nothing Set objConnection = Nothing ---------------------------------------------------5) Export Data from a Database Table to a Text file Option Explicit Dim objConnection, objRecordset Dim objFso,myFile Set objConnection = Createobject ("Adodb.Connection") Set objRecordset = Createobject ("Adodb.Recordset") Set objFso = CreateObject("Scripting.Filesystemobject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\Test class\Desktop\data1.txt",2) myFile.WriteLine "Agent "&" Password" myFile.WriteLine "--------------------" objConnection.Provider = ("Microsoft.ACE.OLEDB.12.0") objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb" objRecordset.Open "Select Agent, Password from Login", objConnection

Do Until objRecordset.EOF myFile.WriteLine objRecordset.Fields("Agent")&" ," & objRecordset.Fields("Password")

objRecordset.MoveNext Loop myFile.Close Set objFso=Nothing objRecordset.Close objConnection.Close Set objRecordset = Nothing Set objConnection = Nothing -----------------------------------------------6) Export Data from a Text File to a Database Table Option Explicit Dim objConnection, objCommand Dim objFso,myFile,myLine,myField,SNO,Agent,Password Set objConnection = Createobject ("Adodb.Connection") Set objCommand = Createobject ("Adodb.Command") Set objFso = CreateObject("Scripting.Filesystemobject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\Test class\Desktop\dat1.txt",1) objConnection.Provider = ("Microsoft.ACE.OLEDB.12.0") objConnection.Open "C:\Documents and Settings\Test class\Desktop\Flights.mdb" myFile.SkipLine myFile.SkipLine Do While myFile.AtEndOfStream = FALSE myLine = myFile.ReadLine myField = Split(myLine,",") SNO = myField(0) Agent = myField(1) Password = myField(2) objCommand.ActiveConnection = objConnection objCommand.CommandText = "Insert into Login2 values('"&SNO&"','"&Agent&"','"&Password&"')" objCommand.Execute Loop

myFile.Close Set objFso=Nothing Set objCommand = Nothing objConnection.Close Set objConnection = Nothing ---------------------------------------------------------------

Excel Scripts

1) Create an Excel file, enter some data and save the file through VB script? 1) 2) 3) 4) 5) 6) 7) Dim objexcel Set objExcel = createobject("Excel.application") objexcel.Visible = True objexcel.Workbooks.add objexcel.Cells(1, 1).Value = "Testing" objexcel.ActiveWorkbook.SaveAs("f:\exceltest.xls") objexcel.Quit

2) Check if the Excel file exists or not, if exists open the file and enter some data , If not Exists create the file and enter some data and save the file through VB script? Dim objExcel, FilePath FilePath="C:\Documents and Settings\gcr.GCRC9A12FBD3D9\Desktop\gcr.xls" Set objExcel=CreateObject("Excel.Application") set objFso=CreateObject("Scripting.FileSystemObject") objExcel.Visible=True If Not objFso.FileExists(FilePath) Then objExcel.Workbooks.Add objExcel.Cells(1,1).value="QTP" objExcel.ActiveWorkbook.SaveAs (FilePath) Else set myFile= objExcel.Workbooks.Open (FilePath) Set mySheet=myFile.Worksheets("Sheet1") mySheet.cells(1,1).value="QTP" objExcel.ActiveWorkbook.Save End If

objExcel.Quit Set objExcel=Nothing 3) Data Driven Testing through an External Excel Sheet 1) Set myExcel=Createobject("Excel.Application") 2) Set myFile=myExcel.workbooks.open ("C:\Documents andSettings\admin\My Documents\gcreddy.xls") 3) Set mySheet=myFile.worksheets("Sheet1") 4) Rows_Count=mySheet.usedrange.rows.count 5) For i= 1 to Rows_Count 6) Agent=mySheet.cells(i,"A") 7) pwd=mySheet.Cells(i,"B") 8) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open" 9) Dialog("Login").Activate 10) Dialog("Login").WinEdit("Agent Name:").Set Agent 11) Dialog("Login").WinEdit("Password:").SetSecure pwd 12) Dialog("Login").WinEdit("Password:").Type micReturn 13) Window("Flight Reservation").Close 14) Next 4) Compare two excel files Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True Set objWorkbook1= objExcel.Workbooks.Open("E:\gcreddy1.xls") Set objWorkbook2= objExcel.Workbooks.Open("E:\gcreddy2.xls") Set objWorksheet1= objWorkbook1.Worksheets(1) Set objWorksheet2= objWorkbook2.Worksheets(1) For Each cell In objWorksheet1.UsedRange If cell.Value <> objWorksheet2.Range(cell.Address).Value Then msgbox "value is different" Else msgbox "value is same" End If Next objWorkbook1.close objWorkbook2.close objExcel.quit set objExcel=nothing

5) Data Driven Testing using Data Table methods Datatable.AddSheet "gcreddy" Datatable.ImportSheet "C:\Documents andSettings\Administrator\Desktop\gcreddy.xls",1,3 n=datatable.GetSheet (3).GetRowCount For i= 1 to n Datatable.SetCurrentRow(i) Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set datatable("agent",3) Dialog("Login").WinEdit("Password:").Set datatable("pwd",3) Dialog("Login").WinButton("OK").Click Window("Flight Reservation").Close Next Example 2): Datatable.AddSheet "gcreddy" Datatable.ImportSheet "C:\Documents andSettings\Administrator\Desktop\gcreddy.xls",1,3 n=datatable.GetSheet (3).GetRowCount For i= 1 to n Datatable.SetCurrentRow(i) VbWindow("Form1").Activate VbWindow("Form1").VbEdit("val1").Set datatable("V1",3) VbWindow("Form1").VbEdit("val2").Set datatable("V2",3) VbWindow("Form1").VbButton("ADD").Click eres= Datatable.Value ("res",3) ares=VbWindow("Form1").VbEdit("res").GetROProperty ("text") If eres=ares Then datatable("res",3)=pass else datatable("res",3)=fail End If Next 6) Open an Excel Spreadsheet Set objExcel = CreateObject("Excel.Application") Set objWorkbook = objExcel.Workbooks.Open("C:\Scripts\gcreddy.xls") 7) Read an Excel Spreadsheet

Set objExcel = CreateObject("Excel.Application") Set objWorkbook = objExcel.Workbooks.Open _ ("C:\Scripts\New_users.xls") intRow = 2 Do Until objExcel.Cells(intRow,1).Value = "" Wscript.Echo "CN: " & objExcel.Cells(intRow, 1).Value Wscript.Echo "sAMAccountName: " & objExcel.Cells(intRow, 2).Value Wscript.Echo "GivenName: " & objExcel.Cells(intRow, 3).Value Wscript.Echo "LastName: " & objExcel.Cells(intRow, 4).Value intRow = intRow + 1 Loop objExcel.Quit 8) Add Formatted Data to a Spreadsheet Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True objExcel.Workbooks.Add objExcel.Cells(1, 1).Value = "Test value" objExcel.Cells(1, 1).Font.Bold = TRUE objExcel.Cells(1, 1).Font.Size = 24 objExcel.Cells(1, 1).Font.ColorIndex = 3 9) Sort an Excel Spreadsheet on Three Different Columns Const xlAscending = 1 Const xlDescending = 2 Const xlYes = 1 Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True Set objWorkbook = _ objExcel.Workbooks.Open("C:\Scripts\Sort_test.xls") Set objWorksheet = objWorkbook.Worksheets(1) Set objRange = objWorksheet.UsedRange

Set objRange2 = objExcel.Range("A1") Set objRange3 = objExcel.Range("B1") Set objRange4 = objExcel.Range("C1") objRange.Sort objRange2,xlAscending,objRange3,,xlDescending, _ objRange4,xlDescending,xlYes 10) Short an excel sheet column Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True Set objWorkbook = objExcel.Workbooks.Add Set objWorksheet = objWorkbook.Worksheets(1) objExcel.Cells(1, objExcel.Cells(2, objExcel.Cells(3, objExcel.Cells(4, 1).Value 1).Value 1).Value 1).Value = = = = "5" "1" "0" "3"

Set objRange=objworksheet.usedrange objrange.sort(objrange) 11) Add New Sheet to Excel File Dim objExcel Set objExcel = createobject("Excel.Application") objExcel.Visible=True objExcel.Workbooks.Add objexcel.ActiveWorkbook.SaveAs ("C:\Documents and Settings\gcr.GCRC9A12FBD3D9\Desktop\gcreddy.xls") objExcel.Worksheets.Add objExcel.ActiveWorkbook.Save objExcel.Quit Set objExcel=Nothing 12) Rename Sheets in an Excel File (WorkBook) Dim objExcel Set objExcel = createobject("Excel.Application") objExcel.Visible=True objExcel.Workbooks.Add objexcel.ActiveWorkbook.SaveAs ("C:\Documents and Settings\gcr.GCRC9A12FBD3D9\Desktop\gcreddy.xls")

objExcel.Worksheets("Sheet1").Name="gcr" objExcel.Worksheets("Sheet2").Name="qtp" objExcel.Worksheets("Sheet3").Name="training" objExcel.ActiveWorkbook.Save objExcel.Quit Set objExcel=Nothing 13) Add a Sheet to an Excel File (WorkBook) and change the Position Dim objExcel Set objExcel = createobject("Excel.Application") objExcel.Visible=True Set myFile= objExcel.Workbooks.Add objexcel.ActiveWorkbook.SaveAs ("C:\Documents and Settings\gcr.GCRC9A12FBD3D9\Desktop\gcreddy.xls") objExcel.Worksheets.Add myFile.Sheets("Sheet4").Move, myFile.Sheets(4) objExcel.ActiveWorkbook.Save objExcel.Quit Set objExcel=Nothing

GUI Script:
QTP Scripts examples
1) Verify Login Boundary (Check all the boundary conditions of the Login dialog box. Checks to see if the correct message appears in the error window (Flight Reservation Message) 1) ApplicationDir = Environment("ProductDir") 2) ApplicationPath = "\samples\flight\app\flight4a.exe" 3) If Window("Flight Reservation").Exist(2) Then 4) Window("Flight Reservation").Close 5) SystemUtil.Run ApplicationDir & ApplicationPath 6) Elseif Not Dialog("Login").Exist(1) Then 7) SystemUtil.Run ApplicationDir & ApplicationPath 8) End If 9) Dialog("Login").WinEdit("Agent Name:").Set Datatable.Value ("AgentName",dtGlobalSheet) 10) Dialog("Login").WinEdit("Password:").Set Datatable.Value ("Password",dtGlobalSheet) 11) Dialog("Login").WinButton("OK").Click 12) If Dialog("Login").Dialog("Flight Reservations").Exist(1) and Datatable.Value ("Status",dtGlobalSheet)="Fail" Then

13) Dialog("Login").Dialog("Flight Reservations").Static("Agent name must be at").Check CheckPoint("Agent name must be at least 4 characters long.") 14) Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click 15) Elseif Window("Flight Reservation").Exist(10) and Datatable.Value ("Status",dtGlobalSheet)="Pass" Then 16) Reporter.ReportEvent PASS,"Login: ","Succeeded" 17) Else 18) Reporter.ReportEvent Fail,"Login: ","Combination #" & Datatable.GetCurrentRow & " was not according to Excel file" 19) End If 2) Verify Cancel Operation (in Login Dialog box, if user selects cancel button, before enter any data after enter data dialog box should be disappeared.) 1) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 2) Dialog("Login").Activate 3) Dialog("Login").WinButton("Cancel").Click 4) If Dialog("Login").Exist (2) =True Then 5) Reporter.ReportEvent 1,"sd","Fail" 6) Else 7) Reporter.ReportEvent 0,"sd","Pass" 8) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 9) End If 10) Dialog("Login").Activate 11) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 12) Dialog("Login").WinButton("Cancel").Click 13) If Dialog("Login").Exist (2) =True Then 14) Reporter.ReportEvent 1,"sd","Fail" 15) Else 16) Reporter.ReportEvent 0,"sd","Pass" 17) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 18) End If 19) Dialog("Login").Activate 20) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 21) Dialog("Login").WinEdit("Password:").SetSecure "4a993af45dcbd506c8451b274d2da07b38ff5531" 22) Dialog("Login").WinButton("Cancel").Click 23) If Dialog("Login").Exist (2)=True Then 24) Reporter.ReportEvent 1,"sd","Fail" 25) Else 26) Reporter.ReportEvent 0,"sd","Pass"

27) Invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 28) End If 29) Dialog("Login").Activate 30) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 31) Dialog("Login").WinEdit("Password:").SetSecure "4a993af45dcbd506c8451b274d2da07b38ff5531" 32) Dialog("Login").WinButton("OK").Click 3) Verify Addition, Subtraction, Multiplication and Division Operations in Calculator Application. 1) Dim aRes,sRes,dRes,mRes 2) VbWindow("VbWindow").Activate 3) VbWindow("VbWindow").VbEdit("VbEdit").Set "10" 4) VbWindow("VbWindow").VbEdit("VbEdit_2").Set "20" 5) v1=VbWindow("VbWindow").VbEdit("VbEdit").GetROProperty ("text") 6) v2=VbWindow("VbWindow").VbEdit("VbEdit_2").GetROProperty ("text") 7) VbWindow("VbWindow").VbButton("ADD").Click 8) aRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText 9) VbWindow("VbWindow").VbButton("SUB").Click 10) sRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText 11) VbWindow("VbWindow").VbButton("MUL").Click 12) mRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText 13) VbWindow("VbWindow").VbButton("DIV").Click 14) dRes=VbWindow("VbWindow").VbEdit("VbEdit_3").GetVisibleText 15) v1=cdbl(v1) 16) v2=cdbl(v2) 17) aRes=cdbl (aRes) 18) sRes=cdbl (sRes) 19) mRes=cdbl (mRes) 20) dRes=cdbl (dRes) 21) If aRes=v1+v2 Then 22) Reporter.ReportEvent 0,"Res","Addition Passed" 23) else 24) Reporter.ReportEvent 1,"Res","Addition Failed" 25) End If 26) If sRes=v1-v2 Then 27) Reporter.ReportEvent 0,"Res","Subtraction Passed" 28) else 29) Reporter.ReportEvent 1,"Res","Subtraction Failed" 30) End If 31) If mRes=v1*v2 Then 32) Reporter.ReportEvent 0,"Res","Multiplecation Passed" 33) else

34) 35) 36) 37) 38) 39) 40)

Reporter.ReportEvent 1,"Res","Multiplecation Failed" End If If dRes=v1/v2 Then Reporter.ReportEvent 0,"Res","Division Passed" else Reporter.ReportEvent 1,"Res","Division Failed" End If

4) Verify state of Update Order Button, before open an Order and after open an Order (in Flight Reservation before opening an order Update Order button should be disabled after opening an order enabled.) 1) Option explicit 2) Dim bo,ao 3) If Not window("Flight Reservation").Exist (2) Then 4) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 5) Dialog("Login").Activate 6) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy" 7) Dialog("Login").WinEdit("Password:").SetSecure "4aa8bce9984f1a15ea187a2da5b18c545abb01cf" 8) Dialog("Login").WinButton("OK").Click 9) End If 10) Window("Flight Reservation").Activate 11) bo=Window("Flight Reservation").WinButton("Update Order").GetROProperty ("Enabled") 12) Window("Flight Reservation").WinButton("Button").Click 13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "1" 15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click 16) ao=Window("Flight Reservation").WinButton("Update Order").GetROProperty ("Enabled") 17) If bo=False Then 18) Reporter.ReportEvent 0,"Res","Update Order Button Disabled" 19) else 20) Reporter.ReportEvent 1,"Res","Update Order Button Enabled" 21) End If 22) If ao=True Then 23) Reporter.ReportEvent 0,"Res","Update Order Button Enabled" 24) else 25) Reporter.ReportEvent 1,"Res","Update Order Button Disabled" 26) End If

5) Price Consistency, In Flight Reservation (In Flight Reservation, First class price=3*Economy class price and Business class price=2*Economy class price) 1) Option explicit 2) Dim n,f,b,e 3) If Not window("Flight Reservation").Exist (2) Then 4) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 5) Dialog("Login").Activate 6) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 7) Dialog("Login").WinEdit("Password:").SetSecure "4aa8b7b7c5823680cfcb24d30714c9bbf0dff1eb" 8) Dialog("Login").WinButton("OK").Click 9) End If 10) For n= 1 to 10 step 1 11) Window("Flight Reservation").Activate 12) Window("Flight Reservation").WinButton("Button").Click 13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set n 15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click 16) Window("Flight Reservation").WinRadioButton("First").Set 17) f=Window("Flight Reservation").WinEdit("Price:").GetVisibleText 18) Window("Flight Reservation").WinRadioButton("Business").Set 19) b=Window("Flight Reservation").WinEdit("Price:").GetVisibleText 20) Window("Flight Reservation").WinRadioButton("Economy").Set 21) e=Window("Flight Reservation").WinEdit("Price:").GetVisibleText 22) f=cdbl(mid(f,2,len (f-1))) 23) b=cdbl(mid(b,2,len (b-1))) 24) e=cdbl(mid(e,2,len (e-1))) 25) If f=3*e and b=2*e Then 26) Reporter.ReportEvent 0,"Res","Pricy Consistancy is there" 27) else 28) Reporter.ReportEvent 1,"Res","Pricy Consistancy is NOT there" 29) End If 30) Window("Flight Reservation").WinButton("Button_2").Click 31) Window("Flight Reservation").Dialog("FlightReservations").WinButton("No").Click 32) Next 6) Verify Total, In Flight Reservation (In Flight Reservation, Total = Tickets * Price) 1) Option Explicit

2) Dim t,p,tot,n 3) For n= 1 to 10 step 1 4) If Not window("Flight Reservation").Exist (2) Then 5) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open" 6) Dialog("Login").Activate 7) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy" 8) Dialog("Login").WinEdit("Password:").SetSecure "4aa892d62c529f1c23298175ad78c58f43da8e34" 9) Dialog("Login").WinButton("OK").Click 10) End If 11) Window("Flight Reservation").Activate 12) Window("Flight Reservation").WinButton("Button").Click 13) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 14) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set n 15) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click 16) t=Window("Flight Reservation").WinEdit("Tickets:").GetVisibleText 17) p=Window("Flight Reservation").WinEdit("Price:").GetVisibleText 18) tot=Window("Flight Reservation").WinEdit("Total:").GetVisibleText 19) t=cdbl (t) 20) p=Cdbl(mid(p,2,len (p-1))) 21) tot=Cdbl(mid(tot,2,len (tot-1))) 22) If tot=t*p Then 23) Reporter.ReportEvent 0,"Res","Calculation Passed" 24) else 25) Reporter.ReportEvent 1,"Res","Calculation Failed" 26) End If 27) Next 7) Verify Flight From & Flight To Combo Boxes (In Flight reservation, select an item from Fly From: combo box and verify weather that item available or not in Fly To: combo box, like this select all items one by one in Fly From and verify weather selected items available or not in Fly To.) 1) 2) 3) 4) 5) 6) 7) Option explicit Dim qtp,flight_app,f,t,i,j,x,y If Not Window("text:=Flight Reservation").Exist (7)= True Then QTP=Environment("ProductDir") Flight_app="\samples\flight\app\flight4a.exe" SystemUtil.Run QTP & Flight_app Dialog("text:=Login").Activate

8) Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set "asdf" 9) Dialog("text:=Login").WinEdit("attached text:=Password:").SetSecure "4aa5ed3daf680e7a759bee1c541939d3a54a5b65" 10) Dialog("text:=Login").WinButton("text:=OK").Click 11) End If 12) Window("text:=Flight Reservation").Activate 13) Window("text:=Flight Reservation").WinButton("window id:=6").Click 14) Window("text:=Flight Reservation").ActiveX("acx_name:=MaskEdBox","window id:=0").Type "090910" 15) f=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").GetItemsCount 16) For i= 0 to f-1 step 1 17) Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").Select (i) 18) x=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly From:").GetROProperty ("text") 19) t=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").GetItemsCount 20) For j= 0 to t-1 step 1 21) Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").Select (j) 22) y=Window("text:=Flight Reservation").WinComboBox("attached text:=Fly To:","x:=244","y:=147").GetROProperty ("text") 23) If x <> y Then 24) Reporter.ReportEvent 0,"Res","Test Passed" 25) Else 26) Reporter.ReportEvent 1,"Res","Test Failed" 27) End If 28) Next 29) Next 8) Verify Order No Entry in Flight Reservation. (In Open Order dialog box, Order No object accepts numeric values only.) 1) If Not window("Flight Reservation").Exist (2) Then 2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 3) Dialog("Login").Activate 4) Dialog("Login").WinEdit("Agent Name:").Set "asdf" 5) Dialog("Login").WinEdit("Password:").SetSecure "4aa9ccae3bb00962b47ff7fb0ce3524c1d88cb43" 6) Dialog("Login").WinButton("OK").Click 7) End If 8) Window("Flight Reservation").Activate

9) Window("Flight Reservation").WinButton("Button").Click 10) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 11) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "a" 12) ord=Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").GetVisibleText 13) If ord= "a" Then 14) Reporter.ReportEvent 1,"Res","Order No Object is taking invalid data" 15) else 16) Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "1" 17) Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click 18) End If 9) Get Test Data from a Flat file and use in Data Driven Testing (through Scripting) 1) Dim fso,myfile 2) Set fso=createobject("scripting.filesystemobject") 3) Set myfile= fso.opentextfile ("F:\gcr.txt",1) 4) myfile.skipline 5) While myfile.atendofline <> True 6) x=myfile.readline 7) s=split (x, ",") 8) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 9) Dialog("Login").Activate 10) Dialog("Login").WinEdit("Agent Name:").Set s(0) 11) Dialog("Login").WinEdit("Password:").SetSecure s(1) 12) Dialog("Login").WinButton("OK").Click 13) Window("Flight Reservation").Close 14) Wend 10) Count, how many Buttons and Edit boxes available in Flight Reservation main window. 1) If Not window("Flight Reservation").Exist (2) Then 2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 3) Dialog("Login").Activate 4) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy" 5) Dialog("Login").WinEdit("Password:").Set "mercury" 6) Dialog("Login").WinButton("OK").Click 7) End If

8) Set oDesc = Description.Create() 9) oDesc("micclass").Value = "WinButton" 10) Set Buttons = Window("text:=Flight Reservation").ChildObjects (oDesc) 11) Num_Buttons = Buttons.Count() 12) Set oDesc1=Description.Create() 13) oDesc1("micclass").Value="WinEdit" 14) Set Editboxes=Window("text:=Flight Reservation").ChildObjects (oDesc1) 15) Num_Editboxes= editboxes.count () 16) sum= Num_Buttons+Num_Editboxes 17) Reporter.ReportEvent 2, "Res","Total Buttons: "& Num_Buttons &"Total Edit boxes: "& Num_Editboxes 11) Verify search options in Open Order Dialog box (After selecting open order, 3 search options should be enabled and not checked, After selecting Order No option, other options should be disabled, After selecting Customer Name, Flight date option enabled and Order No disabled After selecting Flight date option, Customer Name enabled and Order No disabled) 1) If Not window("Flight Reservation").Exist (2) Then 2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 3) Dialog("Login").Activate 4) Dialog("Login").WinEdit("Agent Name:").Set "Gcreddy" 5) Dialog("Login").WinEdit("Password:").SetSecure "4aa9ed25bc0ebde66ed726ad87d7e991347d8b9c" 6) Dialog("Login").WinButton("OK").Click 7) End If 8) Window("Flight Reservation").Activate 9) Window("Flight Reservation").WinButton("Button").Click 10) Window("Flight Reservation").Dialog("Open Order").Activate 11) oe=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled") 12) ce=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled") 13) fe=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty("Enabled") 14) oc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Checked") 15) cc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Checked")

16) fc=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty("Checked") 17) If (oe=true and ce=true and fe=true) and (oc="OFF" and cc="OFF" and fc="OFF") Then 18) Reporter.ReportEvent 0,"Res","Pass" 19) else 20) Reporter.ReportEvent 1,"Res","Fail" 21) End If 22) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" 23) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Checked") 24) If ono="ON" Then 25) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Enabled") 26) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled") 27) fd=false 28) ono=false 29) Reporter.ReportEvent 0,"Res","Pass" 30) else 31) Reporter.ReportEvent 1,"Res","Fail" 32) End If 33) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "OFF" 34) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").Set "ON" 35) cn=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Checked") 36) If cn="ON" Then 37) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled") 38) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Enabled") 39) fd=True 40) ono=false 41) Reporter.ReportEvent 0,"Res","Pass" 42) else 43) Reporter.ReportEvent 1,"Res","Fail" 44) End If 45) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").Set "OFF" 46) Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").Set "ON" 47) fd=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Flight Date").GetROProperty ("Checked")

48) If fd="ON" Then 49) ono=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").GetROProperty ("Enabled") 50) cn=Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Customer Name").GetROProperty ("Enabled") 51) cn=True 52) ono=false 53) Reporter.ReportEvent 0,"Res","Pass" 54) else 55) Reporter.ReportEvent 1,"Res","Fail" 56) End If 12) In Login Dialog box, Verify Help message (The message is The password is 'MERCURY') 1) If Not Dialog("Login").Exist (2) Then 2) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 3) End If 4) Dialog("Login").Activate 5) Dialog("Login").WinButton("Help").Click 6) message=Dialog("Login").Dialog("Flight Reservations").Static("The password is 'MERCURY'").GetROProperty("text") 7) If message="The password is 'MERCURY'" Then 8) Reporter.ReportEvent 0,"Res","Correct message "&message 9) else 10) Reporter.ReportEvent 1,"Res","Worng message " 11) End If

Web Scripts

1) Count all opened Browsers on desktop and close them all? Set oDesc = Description.Create() oDesc("micclass").Value = "Browser" Set Browsers =Desktop.ChildObjects (oDesc) NumberofBrowsers = Browsers.Count() Reporter.ReportEvent 2,"Res","Number of Browsers are: "&NumberOfBrowsers For Counter=0 to NumberofBrowsers-1 Browsers(Counter).Close Next 2) Count, how many links available in Mercury Tours Home Page. Set oDesc = Description.Create()

oDesc("micclass").Value = "Link" Set Lists = Browser("Welcome: Mercury").Page("Welcome: Mercury").ChildObjects (oDesc) NumberOfLinks = Lists.Count() Reporter.ReportEvent 2,"Res","Number of Links are: "&NumberOfLinks 3) Verify whether the 'Gmail' link available or not on Google Homepage Option explicit Dim oLink, Links, TotLinks, i, myLink Set oLink = description.Create oLink("micclass").value = "Link" SystemUtil.Run "D:\Program Files\Internet Explorer\IEXPLORE.EXE" set Links = Browser("name:=Google").page("title:=Google").ChildObjects(oLink) TotLinks = Links.count For i =0 to TotLinks-1 myLink = Links(i).getroproperty("innertext") If mylink = "Gmail" Then reporter.ReportEvent 0,"res","Link Gmail available" End If Next 4) Count number of Links, Edit Boxes available on Google Homepage? Dim oLink Set oLink=description.Create Set oEdit=description.Create oLink("micclass").value="Link" oEdit("micclass").value="WebEdit" Set Links=browser("name:=Google").page("title:=Google").ChildObjects(oLin k) Set EditBoxes=browser("name:=Google").page("title:=Google").ChildObjects (oEdit) TotLinks= Links.count TotEditBoxes=EditBoxes.count msgbox TotLinks msgbox TotEditBoxes Reporter.ReportEvent 0,"Result","Total Links are: "&TotLinks&"Total edit Boxes are: "&TotEditBoxes

5) Count how many links available in a Web Page(any web page, using Regular Expressions) Dim oLink,Links, TotLinks Set oLink=Description.Create oLink("micclass").value="Link" Set Links=Browser("title:=.*").page("title:=.*").ChildObjects(oLink) TotLinks=Links.count msgbox TotLinks Reporter.ReportEvent 2,"Res","Total Links are: "&TotLinks 6) Verify Cost in jjperfumes.com 'Test Flow 'i) Launch jjperfumes.com 'ii) Select a product and enter some quantity 'iii) select Add to Cart, capture Unit price, Quantity and Cost 'iV) Remove $ symbols and compare '---------------------------------- ----SystemUtil.Run "C:\Program Files\Internet Explorer\iexplore.exe","","C:\Documents and Settings\gcr.GCRC9A12FBD3D9","open" Browser("Google").Page("Google").Sync Browser("Google").Navigate "http://www.jjperfumes.com/" Browser("Google").Page("JJ Perfumes-Discount perfume").Image("thumb_1845_WLINP50PSW").Click Browser("Google").Page("JJ Perfumes-Discount perfume_2").WebEdit("quantity").Set "4" Browser("Google").Page("JJ Perfumes-Discount perfume_2").WebButton("Add To Cart").Click Unit_Price = Browser("Google").Page("JJ Perfumes-Discount perfume_3").WebElement("[Remove]").GetROProperty("innertext") Qty = Browser("Google").Page("JJ Perfumes-Discount perfume_3").WebEdit("quantity[]").GetROProperty("value") Cost = Browser("Google").Page("JJ Perfumes-Discount perfume_3").WebElement("[Remove]_2").GetROProperty("innertext") Qty=Cint(Qty) Unit_Price=Cdbl (Mid (Unit_Price,3)) Cost=Cdbl (Mid (Cost, 3)) 'Msgbox Unit_Price: Msgbox Qty: Msgbox Cost If Cost=Qty * Unit_Price Then Reporter.ReportEvent micPass,"Res","Cost is Correct"

Else Reporter.ReportEvent micFail,"Res","Cost is InCorrect" End If Function To Create HTML Report Dim StartTime,stTime, enTime Dim fso, ts,intCnt, intPass,intFail intPass=0 intFail=0 Const ForWriting = 2 Function OpenFile (strFileName) StartTime = Timer stTime = Time Set fso = CreateObject("Scripting.FileSystemObject") Set ts = fso.OpenTextFile(strFileName,2) 'OpenFile = strFileURL CreateHeader End Function ***************************** Function To Close File Dim objIE,strFileURL Function CloseFile ( strFileURL,strEnv ) Footer(strEnv) ts.close() Set objIE = CreateObject("InternetExplorer.Application") objIE.visible = True objIE.Navigate strFileURL wait(5) Set objIE=nothing End Function *********************** Function to Clear Cookies() Function ClearCookies() SystemUtil.Run "iexplore.exe" WebUtil.DeleteCookies Set objBrowser=Description.Create objBrowser("micclass").value="Browser" Set objBCount = Desktop.ChildObjects(objBrowser) intBrowserCount = objBCount.Count strHwnd=Browser("creationtime:=" & intBrowserCount).GetROProperty("hwnd")

SystemUtil.CloseProcessByHwnd(strHwnd) End Function *********************** Function to send Email Function SendMail() If k=0 Then 'Nothing Else msgsub = " Geo_PostalCode pattern searchTest Results:" &vbcrLf &"One or more of the Test Cases Failed." &vbcrLf &"See attachment for details." End If Set objConf = CreateObject("CDO.Configuration") cdoSendUsingPort=2 sMailServerName="smtp.phx.move.com" cdoAnonymous=cdoNONE objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/sen dusing") = cdoSendUsingPort objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/smt pserver") = sMailServerName objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/smt pauthenticate") = cdoAnonymous 'cdoBasic objConf.fields.Item("http://schemas.microsoft.com/cdo/configuration/smt pusessl") = False objConf.fields.Item("http://schemas.microsoft.com/cdo/configuration/smt pserverport") = 25 'objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/sen dusername") = "corp\ NRaoJ " 'objConf.fields.item("http://schemas.microsoft.com/cdo/configuration/sen dpassword") = "123K!r45" objConf.fields.Item("http://schemas.microsoft.com/cdo/configuration/smt pconnectiontimeout") = 60 objConf.fields.Update Set objMsg = CreateObject("CDO.Message") objMsg.Configuration = objConf objMsg.to = "gcreddy@gmail.com" objMsg.From = "gcreddy@gmail.com" objMsg.Subject = "~Geo_PostalCode pattern search" objMsg.TextBody =msgsub doc=strFilepath objMsg.AddAttachment(doc) objMsg.Send

Set objMsg = Nothing NewMail = True End Function *********************** Function to create append excel Function LogFile Set objExcel=CreateObject("Excel.Application") objExcel.visible=False objExcel.workbooks.open(strFilePath) r=1 Do Until len(objExcel.cells(r,1))=0 r=r+1 Loop objExcel.cells(r,1).value="Step Name" objExcel.cells(r,2).value="Step Description" objExcel.cells(r,3).value="Test Results" objExcel.DisplayAlerts = False objExcel.Save objExcel.Quit Set objExcel = Nothing End Function *********************** Function to get the Application Environment on which the script is running Function GetEnv() Set fso=Createobject("Scripting.FileSystemObject") sFile="C:\WINDOWS\system32\drivers\etc\hosts" Set MyFile=fso.OpenTextFile(sFile,1, True) Do sEnv=MyFile.ReadLine If instr(sEnv,"PRODUCTION")>0 Then GetEnv="Production" Exit do Elseif instr(sEnv,"Staging")>0 Then GetEnv="Staging" Exit do Elseif instr(sEnv,"QA MAINTENANCE")>0 Then GetEnv="QAM"

Exit do Elseif instr(sEnv,"qap.")>0 Then GetEnv="qap" Exit do End If Loop While MyFile.AtEndOfStream=False End Function *********************** Function To Create HTML Report Dim StartTime,stTime, enTime Dim fso, ts,intCnt, intPass,intFail intPass=0 intFail=0 Const ForWriting = 2 Function OpenFile (strFileName) StartTime = Timer stTime = Time Set fso = CreateObject("Scripting.FileSystemObject") Set ts = fso.OpenTextFile(strFileName,2) 'OpenFile = strFileURL CreateHeader End Function

Web Scripts-II
Web Application Testing using QTP. Web forms verification, Object state verification, Database Testing and Links verification. 1) Script to get the list of links in Google and do spell check ===================================== Dim d set mw=CreateObject("Word.Application") set d=Description.Create d("micclass").value="Link" set a=Browser("Google").page("Google").childobjects(d) for i=0 to a.count-1 mw.WordBasic.filenew s=a(i).getROProperty("innertext") mw.WordBasic.insert s if mw.ActiveDocument.Spellingerrors.count>0 then

Reporter.ReportEvent 1,"Spelling","spelling error :"&s end if mw.ActiveDocument.Close(False) next mw.quit set mw=nothing 2) Script to check ON the checkboxes in yahoo mail inbox ======================================== Dim d Set d=Description.Create d("micclass").value="WebCheckBox" Set c=Browser("Inbox (17) - Yahoo! Mail").Page("Inbox (17) - Yahoo! Mail").ChildObjects(d) For i=1 to 10 c(i).set "ON" Next 3) script to select a mail having subject 'hi' or 'HI' ================================= n=Browser("yahoo").Page("yahoo").WebTable("Inbox").RowCount For i=2 to n s=Browser("yahoo").Page("yahoo").WebTable("Inbox").GetCellData(i,7) If lcase(trim(s))="hi" Then Browser("yahoo").Page("yahoo").WebCheckBox("index:="&i-1).set "ON" End If Next 4) Function to send a mail ==================== Function SendMail(SendTo, Subject, Body, Attachment) Set otl=CreateObject("Outlook.Application") Set m=otl.CreateItem(0) m.to=SendTo m.Subject=Subject m.Body=Body If (Attachment <> "") Then Mail.Attachments.Add(Attachment) End If m.Send otl.Quit Set m = Nothing Set otl = Nothing

End Function Call SendMail("nagesh.rao46@gmail.com","hi","This is test mail for tsting","") Adv VBScripts 5) Open Internet Explorer and navigate to yahoo mail =================================== Dim ie Set ie=CreateObject("InternetExplorer.Application") ie.Visible=True ie.Navigate "www.yahoomail.com" x=Browser("CreationTime:=0").GetROProperty("title") msgbox x 6) Function for Counting Objects from any opened web page Function Objects_Count(myObject) Dim Objects Set Objects=Description.Create Objects("micclass").value=myObject Set Object=Browser("title:=.*").Page("title:=.*").ChildObjects(Objects) TotObjects=Object.Count Msgbox TotObjects End Function Call Objects_Count("WebButton") 7) Create script for links validation and set results into an excel file Set objDesc=Description.Create objDesc("micclass").value="Link" Set objColl=Browser("title:=.*").page("title:=.*").ChildObjects(objDesc) msgbox objColl.count Set objExcel=Createobject("Excel.application") objExcel.Visible=True objExcel.Workbooks.Add

set objSheet=objExcel.ActiveSheet objSheet.cells(1,1)="LinkName" set c1=objSheet.cells(1,1) c1.font.color=vbBlue objSheet.cells(1,2)="TargetUrl" Set c2=objSheet.cells(1,2) c2.font.color=vbBlue objSheet.cells(1,3)="ActualUrl" Set c3=objSheet.cells(1,3) c3.font.color=vbBlue objSheet.cells(1,4)="Status" Set c4=objSheet.cells(1,4) c4.font.color=vbBlue For i=0 to objColl.count-37 step 1 strName=Browser("title:=.*").page("title:=.*").Link("index:="&i).GetRo Property("name") TargetUrl=Browser("title:=.*").page("title:=.*").Link("index:="&i).GetRo Property("url") msgbox TargetUrl Browser("title:=.*").page("title:=.*").Link("index:="&i).click wait(4) ActualUrl=Browser("title:=.*").GetRoProperty("url") msgbox ActualUrl

If instr (1,TargetUrl,ActualUrl,1) > 0 Then Reporter.ReportEvent micPass,"Link Name "&strName,"Link Validation done" objSheet.cells(i+2,1)=strName objsheet.cells(i+2,2)=TargetUrl objsheet.cells(i+2,3)=ActualUrl objsheet.cells(i+2,4)="Link Validation done" Set c5= objsheet.cells(i+2,4) c5.font.color=vbGreen Else Reporter.ReportEvent micFail,"Link Name validation fail" objSheet.cells(i+2,1)=strName objsheet.cells(i+2,2)=TargetUrl objsheet.cells(i+2,3)=ActualUrl objsheet.cells(i+2,4)="Link Validation fail" Set c5= objsheet.cells(i+2,4) c5.font.color=vbRed End If Browser("title:=.*").Back Next Set objWbook=objExcel.ActiveWorkbook "&strName,"Link

objWbook.SaveAs "E:\gcreddy.xls" objExcel.Quit Set objExcel=nothing

qtp real-time script example

QuickTest Professional is an Industry leading and famous Testing Tool for Functional & Regression Testing QTP uses VB Script for scripting We can use QTP Tool features as well as VB Script Flow Control statements for inserting verification points. If we want to use VB Script Flow Control statements for inserting flow control statements, then we need to define Test results. QTP has provided a facility to define Test Results, using Reporter Utility Object to define test results. Using Comments is a best practice in QTP Scripting to understand the code. Creating functions for modular code is a best practice and intelligent task in scripting /Programming. using Automation Objects is an useful task in QTP scripting using Built-in functions and regular expressions is an useful task. QTP Scripting has several types: a) GUI scripting: using scripting for GUI based Applications b) Web scripting: Automation web based applications using vb script c) Database scripting: Using scripting for Database operations such as data comparisons and validations. d) Excel scripting: Handling and using Excel files in Test Automation

Excel Scripting Examples-2


1) Data Driven Testing for Login Operation by fetching from an excel file Dim objExcel, myFile, mySheet Set objExcel=CreateObject("Excel.Application") Set myFile=objExcel.Workbooks.Open("C:\Documents andSettings\gcreddy\Desktop\data.xls") Set mySheet=myFile.Worksheets("Sheet1") Rows_Count=mySheet.usedrange.rows.count For i= 2 to Rows_Count step 1 SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"

Dialog("text:=Login").Activate Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set mySheet.Cells(i,"A") Dialog("text:=Login").WinEdit("attached text:=Password:").Set mySheet.Cells(i,"B") Wait (2) Dialog("text:=Login").WinButton("text:=OK").Click Window("text:=Flight Reservation").Close Next myFile.Close objExcel.Quit Set objExcel=Nothing ----------------------------------------2) Data Driven Testing for Login Operation by fetching Test Data from anexcel file and Export Result to the Same file Dim objExcel, myFile, mySheet Set objExcel=CreateObject("Excel.Application") Set myFile=objExcel.Workbooks.Open("C:\Documents andSettings\gcreddy\Desktop\data.xls") Set mySheet=myFile.Worksheets("Sheet1") Rows_Count=mySheet.usedrange.rows.count For i= 2 to Rows_Count step 1 SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("text:=Login").Activate Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set mySheet.Cells(i,"A") Dialog("text:=Login").WinEdit("attached text:=Password:").Set mySheet.Cells(i,"B") Wait (2) Dialog("text:=Login").WinButton("text:=OK").Click If Window("text:=Flight Reservation").Exist(12) Then Window("text:=Flight Reservation").Close Result="Login Operation Sucessful" mySheet.Cells(i,"C")=Result Else SystemUtil.CloseDescendentProcesses Result="Login Operation Failed" mySheet.Cells(i,"C")=Result End If Next myFile.Save

myFile.Close objExcel.Quit Set objExcel=Nothing -----------------------------3) 'Data Driven Testing for Login Operation by fetching Test Data from anexcel file ' Export Result and Error message to the Same file ' Dim objExcel, myFile, mySheet Set objExcel=CreateObject("Excel.Application") Set myFile=objExcel.Workbooks.Open("C:\Documents andSettings\gcreddy\Desktop\data.xls") Set mySheet=myFile.Worksheets("Sheet1") Rows_Count=mySheet.usedrange.rows.count For i= 2 to Rows_Count step 1 SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("text:=Login").Activate Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Set mySheet.Cells(i,"A") Dialog("text:=Login").WinEdit("attached text:=Password:").Set mySheet.Cells(i,"B") Wait (2) Dialog("text:=Login").WinButton("text:=OK").Click If Window("text:=Flight Reservation").Exist(12) Then Window("text:=Flight Reservation").Close Result="Login Operation Sucessful" mySheet.Cells(i,"C")=Result Else Error_Message = Dialog("Login").Dialog("Flight Reservations").Static("Agent name must be at").GetROProperty("text") SystemUtil.CloseDescendentProcesses Result="Login Operation Failed" mySheet.Cells(i,"C")=Result mySheet.Cells(i,"D")=Error_Message End If Next myFile.Save myFile.Close objExcel.Quit Set objExcel=Nothing ------------------------------------------------------------------

4) 'Open 1 to 10 Orders in Flight Reservation window and capture Order Numbers and Customer Names 'Export to an Excel File Dim objExcel,myFile,mySheet,i Set objExcel = CreateObject("Excel.Application") Set myFile=objExcel.Workbooks.Open("C:\Documents andSettings\gcreddy\Desktop\data.xls") Set mySheet = myFile.Worksheets("Sheet2") row=1 mySheet.Cells(row,"A")="OrderNo" mySheet.Cells(row,"B")="CustomerName" If Not Window("Flight Reservation").Exist(3) Then SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "asdf" Dialog("Login").WinEdit("Password:").SetSecure "4d0a254623fcf8d10630f10b6ca8e776fcbc0717" Dialog("Login").WinButton("OK").Click End If For i = 1 to 10 Step 1 Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("Button").Click Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set i Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click Customer_Name = Window("Flight Reservation").WinEdit("Name:").GetROProperty("text") row=row+1 mySheet.Cells(row,"A") = i mySheet.Cells(row,"B") = Customer_Name Next myFile.Save myFile.Close objExcel.Quit Set objExcel =Nothing

System Administration
1) GettingLocalComputerInformation

SetobjComputer=CreateObject("Shell.LocalMachine") Wscript.Echo"Computername:"&objComputer.MachineName Wscript.Echo"Shutdownallowed:"&objComputer.IsShutdownAllowed Wscript.Echo"FriendlyUIenabled:"&objComputer.IsFriendlyUIEnabled Wscript.Echo"Guestaccessmode:"&objComputer.IsGuestAccessMode Wscript.Echo"Guestaccountenabled:"&_ objComputer.IsGuestEnabled(0) Wscript.Echo"Multipleusersenabled:"&_ objComputer.IsMultipleUsersEnabled Wscript.Echo"Offlinefilesenabled:"&_ objComputer.IsOfflineFilesEnabled Wscript.Echo"Remoteconnectionsenabled:"&_ objComputer.IsRemoteConnectionsEnabled Wscript.Echo"Undockenabled:"&objComputer.IsUndockEnabled

2) RestartaComputer strComputer="atl-dc-01" SetobjWMIService=GetObject("winmgmts:"_ &"{impersonationLevel=impersonate,(Shutdown)}!\\"&_ strComputer&"\root\cimv2") SetcolOperatingSystems=objWMIService.ExecQuery_ ("Select*fromWin32_OperatingSystem") ForEachobjOperatingSystemincolOperatingSystems objOperatingSystem.Reboot() Next 3) ShutDownaComputer strComputer="." SetobjWMIService=GetObject_ ("winmgmts:{impersonationLevel=impersonate,(Shutdown)}\\"&_ strComputer&"\root\cimv2") SetcolOperatingSystems=objWMIService.ExecQuery_ ("Select*fromWin32_OperatingSystem") ForEachobjOperatingSystemincolOperatingSystems objOperatingSystem.Win32Shutdown(1) Next 4) ModifySystemStartupDelay strComputer="." SetobjWMIService=GetObject("winmgmts:"_ &"{impersonationLevel=impersonate}!\\"&strComputer&"\root\cimv2")

SetcolStartupCommands=objWMIService.ExecQuery_ ("Select*fromWin32_ComputerSystem") ForEachobjStartupCommandincolStartupCommands objStartupCommand.SystemStartupDelay=10 objStartupCommand.Put_ Next

MS Word Scripts
1) create a word document and write some data ==================== dim mw set mw=CreateObject("Word.Application") mw.Documents.Add mw.selection.typetext "hello" mw.ActiveDocument.SaveAs "e:\gcreddy.doc" mw.quit set mw=nothing 2) Create word, Create table and write all the services names ======================================== Set mw = CreateObject("Word.Application") mw.Visible = True Set dc = mw.Documents.Add() Set objRange = dc.Range() dc.Tables.Add objRange,1,3 Set objTable = dc.Tables(1) x=1 strComputer = "." Set wms=GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = wms.ExecQuery("Select * from Win32_Service") For Each s in colItems If x > 1 Then objTable.Rows.Add() End If objTable.Cell(x, 1).Range.Font.Bold = True objTable.Cell(x, 1).Range.Text = s.Name objTable.Cell(x, 2).Range.text = s.DisplayName objTable.Cell(x, 3).Range.text = s.State x=x+1 Next

3) script to display all the doc files in all the drives in the system ========================================= Dim mw Set mw=CreateObject("Word.Application") Set fs=createobject("Scripting.FileSystemObject") Set d=fs.Drives mw.FileSearch.FileName="*.doc" For each dr in d msgbox dr mw.FileSearch.LookIn=dr mw.FileSearch.SearchSubFolders=True mw.FileSearch.Execute For each i in mw.FileSearch.FoundFiles print i Set f=fs.GetFile(i) print f.Name&" "&f.Size&" "&f.DateCreated print "-------------------------------------------------------------------" Next Next mw.Quit

4) Counting the number of times a word appears in a word document =========================================

Set objWord=CreateObject("Word.Application") Set myfile=objWord.Documents.Open ("C:\Documents and Settings\gcr.GCRC-9A12FBD3D9\Desktop\xyz.doc") strText="gcreddy" strRead=myfile.Content Set RegExp=new regexp regexp.ignorecase=True regexp.global=True regexp.pattern=strText Set matches=regexp.execute(strRead) matchesFound=matches.count msgbox matchesfound myfile.close set objFso=Nothing

VBScript to read XML

XML Scripts

Set xmlDoc = CreateObject(Msxml2.DOMDocument) xmlDoc.load(D:\gcreddy.xml) Set ElemList = xmlDoc.getElementsByTagName(segment) filepath = ElemList.item(0).getAttribute(filePath) MsgBox filepath Set ElemList = xmlDoc.getElementsByTagName(description) plot = ElemList.item(0).Text MsgBox plot How Get Root Element attributes value from XML file Function GetRootElementAttributeValueFromXML(sFileNameWithPath,sA ttribute) Why we need to ADD 2 because each attribute followed by (=) and () iLenOfValue=len(sAttribute) + 2 Set doc = XMLUtil.CreateXML() doc.LoadFile sFileNameWithPath Set root = doc.GetRootElement() IF instr(1,root,sAttribute) <= 0 then Reporter.ReportEvent micFail,sAttribute,Not Found in XML file. exitrun(0) Else sStartPos=instr(1,root,sAttribute) + iLenOfValue sEndPos=instr(sStartPos,root,"") GetRootElementAttributeValueFromXML=mid(root,sStartPos,sEndPos sStartPos) End if End Function msgbox(GetRootElementAttributeValueFromXML(c:\temp\gcreddy.xml ,MerchantId))

QTP Skills

7 Steps to Improve Skills in QTP I) QTP Testing Process In order to use QTP IDE properly, you should have good command on QTP Testing process.

a) Planning a) Analyzing the AUT b) Implementing Automation Framework c) Creating/Selecting Test cases d) Collecting Test Data e) Automation Infrastrucure development f) Tool settings Configuration & Globalization b) Generating the basic Test 1) Keyword driven methodology/Shared object repository method/Preparing the script manually 2) Descriptive programming/Programmatic Descriptions i) Entering Programmatic Descriptions Directly into Statements ii) Using Description Objects for Programmatic Descriptions iii) Retrieving Child Objects iv) Using the Index Property in Programmatic Descriptions c) Enhancing the Test a) Adding Comments b) Creating Checkpoints Programmatically c) Synchronization d) Parameterization e) Inserting Programmatic statements f) Enhancing Tests with the windows API g) Calling Functions and/or Actions d) Debugging the Test e) Running the Test f) Analyzing the Test Results g) Reporting Defects a. Manual Defect Reporting b. Tool based Defect Reporting c. Integration with Quality Center II) VB Script VbScript is the QTP Tool Default Scripting Language for applaying Progamming Logic, so learn Vbscript indepth.

Below fundamentals & Features are Important: a) VBScript Fundamentals 1)Introduction a) Scripting Languages vs. Programming Languages b) Basic Features of VBScript c) Hosting Environments & Script Engines d) Crating & running a Script 2) Variables and Constants a) VBScript data types b) Declaring Variables and Option Explicit Statement c) Assigning Values to Variables d) Scalar Variables and Array Variables e) Dynamic Arrays, Dimensional Arrays f) Constants g) Variables Vs. Constants 3) VBScript Operators a) Operator Precedence b) Arithmetic Operators c) Comparison Operators d) Concatenation Operators e) Logical Operators 4) Flow Control (I. Conditional Statements) a) VBScript Conditional Statements b) Running a state if condition is true (Single line Syntax) c) Running a block of Statements if Condition is true d) Running Certain Statements if a Condition is True and Running Others if a Condition is False e) Deciding Among Several Alternatives (IF..Else If) f) Executing a certain block of statements when two / more conditions are True (Nested If...) g) Deciding Among Several Alternatives (Selct case Statement) 5) Flow Control (II. Looping through the code) a) Do...Loop (Loops while or until a condition is True.) b) While...Wend (Loops while a condition is True.) c) For...Next: Uses a counter to run statements a specified number of times. d) For Each...Next (Repeats a group of statements for each item in a collection or each element of an array.) e) Nested Loops

6) VBScript Procedures a) Sub Procedures b) Function Procedures c) Creating & Calling Procedures 7) Coding Conventions a) Constant Naming Conventions b) Variable Naming Conventions c) Variable Scope Prefixes d) Object Naming Conventions e) Code Commenting Conventions b) Advanced VBScript 1) VBScript Intrinsic (Pre-Defined) Functions a) Conversions b) Dates/Times c) Formatting Strings d) Input/Output e) Math f) Miscellaneous g) Rounding h) Strings i) Variants 2) Regular Expressions a) Uses for Regular Expressions b) Regular Expression Syntax c) Build a Regular Expression d) Order of Precedence e) Ordinary Characters f) Character Matching g) Anchors h) Alternation and Grouping i) Backreferences j) Regular Expression (RegExp) Object 3) File System Operations a) Computer File System b) Working with Drives and Folders c) Working with Flat Files d) Working with Word Docs e) Working with Excel Sheets 4) Database Operations

a) ActiveX Data Objects b) ADODB Connection Object & Recordset Object c) Test Database Creation & Collecting Test Data d) Databases Connections (Ms-Access, SQL Server and Oracle) e) Data Driven Testing by fetching Data from a Database f) Data Comparisons 5) Methods, Objects and Classes a) VBScript Global Methods b) QTP Methods c) FileSystemObject d) Dictionary Object e) Classes 6) Error Handling a) Error Handling Guidelines b) Error Handling in QuickTest Professional c) Error Preventing d) Synchronization e) QTP Exit Statements f) VBScript error handling vs. Recovery Scenarios g) On Error Statement h) Err Object III) Automation Framework Automation Framework is a Systamatic Approach for Automating, SoftwareTesting Process. In order to Create & Run Tests as well oraganizing & Managing Automation Resources, a well defined Framework required. Framework may vary from one company to another. Below concepts are important to learn: o Test Automation Framework o Types of Framework o Keyword Driven Framework o Framework Structure o Developing a Robust Automation Framework o Implementing & Managing Automation Resources IV) COM/DCOM Technologies

When working with QTP, It is important to know, Microsoft Applications like: o o o o MS Excel, Ms Word, Outlook Express and Internet Explorer

V) XML XML is an extremely popular and useful format. It can be used in several areas in QTP. Ex: o Exporting objects, o Environment Variables, o Data driven Testing o Data transporting etc. VI) SQL SQL Knowledge is highly recomendable in order to perform Database Testing using QTP Below concepts are important: o Database Fundamentals o Data Creation & Exporting o Database Connections o Select Statements VII) HTML, DOM In order to work with Web based Applications, It is important to femiliar with web technologies like: o HTML, DHTML o Flash o HTTP like Protocols o DOM (Documentation Object Model)

Error Handling in QTP


Error Handling: Error handling refers to the anticipation, detection, and resolution of programming, application, and communications errors. Within every Script we have to think about possible exceptions and how to handle them. Especially in the uppermost layers of the script, it is important to handle all exceptions.

Error Handling in QuickTest Professional: QTP and VBScript give the Test Engineer some tools to handle errors and Exceptions. Error Preventing: A good method for using error handling is to try to prevent them. When an error occurred, Report it in detail. When working with GUI objects, use the Window.Exist property. Every IfThen..End If statement has the Else part, the same for Select Case. Use Case Else. Error Handling Methods in QTP and VB Script: a) b) c) d) Synchronization Exist Property Recover Scenarios On Error Statement

Without an On Error statement, any run-time error that occurs is fatal: an error message is displayed, and execution stops. Whenever possible, you use structured exception handling in your code, rather than resorting to unstructured exception handling and the On Error statement. Parts: GoToline Enables the error-handling routine that starts at the line specified in the required line argument. The line argument is any line label or line number. If a run-time error occurs, control branches to the specified line, making the error handler active. The specified line must be in the same procedure as the On Error statement, or a compile-time error will occur. GoTo 0 Disables enabled error handler in the current procedure and resets it to

Nothing. GoTo -1 Disables enabled exception in the current procedure and resets it to Nothing. Resume Next Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred, and execution continues from that point. Use this form rather than On Error GoTo when accessing objects. on Error Resume Next Example1: Dim a a=1 b-2 MsgBox a + b ' displays result without showing error Example2: Function Sum(Num1, Num2) If IsNumeric(Num1) = False Or IsNumeric(Num2) = False Then On Error Resume Next Err.Raise vbObjectError + 100, "Sum Function", _ "One or more parameters are invalid." Exit Function End If Sum = Num1 +Num2 End Function Call Sum("gcreddy","QTP") 'Comes out without showing error Call Sum(100,200) ' returns sum of 100,200 as 300 e) Error Object The Err object is an intrinsic object with global scope there is no need to create an instance of it in your code. The properties of the Err object are set by the generator of an error

Visual Basic, an Automation object, or the VBScript programmer. The default property of the Err object is Number. Err.Number contains an integer and can be used by an Automation object to return an SCODE. When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a run-time error in your code, use the Raise method. The Err object's properties are reset to zero or zero-length strings ("") after an On Error Resume Next statement. The Clear method can be used to explicitly reset Err. Example: On Error Resume Next Err.Raise 6 ' Raise an overflow error. MsgBox ("Error # " & CStr(Err.Number) & " " & Err.Description) Err.Clear ' Clear the error. Err Object Properties and Methods Properties Description Property HelpContext Property HelpFile Property Number Property Source Property Methods Clear Method Raise Method

f)

Exit Statement

Open 30 to 40 Orders in Flight Reservation Window, if some records not available handle the situation Option Explicit Dim Order_Number If Not Window("Flight Reservation").Exist(3) Then SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "gcreddy" Dialog("Login").WinEdit("Password:").SetSecure "4c2e1e65bf29943393b6940f116d35231ce5fb7e" Dialog("Login").WinButton("OK").Click End If For Order_Number= 30 to 40 step 1 Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("Button").Click Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set Order_Number Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click If Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").Exist(3) Then Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click Window("Flight Reservation").Dialog("Open Order").WinButton("Cancel").Click Reporter.ReportEvent micWarning,"Res", "Up to "& Order_Number-1 &" Order only available" Exit For End If Next

VB Script for QTP


It explains VB Script in QTP orientation, It covers all most all VB Script Fundamentals and Features.

It describes, Variables, constants declarations, usage of operators, VB Script flow control statements, Procedures, Coding conventions, Regular Expressions, File system Operations, Database Operations etc..

Scripting Vs Programming
Scripting Language: Scripting Language is a Light weight language, no need to compile them separately, during execution they automatically compile an run. 1) It is an Interpreter based Language 2) Interpreter converts high level instructions into machine language line by line 3) It doesnt create executable file. 4) No need to compile the program 5) It takes less code for achieving tasks. 6) It greatly reduces development time 7) It reduces maintenance of cost 8) Implicit Support of Data Types. 9) Limited support for User Interface Design 10) Limited or No Support for Graphics Design Example Scripting Languages are: Shell, Perl, VB Script, Java Script, Python, Ruby, Rexx, PHP Etc.. Programming Language: 1) It is a compiler based Language. 2) Compiler converts the whole program in single short into machine language. 3) It Creates .exe file. Need to compile the program 4) It takes numerous lines of code 5) It increases development time 7) It Increases maintenance of cost 8) Explicit support of Data Types 9) Rich support for User Interface Design 10) Rich Support for Graphics Design

Example Programming Languages are: COBOL, Basic, C, C++, VC++, VB Etc...

VB Script Fundamentals And Features


VB Script has several purposes: a) Client side scripting in the Web (HTML)(Browser) (IE) b) Server side scripting in the Web (ASP) (Web Server)(IIS) c) Network Administration (Server OS) (WSH-Windows Script Host) d) System Administration (Client OS) (WSH-Windows Script Host) e) Test Automation (QTP) (QTP) Our QTP Point of view below are the learning objectives: a) Adding Comments b) Data types c) Declarations (Variables (Scalar and Array),Constants)) d) VB Script Operators i) Arithmetic Operators (Including Concatination operators) ii) Comparison iii) Logical e) Flow Control Statements (a. Conditional Statements) i) If...Then...Else...End If ii) Select Case...Case...Case Else...End Select f) Flow Control Statements (b. Loop Statements) i) For...Next ii) While...Wend iii) Do While/Until...Loop iV) For Each...Next g) VB Script Procedures(Functions) i) Built-in Functions(String, Array, Math,Date & Time, Conversion functions etc...)

ii) User defined 1) Sub Procedures 2) Function Procedures h) Coding Convensions -------------------i) File System Operations j) Excel sheet Operations k) database Operations l) Other VB Script Objects i) Dictionary Object ii) Word iii) Internet Explorer Object iV) RegExp Object m) Regular expressions k) Error Handling

VB Script Variables
Definition 1): Variable is a named memory location for storing program information Definition 2): A variable is a convenient placeholder that refers to a computer memory location where we can store program information that may change during the time our script is running. Purpose of Variable: a) Comparing values Example: Dim x,y,a x=100 y=100 a=x=y Msgbox a 'It returns True b) Holding Program Result

Example: Cost=Tickets*Price c) Passing parameters d) To store data that returned by functions Example: myDate=Now It returns current data & time e) To hold data Example: myName=gcreddy Declaring Variables We declare variables explicitly in our script using the Dim statement, the Public statement, and the Private statement. For example: Dim city Dim x We declare multiple variables by separating each variable name with a comma. For Example: Dim x, y, city, gcreddy We can also declare a variable implicitly by simply using its name in our script. That is notgenerally a good practice because we could misspell the variable name in one or more places, causing unexpected results when our script is run. For that reason, the Option Explicit statement is available to require explicit declaration of all variables. The Option Explicit statement should be the first statement in our script. Option Explicit Statement Forces explicit declaration of all variables in a script. Option Explicit ' Force explicit variable declaration. Dim MyVar ' Declare variable. MyInt = 10 ' Undeclared variable generates error. MyVar = 10 ' Declared variable does not generate error.

Naming Restrictions for Variables Variable names follow the standard rules for naming anything in VBScript. A variable name: a) Must begin with an alphabetic character. Dim abc 'Right Dim 9ab 'Wrong Dim ab9 'Right b) Cannot Dim abc Dim ab.c Dim ab-c Dim ab c Dim ab_c contain an embedded period. 'Right 'worng 'wrong 'wrong 'Right

c) Must not exceed 255 characters. d) Must be unique in the scope in which it is declared. Scope of Variables A variable's scope is determined by where we declare it. When we declare a variable within a procedure, only code within that procedure can access or change the value of that variable. If we declare a variable outside a procedure, we make it recognizable to all the procedures in our script. This is a script-level variable, and it has script-level scope. Example: Dim x,y,z x=10 y=20 z=x+y msgbox z 'Returns 30 Function res Dim a,b,c a=30 b=40 c=a+b+y msgbox c ' Returns 90

End Function Call res Life Time of Variables The lifetime of a variable depends on how long it exists. The lifetime of a script-level variable extends from the time it is declared until the time the script is finished running. At procedure level, a variable exists only as long as you are in the procedure. Assigning Values to Variables Values are assigned to variables creating an expression as follows: The variable is on the left side of the expression and the value you want to assign to the variable is on the right. For example: A = 200 City = Hyderabad X=100: Y=200 Scalar Variables and Array Variables A variable containing a single value is a scalar variable. A variable containing a series of values, is called an array variable. Array variables and scalar variables are declared in the same way, except that the declaration of an array variable uses parentheses () following the variable name. Example: Dim A(3) Although the number shown in the parentheses is 3, all arrays in VBScript are zero-based, so this array actually contains 4 elements. We assign data to each of the elements of the array using an index into the array. Beginning at zero and ending at 4, data can be assigned to the elements of an array as follows:

A(0) A(1) A(2) A(3)

= = = =

256 324 100 55

Similarly, the data can be retrieved from any element using an index into the particulararray element you want. For example: SomeVariable = A(4) Arrays aren't limited to a single dimension. We can have as many as 60 dimensions, although most people can't comprehend more than three or four dimensions. In the following example, the MyTable variable is a two-dimensional array consisting of 6 rows and 11 columns: Dim MyTable(5, 10) In a two-dimensional array, the first number is always the number of rows; the secondnumber is the number of columns. Dynamic Arrays We can also declare an array whose size changes during the time our script is running. This is called a dynamic array. The array is initially declared within a procedure using either the Dim statement or using the ReDim statement. However, for a dynamic array, no size or number of dimensions is placed inside the parentheses. For example: Dim MyArray() ReDim AnotherArray() To use a dynamic array, you must subsequently use ReDim to determine the number of dimensions and the size of each dimension. In the following example, ReDim sets the initial size of the dynamic

array to 25. A subsequent ReDim statement resizes the array to 30, but uses the Preserve keyword to preserve the contents of the array as the resizing takes place. ReDim MyArray(25) ReDim Preserve MyArray(30) There is no limit to the number of times we can resize a dynamic array, although if we make an array smaller, we lose the data in the elimina

VB Script Operators
Operators are used for performing mathematical, comparison and logical operations. VB Script has a full range of operators, including arithmetic operators, comparisonoperators, concatenation operators, and logical operators. Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence. 1) Arithmetic Operators: Operator Description 1) Exponentiation Operator (^) Raises a number to the power of an exponent 2) Multiplication Operator (*) Multiplies two numbers. 3) Division Operator (/) Divides two numbers and returns a floatingpoint result. 4) Integer Division Operator (\) Divides two numbers and returns an integer result. 5) Mod Operator Divides two numbers and returns only the remainder. 6) Addition Operator (+) Sums two numbers.

7) Subtraction Operator (-) Finds the difference between two numbers or indicates the negative value of a numeric expression. 8) Concatenation Operator (&) Forces string concatenation of two expressions. Example: Dim a,b,c a=10 b=3 c=a^b msgbox c '1000 c=a*b msgbox c '30 c=a/b msgbox c '3.33333333 c=a\b msgbox c '3 c=a mod b msgbox c '1 c=a-b msgbox c '7 Dim a,b,c a=10 b=2 c=3 d=c*a^b 'c=a+b msgbox d '1000 Addition (+) operator Dim a,b,c a=10 b=2

c=a+b msgbox c '12 (if both are numeric, then it adds) a="10" b=2 c=a+b msgbox c '12 (one is string another numeric, then it adds) a="10" b="2" c=a+b msgbox c '102 (if both are strings, then it concatenates) a="hydera" b="bad" c=a+b msgbox c 'hyderabad a="gagan" b=2 c=a+b msgbox c 'error Concatenation Operator Dim a,b,c a=10 b=2 c=a&b msgbox c '102 a="10" b=2 c=a&b msgbox c '102 a="10" b="2" c=a&b msgbox c '102 a="hydera" b="bad"

c=a&b msgbox c '102 2) Comparison Operators Used to compare expressions. Operator Description 1) = (Equal to) Used to compare expressions. 2) <> (Not equal to) Used to compare expressions. 3) < Less than 4) > Grater than 5) <= Less than or equal to 6) >= Greater than or equal to 7) Is Object equivalence Example: Dim x,y,z x=10 y=20 z=x=y Msgbox z 'False x=10 y=20 z=x>y Msgbox z 'False x=10 y=20 z=x>=y Msgbox z 'False x=10 y=20 z=x<>y Msgbox z 'True x=10 y=20 z=x<y Msgbox z 'True x=10

y=20 z=x<=y Msgbox z 'True 3) Concatenation Operators Operator Description 1) Addition Operator (+) Sums two numbers If Then 1) Both expressions are numeric Add. 2) Both expressions are strings Concatenate. 3) One expression is numeric and the other is a string Add. 2) Concatenation Operator (&) Forces string concatenation of two expressions.

4) Logical Operators Operator Description Syntax 1) Not Performs logical negation on an expression result= Not expression 2) And Performs a logical conjunction on two expressions. result= expression1 And expression2 3) Or Performs a logical disjunction on two expressions. result= expression1 Or expression2 4) Xor Performs a logical exclusion on two expressions. result= expression1 Xor expression2 5) Eqv Performs a logical equivalence on two expressions. result= expression1 Eqv expression2 6) Imp Performs a logical implication on two expressions. result= expression1 Imp expression2

Methods

Input and Out Put Operations


InputBox Function Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the contents of the text box. Example:

Dim Input Input = InputBox("Enter your name") MsgBox ("You entered: " & Input) MsgBox Function Displays a message in a dialog box, waits for the user to click a button, andreturns a value indicating which button the user clicked. Example: Dim MyVar MyVar = MsgBox ("Hello World!", 65, "MsgBox Example") MyVar contains either 1 or 2, depending on which button is clicked.

Conditional Statements

Flow Control (Conditional Statements)


We can control the flow of our script with conditional statements and looping statements. Using conditional statements, we can write VBScript code that makes decisions and repeats actions. The following conditional statements are available in VBScript: 1) IfThenElse Statement 2) Select Case Statement Making Decisions Using If...Then...Else The If...Then...Else statement is used to evaluate whether a condition is True or False and, depending on the result, to specify one or more statements to run. Usually the condition is an expression that uses a comparison operator to compare one value or variable with another. If...Then...Else statements can be nested to as many levels as you need. 1) Running a Statement if a Condition is True (single statement) To run only one statement when a condition is True, use the single-line syntax for the If...Then...Else statement. Dim myDate myDate = #2/13/98# If myDate < Now Then myDate = Now 2) Running Statements if a Condition is True (multiple statements) To run more than one line of code, we must use the multiple-line (or block) syntax.

This syntax includes the End If statement. Dim x x= 20 If x>10 Then msgbox "x value is: "&x msgbox "Bye Bye" End If 3) Running Certain Statements if a Condition is True and Running Others if a Condition is False We can use an If...Then...Else statement to define two blocks of executable statements: one block to run if the condition is True, the other block to run if the condition is False. Example: Dim x x= Inputbox (" Enter a value") If x>100 Then Msgbox "Hello G.C.Reddy" Msgbox "X is a Big Number" Msgbox "X value is: "&X Else Msgbox "GCR" Msgbox "X is a Small Number" Msgbox "X value is: "&X End If 4) Deciding Between Several Alternatives A variation on the If...Then...Else statement allows us to choose from several alternatives. Adding ElseIf clauses expands the functionality of the If...Then...Else statement so we can control program flow based on different possibilities. Example: Dim x x= Inputbox (" Enter a value") If x>0 and x<=100 Then Msgbox "Hello G.C.Reddy" Msgbox "X is a Small Number" Msgbox "X value is "&x Else IF x>100 and x<=500 Then Msgbox "Hello GCR"

Msgbox "X is a Medium Number" Else IF x>500 and x<=1000 Then Msgbox "Hello Chandra Mohan Reddy" Msgbox "X is a Large Number" Else Msgbox "Hello Sir" Msgbox "X is a Grand Number" End If End If End If 5) Executing a certain block of statements when two / more conditions are True (Nested If...) Example: Dim State, Region State=Inputbox ("Enter a State") Region=Inputbox ("Enter a Region") If state= "AP" Then If Region= "Telangana" Then msgbox "Hello G.C.Reddy" msgbox "Dist count is 10" Else if Region= "Rayalasema" Then msgbox "Hello GCR" msgbox "Dist count is 4" Else If Region= "Costal" Then msgbox "Hello Chandra mohan Reddy" msgbox "Dist count is 9" End If End If End If End If Making Decisions with Select Case The Select Case structure provides an alternative to If...Then...ElseIf for selectively executing one block of statements from among multiple blocks of statements. A Select Case statement provides capability similar to the If...Then...Else statement, but it makes code more efficient and readable. Example: Option explicit

Dim x,y, Operation, Result x= Inputbox (" Enter x value") y= Inputbox ("Enter y value") Operation= Inputbox ("Enter an Operation") Select Case Operation Case "add" Result= cdbl (x)+cdbl (y) Msgbox "Hello G.C.Reddy" Msgbox "Addition of x,y values is "&Result Case "sub" Result= x-y Msgbox "Hello G.C.Reddy" Msgbox "Substraction of x,y values is "&Result Case "mul" Result= x*y Msgbox "Hello G.C.Reddy" Msgbox "Multiplication of x,y values is "&Result Case "div" Result= x/y Msgbox "Hello G.C.Reddy" Msgbox "Division of x,y values is "&Result Case "mod" Result= x mod y Msgbox "Hello G.C.Reddy" Msgbox "Mod of x,y values is "&Result Case "expo" Result= x^y Msgbox "Hello G.C.Reddy" Msgbox"Exponentation of x,y values is "&Result Case Else Msgbox "Hello G.C.Reddy" msgbox "Wrong Operation" End Select

Looping Through Code

Flow Control (Loop Statements)


o Looping allows us to run a group of statements repeatedly. o Some loops repeat statements until a condition is False;

o Others repeat statements until a condition is True. o There are also loops that repeat statements a specific number of times. The following looping statements are available in VBScript: o Do...Loop: Loops while or until a condition is True. o While...Wend: Loops while a condition is True. o For...Next: Uses a counter to run statements a specified number of times. o For Each...Next: Repeats a group of statements for each item in a collection or each element of an array. 1) Using Do Loops We can use Do...Loop statements to run a block of statements an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True. a) Repeating Statements While a Condition is True Repeats a block of statements while a condition is True or until a condition becomes True i) Do While condition Statements --------------------Loop Or, we can use this below syntax: Example: Dim x Do While x<5 x=x+1 Msgbox "Hello G.C.Reddy" Msgbox "Hello QTP" Loop ii) Do Statements --------------------Loop While condition Example: Dim x x=1 Do

Msgbox "Hello G.C.Reddy" Msgbox "Hello QTP" x=x+1 Loop While x<5 b) Repeating a Statement Until a Condition Becomes True iii) Do Until condition Statements --------------------Loop Or, we can use this below syntax: Example: Dim x Do Until x=5 x=x+1 Msgbox "G.C.Reddy" Msgbox "Hello QTP" Loop Or, we can use this below syntax: iv) Do Statements --------------------Loop Until condition Or, we can use this below syntax: Example: Dim x x=1 Do Msgbox Hello G.C.Reddy Msgbox "Hello QTP" x=x+1 Loop Until x=5 2 While...Wend Statement Executes a series of statements as long as a given condition is True. Syntax: While condition Statements ---------------------

Wend Example: Dim x x=0 While x<5 x=x+1 msgbox "Hello G.C.Reddy" msgbox "Hello QTP" Wend 3) For...Next Statement Repeats a group of statements a specified number of times. Syntax: For counter = start to end [Step step] statements Next Example: Dim x For x= 1 to 5 step 1 Msgbox "Hello G.C.Reddy" Next 4) For Each...Next Statement Repeats a group of statements for each element in an array or collection. Syntax: For Each item In array Statements Next Example: (1 Dim a,b,x (3) a=20 b=30 x(0)= "Addition is "& a+b x(1)="Substraction is " & a-b x(2)= "Multiplication is " & a*b x(3)= "Division is " & a/b For Each element In x msgbox element Next

Example: (2 MyArray = Array("one","two","three","four","five") For Each element In MyArray msgbox element Next

VB Script Procedures

User Defined Functions


In VBScript, there are two kinds of procedures available; the Sub procedure and the Function procedure. 1) Sub Procedures A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform actions but don't return a value. A Sub procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure). If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses (). Syntax: Sub Procedure name () Statements --------------------End Sub Or Sub Procedure name (argument1, argument2) Statements --------------------End Sub Example: 1 Sub ConvertTemp() temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperature is " & Celsius(temp) & " degrees C." End Sub Example: 2

2) Function Procedures A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but can also return a value. A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant. Syntax: Function Procedure name () Statements --------------------End Function Or Function Procedure name (argument1, argument2) Statements --------------------End Function Example: 1 Function Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9 End Function Example: 2 Function cal(a,b,c) cal = (a+b+c) End Function 3) Getting Data into and out of Procedures o Each piece of data is passed into our procedures using an argument.

o Arguments serve as placeholders for the data we want to pass into ourprocedure. We can name our arguments any valid variable name. o When we create a procedure using either the Sub statement or the Function statement, parentheses must be included after the name of the procedure. o Any arguments are placed inside these parentheses, separated by commas. 4) Using Sub and Function Procedures in Code A Function in our code must always be used on the right side of a variable assignment or in an expression. For example: Temp = Celsius(fDegrees) -OrMsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees." To call a Sub procedure from another procedure, type the name of the procedurealong with values for any required arguments, each separated by a comma. The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses. The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other doesn't. Both do exactly the same thing. Call MyProc(firstarg, secondarg) MyProc firstarg, secondarg Notice that the parentheses are omitted in the call when the Call statement isn't used. 5) Examples: (here, I used Flight Reservation Application for creating Functions, why because, It is the default application for QTP, anybody can practice easily...G C Reddy) '******************************************* ' Login Operation '******************************************* Function Login(Agent,Pwd)

SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe" Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set Agent Dialog("Login").WinEdit("Password:").Set Pwd Dialog("Login").WinButton("OK").Click If Window("Flight Reservation").Exist(10) Then Login="Login Operation Sucessful" 'Msgbox Login else Login="Login Operation Unsucessful" Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click Dialog("Login").WinButton("Cancel").Click 'Msgbox Login End If End Function '*************************************** ' Closing Application '*************************************** Function Close_App() if Window("Flight Reservation").Exist(3) Then Window("Flight Reservation").Close End If End Function '*************************************** ' Open Order '*************************************** Function Open_Order(ord) ordnum=0 On Error Resume Next Window("Flight Reservation").Activate Window("Flight Reservation").WinButton("Button").Click Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set ord Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click ordnum=Window("Flight Reservation").WinEdit("Order No:").GetROProperty ("text") ordnum=cdbl (ordnum) If ord=ordnum Then Open_Order= "Order Number "&ordnum&" Opened Sucuessfully"

'Msgbox Open_Order else Open_Order= "Order Number "&ordnum&" Not Opened/ Not Available" Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click Window("Flight Reservation").Dialog("Open Order").WinButton("Cancel").Click 'Msgbox Open_Order End If End Function '****************************************** ' Update Order '****************************************** Function Update_Order(Tickets) Window("Flight Reservation").Activate Window("Flight Reservation").WinEdit("Tickets:").Set Tickets Window("Flight Reservation").WinButton("Update Order").Click wait(10) update=Window("Flight Reservation").ActiveX("Threed Panel Control").GetROProperty ("text") If update="Update Done..." Then Update_Order= "Order Updated Sucussfully" 'Msgbox Update_Order Else Window("Flight Reservation").Dialog("Flight Reservations").WinButton("OK").Click Update_Order= "Order Not Updated" 'Msgbox Update_Order End If End Function '****************************************** ' Function to send a mail '****************************************** Function SendMail(SendTo, Subject, Body, Attachment) Set otl=CreateObject("Outlook.Application") Set m=otl.CreateItem(0) m.to=SendTo m.Subject=Subject m.Body=Body If (Attachment <> "") Then Mail.Attachments.Add(Attachment) End If m.Send otl.Quit

Set m = Nothing Set otl = Nothing End Function Call SendMail("gcreddy@gcreddy.com","hi","This is test mail for testing","")

VB Script Errors

Generally Errors in VB Script are 2 Types

1) VB Script Run-time Errors VB Script run-time errors are errors that result when your VBScript script attempts to perform an action that the system cannot execute. VBScript run-time errors occur while your script is being executed; when variable expressions are being evaluated, and memory is being dynamic allocated. Error Number Description: 429 ActiveX component can't create object 507 An exception occurred 449 Argument not optional 17 Can't perform requested operation 430 Class doesn't support Automation 506 Class not defined 11 Division by zero 48 Error in loading DLL 5020 Expected ')' in regular expression 5019 Expected ']' in regular expression 432 File name or class name not found during Automation operation 92 For loop not initialized 5008 Illegal assignment 51 Internal error 505 Invalid or unqualified reference 481 Invalid picture 5 Invalid procedure call or argument 5021 Invalid range in character set 94 Invalid use of Null 448 Named argument not found 447 Object doesn't support current locale setting 445 Object doesn't support this action 438 Object doesn't support this property or method 451 Object not a collection 504 Object not safe for creating 503 Object not safe for initializing

502 Object not safe for scripting 424 Object required 91 Object variable not set 7 Out of Memory 28 Out of stack space 14 Out of string space 6 Overflow 35 Sub or function not defined 9 Subscript out of range 5017 Syntax error in regular expression 462 The remote server machine does not exist or is unavailable 10 This array is fixed or temporarily locked 13 Type mismatch 5018 Unexpected quantifier 500 Variable is undefined 458 Variable uses an Automation type not supported in VBScript 450 Wrong number of arguments or invalid property assignment 2) VB Script Syntax Errors VBScript syntax errors are errors that result when the structure of one of yourVBScript statements violates one or more of the grammatical rules of theVBScript scripting language. VBScript syntax errors occur during the program compilation stage, before the program has begun to be executed. Error Number Description: 1052 1044 1053 1058 1057 1005 1006 1011 1021 1047 1025 1014 1023 1015 1010 1012 1046 1026 Cannot have multiple default property/method in a Class Cannot use parentheses when calling a Sub Class initialize or terminate do not have arguments 'Default' specification can only be on Property Get 'Default' specification must also specify 'Public' Expected '(' Expected ')' Expected '=' Expected 'Case' Expected 'Class' Expected end of statement Expected 'End' Expected expression Expected 'Function' Expected identifier Expected 'If' Expected 'In' Expected integer constant

1049 Expected Let or Set or Get in property declaration 1045 Expected literal constant 1019 Expected 'Loop' 1020 Expected 'Next' 1050 Expected 'Property' 1022 Expected 'Select' 1024 Expected statement 1016 Expected 'Sub' 1017 Expected 'Then' 1013 Expected 'To' 1018 Expected 'Wend' 1027 Expected 'While' or 'Until' 1028 Expected 'While,' 'Until,' or end of statement 1029 Expected 'With' 1030 Identifier too long 1014 Invalid character 1039 Invalid 'exit' statement 1040 Invalid 'for' loop control variable 1013 Invalid number 1037 Invalid use of 'Me' keyword 1038 'loop' without 'do' 1048 Must be defined inside a Class 1042 Must be first statement on the line 1041 Name redefined 1051 Number of arguments must be consistent across properties specification 1001 Out of Memory 1054 Property Set or Let must have at least one argument 1002 Syntax error 1055 Unexpected 'Next' 1015 Unterminated string constant

Built-In Functions of VB Script


o Conversions (25) o Dates/Times (19) o Formatting Strings (4) o Input/Output (3) o Math (9)

o Miscellaneous (3) o Rounding (5) o Strings (30) o Variants (8)

Important Functions
1) Abs Function Returns the absolute value of a number. Dim num num=abs(-50.33) msgbox num 2) Array Function Returns a variant containing an Array Dim A A=Array("hyderabad","chennai","mumbai") msgbox A(0) ReDim A(5) A(4)="nellore" msgbox A(4) 3) Asc Function Returns the ANSI character code corresponding to the first letter in a string. Dim num num=Asc("A") msgbox num * It returns the value 65 * 4) Chr Function Returns the character associated with the specified ANSI character code. Dim char Char=Chr(65)

msgbox char * It returns A * 5) CInt Function Returns an expression that has been converted to a Variant of subtype Integer. Dim num num=123.45 myInt=CInt(num) msgbox MyInt 6) Date Function Returns the Current System Date. Dim mydate mydate=Date msgbox mydate 7) Day Function Ex1) Dim myday myday=Day("17,December,2009") msgbox myday Ex2) Dim myday mydate=date myday=Day(Mydate) msgbox myday 8) DateDiff Function Returns the number of intervals between two dates. Dim Date1, Date2, x Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("yyyy", Date1, Date2) Msgbox x 'Differnce in Years Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("q", Date1, Date2) Msgbox x 'Differnce in Quarters

Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("m", Date1, Date2) Msgbox x 'Differnce in Months Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("w", Date1, Date2) Msgbox x 'Differnce in weeks Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("d", Date1, Date2) Msgbox x 'Differnce in days Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("h", Date1, Date2) Msgbox x 'Differnce in Hours Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("n", Date1, Date2) Msgbox x 'Differnce in Minutes Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("s", Date1, Date2) Msgbox x 'Differnce in Seconds Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("y", Date1, Date2) Msgbox x 'Differnce in day of years Date1=#10-10-09# Date2=#10-10-11# x=DateDiff("a", Date1, Date2) Msgbox x 'Error Date1=#10-10-09# Date2=#10-10-11#

x=DateDiff(Date1, Date2) Msgbox x 'Error 9) Hour Function Returns a whole number between 0 and 23, inclusive, representing the hour of the day. Dim mytime, Myhour mytime=Now myhour=hour (mytime) msgbox myhour 10) Join Function Returns a string created by joining a number of substrings contained in an array. Dim mystring, myarray(3) myarray(0)="Chandra " myarray(1)="Mohan " myarray(2)="Reddy" mystring=Join(MyArray) msgbox mystring 11) Eval Function Evaluates an expression and returns the result. 12) Time Function Returns a Variant of subtype Date indicating the current system time. Dim mytime mytime=Time msgbox mytime 13) VarType Function Returns a value indicating the subtype of a variable. Dim x,y x=100 y=VarType(x) Msgbox y '2 (Integer)

x="Hyderabad" y=VarType(x) Msgbox y '8 (String) x=#10-10-10# y=VarType(x) Msgbox y '7(Date format) x=100.56 y=VarType(x) Msgbox y ' 5(Double)

y=VarType(a) Msgbox y '0 (Empty) Set x =CreateObject("Scripting.FileSystemObject") y=VarType(x) Msgbox y '9(Automation Object) 14) Left Function Dim Val, x,y Val="Hyderabad" x=Left(Val,3) Msgbox x 'Hyd Val=100 x=Left(Val,1) Msgbox x '1 Val="Hyderabad" x=Left(Val,0) Msgbox x 'Null Val="Hyderabad" x=Left(Val,12) Msgbox x 'Hyderabad Val=#10-10-10# x=Left(Val,3) Msgbox x '10/

Val="Hyderabad" x=Left(Val) Msgbox x 'Error (Lengnth is Manditory) 14) Right Function Dim AnyString, MyStr AnyString = "Hello World" ' Define string. MyStr = Right(AnyString, 1) ' Returns "d". MyStr = Right(AnyString, 6) ' Returns " World". MyStr = Right(AnyString, 20) ' Returns "Hello World". 15) Len Function Returns the number of characters in a string or the number of bytes required to store a variable. Ex 1): Dim Mystring mystring=Len("G.C.Reddy") msgbox mystring Ex 2): Dim Mystring Mystring=Inputbox("Enter a Value") Mystring=Len(Mystring) Msgbox Mystring 16) Mid Function Returns a specified number of characters from a string. Dim Val, x,y Val="Hyderabad" x=Mid(Val,3,4) Msgbox x 'dera Val=100 x=Mid(Val,1) Msgbox x '100 Val="Hyderabad" x=Mid(Val,6,7) Msgbox x 'abad Val="Hyderabad"

x=Mid(Val,6,1) Msgbox x 'a Val="Hyderabad" x=Mid(Val,6,0) Msgbox x 'Null Val="Hyderabad" x=Mid(Val,12) Msgbox x 'Null Val=#10-10-10# x=Mid(Val,3,3) Msgbox x '/10 Val=#2010-10-10# x=Mid(Val,5) Msgbox x '/2010 Val="Hyderabad" x=Mid(Val) Msgbox x 'Error 17) Timer Function Returns the number of seconds that have elapsed since 12:00 AM (midnight). Function myTime(N) Dim StartTime, EndTime StartTime = Timer For I = 1 To N Next EndTime = Timer myTime= EndTime - StartTime msgbox myTime End Function Call myTime(2000) 17) isNumeric Function Dim MyVar, MyCheck MyVar = 53

MyCheck = IsNumeric(MyVar) msgbox MyCheck MyVar = "459.95" MyCheck = IsNumeric(MyVar) msgbox MyCheck MyVar = "45 Help" MyCheck = IsNumeric(MyVar) msgbox MyCheck * It Returns True/False like Result * 18) Inputbox Function Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the contents of the text box. Dim Input Input = InputBox("Enter your name") MsgBox ("You entered: " & Input) 19) Msgbox Function Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked. Dim MyVar MyVar = MsgBox ("Hello World!", 65, "MsgBox Example") 20) CreateObject

creates and returns reference of the filesytemobject to an Automation object. It can be used for performing operations on computer file system Set objFso=createobject ("Scripting.FileSystemObject") 'creates and returns reference of the Excel bject to an Automation object. It can be used for performing operations on Spreed sheet (MsExcel files) Set objExcel = CreateObject("Excel.Application") 'creates and returns reference of the Word Object to an Automation object. It can be used for performing operations on Ms-Word documents

Set objWord = CreateObject("Word.Application") 'creates and returns reference of the Database Connection to an Automation object. It can be used for Connecting, opening and Closing databases Set objConnection = CreateObject("ADODB.Connection")

'creates and returns reference of the Database Recordset to an Automation object. It can be used for performing operations on database tables(Records) Set objRecordSet = CreateObject("ADODB.Recordset") 'creates and returns reference of the Ms-Power point object to an Automation object. It can be used for performing operations on Power point presentations Set objPPT = CreateObject("PowerPoint.Application") Set xmldoc = WScript.CreateObject("msxml2.domdocument")
21) Round Returns a number rounded to a specified number of decimal places. Dim num num=172.499 num=Round(num) msgbox num 22) StrReverse It returns reverse value of the given sring x=strreverse ("dabaraedyh") msgbox x 23) strComp It compares two strings based on ASCII Values and Returens -1 (1st less than 2nd ), 0 (Equal) and 1 (1st greater than 2nd) Dim x, y x="cd": y="bcd"

comp=strcomp(x,y) msgbox comp 24) Replace It replace a sub string with given value (another sub string) mystring=Replace("kb script", "k","v") msgbox mystring

User Defined Functions


---------------------------------------------------------i) Launching Application
Navigation: a) Launch the Browser b) Enter / Select the URL (www.jjperfumes.com) Verification: Capture the Browser Name and Verify Function Launch_App() SystemUtil.Run C:\Program Files\Internet Explorer\IEXPLORE.EXE,",C:\Documents and Settings\Administrator,open Browser(Google).Page(Google).Sync Browser(Google).Navigate http://www.jjperfumes.com/ Wait (8) Browser_Name = Browser(Google).GetROProperty(title) If Browser_Name=JJ Perfumes-Discount perfume cheap brand name perfumes, fragrance & cologne online Then Launch_App=Jjperumes.com Browser Launched Sucessfully Msgbox Launch_App Else Launch_App=Jjperumes.com Browser Not Launched Msgbox Launch_App End If End Function

ii) Customer Registration


Pre-Setup: Launching Application Navigation: a) Select Registration Link in jjperfumes.com homepage b) Enter all Mandatory details c) Select Submit button Verify: Capture confirmation Message and Verify Function Register(Email) Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount

perfume).Link(Register).Click Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebList(usertype).Select Retailer Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebEdit(firstname).Set dfgdg Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebEdit(lastname).Set dgdfgdfg Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebList(gender).Select Male Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebEdit(address1).Set dfgfdgf Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebEdit(phone).Set 9222222223 Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebEdit(email).Set Email Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebEdit(city).Set chennai Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebList(state).Select MS MISSISSIPPI Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebEdit(zip).Set 23456 Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebEdit(password).SetSecure 3c30bbc7daa0dccb83c2941bb87fa0709d34 Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebEdit(conPass).SetSecure 3c30bbcdb1f7a32d27a56f70a60f7d1e4159 Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebButton(Submit).Click Wait (5) Confirm_Message = Browser(JJ Perfumes-Discount perfume).Page(JJ PerfumesDiscount perfume_3).WebElement(Registered successfully.).GetROProperty(innertext) If Confirm_Message=Registered successfully. Then Register=Customer Registration Sucessful Msgbox Register Else Register=Registration Failed Msgbox Register End If End Function -

Function Register(Email) Set myBrowser=Browser(JJ Perfumes-Discount perfume).Page(JJ PerfumesDiscount perfume_2) Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume).Link(Register).Click myBrowser.WebList(usertype).Select Retailer myBrowser.WebEdit(firstname).Set dfgdg myBrowser.WebEdit(lastname).Set dgdfgdfg myBrowser.WebList(gender).Select Male myBrowser.WebEdit(address1).Set dfgfdgf myBrowser.WebEdit(phone).Set 9222222223 myBrowser.WebEdit(email).Set Email myBrowser.WebEdit(city).Set chennai myBrowser.WebList(state).Select MS MISSISSIPPI myBrowser.WebEdit(zip).Set 23456 myBrowser.WebEdit(password).SetSecure 3c30bbc7daa0dccb83c2941bb87fa0709d34 myBrowser.WebEdit(conPass).SetSecure 3c30bbcdb1f7a32d27a56f70a60f7d1e4159 myBrowser.WebButton(Submit).Click Wait (5) Confirm_Message = Browser(JJ Perfumes-Discount perfume).Page(JJ PerfumesDiscount perfume_3).WebElement(Registered successfully.).GetROProperty(innertext) If Confirm_Message=Registered successfully. Then Register=Customer Registration Sucessful Msgbox Register Else Register=Registration Failed Msgbox Register End If End Function

iii) Login Operation


Pre-Requisites: a) Launching Application b) Customer Registration Navigation: a) Select Login Link in jjperfumes.com homepage b) Enter Email and Password c) Select Login Button Verify: Check existence of LogOut Link

Function Login(Email, Pwd) Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume).Link(Login).Click Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebEdit(username).Set Email Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebEdit(password).Set Pwd Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_2).WebButton(Login).Click If Browser(JJ Perfumes-Discount perfume).Page(JJ Perfumes-Discount perfume_3).Link(Logout).Exist(10) Then Login=Login Operation Sucessful Msgbox Login Else Login=Login Failed Msgbox Login End If End Function

iv) Closing Application


Navigation: a) Check the Existence of jjperfumes.com Browser b) Close the Browser window (If exists) Function Launch_App() SystemUtil.Run C:\Program Files\Internet Explorer\IEXPLORE.EXE,",C:\Documents andSettings\Administrator,open Browser(Google).Page(Google).Sync Browser(Google).Navigate http://www.jjperfumes.com/ Wait (8) Browser_Name = Browser(Google).GetROProperty(title) If Browser_Name=JJ Perfumes-Discount perfume cheap brand name perfumes, fragrance & cologne online Then Launch_App=Jjperumes.com Browser Launched Sucessfully Msgbox Launch_App Else Launch_App=Jjperumes.com Browser Not Launched Msgbox Launch_App End If End Function **********************************************************

v) Login Operation In Flight Reservation Application


Function Login (Agent, Password) SystemUtil.Run C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe,",C:\Program Files\HP\QuickTest Professional\samples\flight\app\,open Dialog(Login).Activate Dialog(Login).WinEdit(Agent Name:).Set Agent Dialog(Login).WinEdit(Password:).Set Password wait 2 Dialog(Login).WinButton(OK).Click If Window(Flight Reservation).Exist(12) Then Window(Flight Reservation).Close Login=Login Operation Sucessful Msgbox Login Else SystemUtil.CloseDescendentProcesses If Dialog(Login).Dialog(Flight Reservations).Exist(2) Then Dialog(Login).Dialog(Flight Reservations).WinButton(OK).Click Dialog(Login).WinButton(Cancel).Click End if Login=Login Failed Msgbox Login End if End Function

vi) Open Order In Flight Reservation Application


Function Open_Order(Order_Number) Window(Flight Reservation).Activate Window(Flight Reservation).WinButton(Button).Click Window(Flight Reservation).Dialog(Open Order).WinCheckBox(Order No.).Set ON Window(Flight Reservation).Dialog(Open Order).WinEdit(Edit).Set Order_Number Window(Flight Reservation).Dialog(Open Order).WinButton(OK).Click OrdNum = Window(Flight Reservation).WinEdit(Order No:).GetVisibleText() OrdNum=CInt(OrdNum) If OrdNum=Order_Number Then Open_Order= Order_Number& Opened sucessfully Msgbox Open_Order Else Open_Order= Order_Number& Not Opened Msgbox Open_Order End If

End Function

vii) Update Order In Flight Reservation Application


Function Update_Order(Tickets) Window(Flight Reservation).Activate Window(Flight Reservation).WinButton(Button).Click Window(Flight Reservation).Dialog(Open Order).WinCheckBox(Order No.).Set ON Window(Flight Reservation).Dialog(Open Order).WinEdit(Edit).Set 2 Window(Flight Reservation).Dialog(Open Order).WinButton(OK).Click Window(Flight Reservation).WinEdit(Tickets:).Set Tickets Window(Flight Reservation).WinButton(Update Order).Click Wait (10) Message = Window(Flight Reservation).ActiveX(Threed Panel Control).GetROProperty(text) If Message=Update Done Then Update_Order=Order Updated Sucessfully Msgbox Update_Order Else Update_Order=Order Not Updated Msgbox Update_Order End If End Function

viii) Write Function to Count how many Browsers opened on desktop and close them all
Function Close_Browsers() Dim oBrowser, Browsers, TotBrowsers, i Set oBrowser=Description.Create oBrowser(micclass).Value=Browser Set Browsers=Desktop.ChildObjects(oBrowser) TotBrowsers=Browsers.Count Msgbox TotBrowsers For i= 0 to TotBrowsers-1 Step 1 Browsers(i).close Next End Function

ix) Write Function to Count how many Buttons available in FR Window


Function Count_Buttons() Dim oButton, Buttons, TotButtons, i Set oButton=Description.Create

oButton(Class Name).Value=WinButton Set Buttons=Window(text:=Flight Reservation).ChildObjects(oButton) TotButtons=Buttons.Count Msgbox TotButtons End Function Call Count_Buttons()

x) Write Function to Count how many Objects available in FR Window by specified Test Object class
Function Count_Objects(Object) Dim obj, Objects, TotObjects, i Set obj=Description.Create obj(Class Name).Value=Object Set Objects=Window(text:=Flight Reservation).ChildObjects(obj) TotObjects=Objects.Count Msgbox TotObjects End Function Call Count_Objects(WinRadioButton) Call Count_Objects(WinButton) Call Count_Objects(WinEdit) Call Count_Objects(WinComboBox)

xi) Write function to capture all button names one by one from Login Dialog Box
Function Capture_Buttons() Dim oButton, Buttons, TotButtons, i, myButton Set oButton=Description.Create oButton(Class Name).Value=WinButton Set Buttons=Dialog(text:=Login).ChildObjects(oButton) TotButtons=Buttons.Count For i= 0 to TotButtons-1 myButton=Buttons(i).GetRoProperty(text) Msgbox myButton Next End Function Call Capture_Buttons()

xii) Write function to Count Howmany Links available in Google Homepage


Function Count_Links() Dim oLink, Links, TotLinks, i Set oLink=Description.Create oLink(micclass).Value=Link

Set Links=Browser(title:=Google).Page(title:=Google).ChildObjects(oLink) TotLinks=Links.Count Msgbox TotLinks End Function Call Count_Links() -

VB Script Objects
a) FileSystemObject Scripting allows us to process drives, folders, and files using the FileSystemObject (FSO)object model. Creating FileSystemObject: Set Variable=CreateObject("Scripting.FileSystemObject") Example: Dim objFso Set objFso=CreateObject("Scripting.FileSystemObject") objFso.CteateTextFile("D:\gcreddy.txt") b) Dictionary Creating Dictionary Object: Set Variable=CreateObject("Scripting.Dictionary") Example: c) Excel Application Creating Excel Object: Set Variable=CreateObject("Excel.Application") Example: d) Word Application

Creating Word Object: Set Variable=CreateObject("Word.Application") Example: e) Shell Creating Shell Object: Set Variable= WScript.CreateObject("Wscript.Shell") Example: f) Network Creating Network Object: Set Variable= WScript.CreateObject("WScript.Network") Example: g) PowerPoint Creating PowerPointObject: Set Variable=CreateObject("PowerPoint.Application") Example: h) ADODB Connection The ADO Connection Object is used to create an open connection to a data source. Through this connection, you can access and manipulate a database. Creating Database Connection Object: Set Variable=CreateObject("ADODB.Connection") Example: i) ADODB RecordSet

The ADO Recordset object is used to hold a set of records from a database table. A Recordset object consist of records and columns (fields). Creating Database RecordSet Object: Set Variable=CreateObject("ADODB.RecordSet") Example: j) ADODB Command The ADO Command object is used to execute a single query against a database. The query can perform actions like creating, adding, retrieving, deleting or updating records. Creating Database Command Object: Set Variable=CreateObject("ADODB.Command") Example: k) Error Creating Error Object: l) RegExp

Creating RegExp Object: Set objReg=CreateObject("vbscript.regexp") m) Internet Explorer

n) Outlook Express a) Dictionary Object

Dictionary Object that stores data key, item pairs. A Dictionary object is the equivalent of a PERL associative array/Hash Variable. Items can be any form of data, and are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually an integer or a string, but can be anything except an array.

Creating a Dictionary Object:


Set objDictionary = CreateObject("Scripting.Dictionary")

Dictionary Objects Methods:

Add Method Adds a key and item pair to a Dictionary object Exists Method Returns true if a specified key exists in the Dictionary object, false if it does not. Items Method Returns an array containing all the items in a Dictionary object. Keys Method Returns an array containing all existing keys in a Dictionary object. Remove Method Removes a key, item pair from a Dictionary object. RemoveAll Method The RemoveAll method removes all key, item pairs from a Dictionary object.

Example:

Dim cities Set cities = CreateObject("Scripting.Dictionary") cities.Add "h", "Hyderabad" cities.Add "b", "Bangalore" cities.Add "c", "Chennai"

Dictionary Objects Properties: Count Property Returns the number of items in a collection or Dictionary object. Readonly. CompareMode Property Sets and returns the comparison mode for comparing string keys in a Dictionary object. Key Property Sets a key in a Dictionary object. Item Property Sets or returns an item for a specified key in a Dictionary object. For collections, returnsan item based on the specified key. Read/write. Examples:

atoElements1) AddDictionary

SetobjDictionary=CreateObject("Scripting.Dictionary") objDictionary.Add"Printer1","Printing" objDictionary.Add"Printer2","Offline" objDictionary.Add"Printer3","Printing" 2) Delete All aElements fromDictionary

SetobjDictionary=CreateObject("Scripting.Dictionary")

objDictionary.Add"Printer1","Printing" objDictionary.Add"Printer2","Offline" objDictionary.Add"Printer3","Printing" colKeys=objDictionary.Keys Wscript.Echo"Firstrun:" ForEachstrKeyincolKeys Wscript.EchostrKey Next objDictionary.RemoveAll colKeys=objDictionary.Keys Wscript.EchoVbCrLf&"Secondrun:" ForEachstrKeyincolKeys Wscript.EchostrKey Next 3) Delete One Element from a Dictionary Set objDictionary = CreateObject("Scripting.Dictionary") objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing" colKeys = objDictionary.Keys Wscript.Echo "First run: " For Each strKey in colKeys Wscript.Echo strKey Next objDictionary.Remove("Printer 2") colKeys = objDictionary.Keys Wscript.Echo VbCrLf & "Second run: " For Each strKey in colKeys Wscript.Echo strKey Next

4) List the Number of Items in a Dictionary

SetobjDictionary=CreateObject("Scripting.Dictionary") objDictionary.Add"Printer1","Printing" objDictionary.Add"Printer2","Offline" objDictionary.Add"Printer3","Printing" Wscript.EchoobjDictionary.Count

5) Verify the Existence of a Dictionary Key Set objDictionary = CreateObject("Scripting.Dictionary") objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing" If objDictionary.Exists("Printer 4") Then Wscript.Echo "Printer 4 is in the Dictionary." Else Wscript.Echo "Printer 4 is not in the Dictionary." End If

VB Script General Examples


1) Write a program for finding out whether the given year is a leap year or not? Dim xyear xyear=inputbox ("Enter Year") If xyear mod 4=0 Then msgbox "This is a Leap year" Else msgbox "This is NOT" End If 2) Write a program for finding out whether the given number is, Even number or Oddnumber? Dim num num=inputbox ("Enter a number")

If num mod 2=0 Then msgbox "This is a Even Number" Else msgbox "This is a Odd Number" End If 3) Read two numbers and display the sum? Dim num1,num2, sum num1=inputbox ("Enter num1") num2=inputbox ("Enter num2") sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion require msgbox ("Sum is " &sum) 4) Read P,T,R values and Calculate the Simple Interest? Dim p,t, r, si p=inputbox ("Enter Principle") t=inputbox ("Enter Time") r=inputbox ("Enter Rate of Interest") si= (p*t*r)/100 ' p= principle amount, t=time in years, r= rate of interest msgbox ("Simple Interest is " &si) 5) Read Four digit number, calculate & display the sum of the number or display Error message if the number is not a four digit number? Dim num, sum num=inputbox ("Enter a Four digit number") If Len(num) = 4 Then sum=0 sum=sum+num mod 10 num=num/10 num= left (num, 3) sum=sum+num mod 10 num=num/10 num= left (num, 2) sum=sum+num mod 10 num=num/10 num= left (num, 1) sum=sum+num mod 10 msgbox ("Sum is " &sum) else msgbox "Number, you entered is not a 4 digit number"

End If 6) Read any Four-digit number and display the number in reverse order? Dim num,rev num= inputbox("Enter a number") If len(num)=4 Then rev=rev*10 + num mod 10 num=num/10 num= left(num,3) rev=rev*10 + num mod 10 num=num/10 num= left(num,2) rev=rev*10 + num mod 10 num=num/10 num= left(num,1) rev=rev*10 + num mod 10 msgbox "Reverse Order of the number is "&rev Else msgbox "Number, you entered is not a 4 digit number" End If 7) Read 4 subjects marks; calculate the Total marks and grade? a) If average marks Greater than or equal to 75, grade is Distinction b) If average marks Greater than or equal to 60 and less than 75 , then grade is First c) If average marks Greater than or equal to 50 and less than 60 , then grade is Second d) If average marks Greater than or equal to 40 and less than 50 , then grade is Third e) Minimum marks 35 for any subject, otherwise 'no grade fail') Dim e,m,p,c, tot e=inputbox ("Enter english Marks") m=inputbox ("Enter maths Marks") p=inputbox ("Enter physics Marks") c=inputbox ("Enter chemistry Marks") tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c) msgbox tot If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=300 Then msgbox "Grade is Distinction" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot

>=240 and tot<300 Then msgbox "Grade is First" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=200 and tot<240 Then msgbox "Grade is Second" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=160 and tot<200 Then msgbox "Grade is Third" else msgbox "No Grade, Fail" End If End If End If End If 8) Display Odd numbers up to n? Dim num,n n=Inputbox ("Enter a Vaule") For num= 1 to n step 2 msgbox num Next 9) Display Even numbers up to n? Dim num,n n=Inputbox ("Enter a Vaule") For num= 2 to n step 2 msgbox num Next 10) display natural numbers up to n and write in a text file? Dim num, n, fso, myfile n= inputbox ("Enter any Value") num=1 For num= 1 to n step 1 Set fso= createobject ("scripting.filesystemobject") set myfile=fso.opentextfile ("E:\gcreddy.txt", 8, true) myfile.writeline num myfile.close Next

11) Display Natural numbers in reverse order up to n? Dim num,n n=Inputbox ("Enter a Vaule") For num=n to 1 step -1 msgbox num Next 12) Display Natural numbers sum up to n? (Using For...Next Loop) Dim num, n, sum n= inputbox ("Enter a Value") sum=0 For num= 1 to n step 1 sum= sum+num Next msgbox sum 13) Display Natural numbers sum up to n? (using While...Wend Loop) Dim num, n, sum n= inputbox ("Enter a Value") While num <=cdbl (n) sum= sum+num num=num+1 Wend msgbox sum 14) Display Natural numbers sum up to n? (Using Do...Until...Loop) Dim num, n, sum n= inputbox ("Enter a Value") sum=0 num=1 Do sum= sum+num num=num+1 Loop Until num =cdbl (n+1) msgbox sum 15) Write a Function for Natural Numbers sum up to n? Function NNumCou (n)

Dim num, sum sum=0 For num= 1 to n step 1 sum= sum+num Next msgbox sum End Function 16) Verify weather the entered 10 digit value is a numeric value or not? Dim a,x,y,z,num num=Inputbox ("Enter a Phone Number") d1= left (num,1) d10=Right (num,1) d2=mid (num, 2, len (1)) d3=mid (num, 3, len (1)) d4=mid (num, 4, len (1)) d5=mid (num, 5, len (1)) d6=mid (num, 6, len (1)) d7=mid (num, 7, len (1)) d8=mid (num, 8, len (1)) d9=mid (num, 9, len (1)) If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then msgbox "It is a Numeric Value" else Msgbox "It is NOT Numeric" End If 17) Verify weather the entered value is a 10 digit value or not and Numeric value or not? (Using multiple if conditions) Dim a,x,y,z,num num=Inputbox ("Enter a Phone Number") d1= left (num,1) d10=Right (num,1) d2=mid (num, 2, len (1)) d3=mid (num, 3, len (1)) d4=mid (num, 4, len (1))

d5=mid (num, 5, len (1)) d6=mid (num, 6, len (1)) d7=mid (num, 7, len (1)) d8=mid (num, 8, len (1)) d9=mid (num, 9, len (1)) If len (num) =10 Then If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then msgbox "It is a Numeric Value" End If End If If len (num) <> 10 Then Msgbox "It is NOT valid Number " End If 18) Generate interest for 1 to 5 years (for 1 year -7%, 2 years -8%, 3 years-9%, 4 years-10%, 5 years -11%) Dim amount, duration, intr amount=inputbox("enter amount") If amount<10000 Then msgbox "low amount" else For duration=1 to 5 If duration=1 Then intr=amount*7/100 msgbox "1 year intrest is: " &intr else if duration=2 Then intr=amount*8/100 msgbox "2 years intrest is: " &intr else if duration=3 Then intr=amount*9/100 msgbox "3 years intrest is: "&intr else if duration=4 Then intr=amount*10/100 msgbox "4 years intrest is: "&intr else if duration=5 Then intr=amount*11/100

msgbox "5 years intrest is: "&intr else msgbox "invalid data" End If End If End If End If End If Next End If

VB Script General Examples


1) Read a value and find size of the value Dim val: val=Inputbox("Enter value for val: ") val_length =Len(val) msgbox "Size of "&val&" is "&val_length

2) Read a value and find whether the value is numeric or not? Dim val: val=Inputbox("Enter value for val: ") val_type =IsNumeric(val) If val_type = true Then msgbox "val is Numeric" else msgbox "val is not Numeric" End If 3)'Read a value and find whether the value is Date type data or not? Dim val: val=Inputbox("Enter value for val: ") val_type =IsDate(val) If val_type = true Then msgbox "val is Date type data" else msgbox "val is not date type" End If

4)Read a value and Verify whether the value is 10-digit number or not and started with 9 0r 8. 'Then Display it is a valid mobile number Dim val,val_Length, val_Numeric, val_Start val=Inputbox("Enter value for val: ") val_Length= Len(val) val_Numeric=IsNumeric(val) val_Start=Left(val,1) If val_Length=10 and val_Numeric and val_Start=9 or val_Start=8 Then msgbox val&" is a valid mobile number " Else msgbox val&" is not a valid mobile number " End If 5) 'Read a mobile number and verify the series 'if it starts with 92478 or 92471 then display it is TataIndicom number 'if it starts with 98490 or 98480 then display it is Airtel number Dim val, val_Length,val_Numeric,val_Series,val_Start val=Inputbox("Enter value for val: ") val_Length= Len(val) val_Numeric=IsNumeric(val) val_Start=Left(val,1) val_Series=Left(val,5) If val_Numeric=true Then If val_Length=10 and val_Start=9 Then If val_Series = 92478 or val_Series=92471 Then msgbox "It is TataIndicom Number" ElseIf val_Series=98490 or val_Series = 98480 then msgbox "It is Airtel Number" End If Else msgbox val&" is not a valid mobile number " End If Else msgbox val& " is Invalid data"

End If 6) Read a Value and Verify weather the value is started with Alfa bytes or not? (First letter should be Alfa byte) Dim val, val_Asc val=Inputbox("enter a value") val_Asc=Asc(val) Msgbox val_Asc If val_Asc>=65 and val_Asc<=90 or val_Asc>=97 and val_Asc<=122Then msgbox val&" is an Alphabet" Else msgbox val&" is not an Alphabet" End If 7) Read a value and Verify weather the value is Alfa bytes are not? Dim str, valAsc, flag,i Dim strlen, counter,valsingle counter=0 str=Inputbox("enter a string value") strlen= Len(str) For i=1 to strlen step 1 valsingle=Mid(str,i,1) valAsc=Asc(valsingle) If valAsc>=65 and valAsc<=90 or valAsc>=97 and valAsc<=122Then flag=1 counter=counter+1 Else flag=0 End If Next msgbox "No.of characters " &counter If counter=strlen and flag=1Then msgbox str&" is an Alphabetic value"

Else msgbox str&" is not an Alphabetic value" End If

You might also like