Home Techfundu is an information sharing and learning platform for information technology professionals. TechFundu members can connect with other IT Professionals and build their professional network, members can publish their technical articles, blogs and videos, members can rate and comments on articles, blogs and videos, members can create group discussions or can participate in discussions started by other members, they help each other in resolving complex technical problems, members can create their blogs, member publish tech events and register in them, member can publish tech jobs and apply for jobs. TechFundu is more much, come join us and Share, Learn, Connect and Grow with TechFundu Community. http://www.techfundu.com/ Tue, 07 Sep 2010 02:27:58 +0000 Joomla! 1.5 - Open Source Content Management en-gb Cloud Migration for Dummies: The Practical Top 10 Checklist http://www.techfundu.com/20100423100/technology-management/cloud-computing/cloud-migration-for-dummies-the-practical-top-10-checklist http://www.techfundu.com/20100423100/technology-management/cloud-computing/cloud-migration-for-dummies-the-practical-top-10-checklist
With all the talk about the cloud, and an increasing understanding of its value and importance, there are elementary steps that must be taken before migrating your application to the cloud.  For advanced developers, these may seem second nature, but with today's technological platforms that enable easy migration, it has now become possible for beginner and intermediate developers to use the cloud. These tips can be beneficial for them.
  1. Is your app a web app?  It sounds basic, but before you migrate to the web, you need to make sure that your application is a web application.  Today, there are simple tools that can easily convert it, but make sure to convert it.
  2. Is your app native .NET/Java?  Before you start to migrate your app to the cloud, understand what it is you are transferring and the technological aspects of it.  This is important because you need to know which clouds support your stack of technologies.
  3. Do you use any interop to other technologies? Prepare yourself.  If you do use any interop, it is important to make sure that those technologies are also supported by the  cloud you are targeting
  4. What database type do you use?  When you are planning to migrate, make sure that the target cloud can support the database you are using.  If not, can you change the database? Alternatively, you can consider running the application on the cloud and connect to an on-premise database; some DB vendors already support securing these channels.
  5. What kind of management/monitoring tools do you use on your app?  This is particularly important to check if your app was not originally a web app.  Not all management and monitoring tools can be used on the web (and even more so, not on the cloud), so confirm this before you start.   If your tools are not web-compatible, can you recreate them for the web?
  6. Can you assess the costs of cloud deployment of your app? Costs are an important factor when considering migrating to the cloud.  Explore whether you can optimize your costs.  For example, what are the payable elements on this specific cloud and will you be able to optimize those elements to maintain the lowest possible costs?  Some will try to scare you away from the cloud with forewarnings of high costs, but there are cost-effective ways to use the cloud.
  7. Determine the security risks that cloud deployment will reveal.  There are two steps to this.  First, review the provider's regulations and trust level.  Second, know that security hazards can be created by making the client available from any PC that is connected to the web.
  8. Upgrade costs.  Figure out what the costs and technical implications of upgrading your app are, as well as changing it after deployment.
  9. Flexibility and transferability.  Have you checked if you will be able to move between cloud providers? Are you locked into a specific provider after the app is deployed? Sometimes, when choosing a specific cloud platform, you have to make adjustments to fit their specifications.  This may put restrictions on your ability to transfer to another cloud platform.
  10. Scalability and redundancy capabilities. Are you able to provide full dynamic scalability and redundancy capabilities to the server parts of your app? It is important to realize that these are directly affected by the technologies that you use, and their ability to scale. When it comes to ability to scale, if you cannot scale dynamically, you simply can’t move to the cloud.

These are only some of the important concerns you should review after you have decided to step onto the cloud, but before you begin the migration.

Thanks to Itzik Spitzen of www.visualwebgui.com for assisting with this article.

]]>
chevy@ncsm.co.il (Chevy Weiss) frontpage Fri, 23 Apr 2010 11:46:08 +0000
Learn Oracle PL/SQL in 24 Hours http://www.techfundu.com/2009102065/database-technologies/oracle/learn-oracle-pl/sql-in-24-hours http://www.techfundu.com/2009102065/database-technologies/oracle/learn-oracle-pl/sql-in-24-hours What is PL/SQL?

PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation in the early 90’s to enhance the capabilities of SQL.

The PL/SQL Engine:

Oracle uses a PL/SQL engine to process the PL/SQL statements. A PL/SQL code can be stored in the client system (client-side) or in the database (server-side).

A Simple PL/SQL Block:

Each PL/SQL program consists of SQL and PL/SQL statements which form a PL/SQL block.

A PL/SQL Block consists of three sections:

  • The Declaration section (optional).
  • The Execution section (mandatory).
  • The Exception (or Error) Handling section (optional).

This is how a sample PL/SQL Block looks.

DECLARE
     Variable declaration
BEGIN
     Program Execution
EXCEPTION
     Exception handling
END;

 Declaration Section:
The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE. This section is optional and is used to declare any placeholders like variables, constants, records and cursors, which are used to manipulate data in the execution section.

Execution Section:
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends with END. This is a mandatory section and is the section where the program logic is written to perform any task. The programmatic constructs like loops, conditional statement and SQL statements form the part of execution section.

Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This section is optional. Any errors in the program can be handled in this section, so that the PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that cannot be handled, the Block terminates abruptly with errors.

Every statement in the above three sections must end with a semicolon; PL/SQL blocks can be nested within other PL/SQL blocks. Comments can be used to document code.

Advantages of PL/SQL

These are the advantages of PL/SQL.

  • Block Structures: PL/SQL consists of blocks of code, which can be nested within each other. Each block forms a unit of a task or a logical module. PL/SQL Blocks can be stored in the database and reused.
  • Procedural Language Capability: PL/SQL consists of procedural language constructs such as conditional statements (if else statements) and loops like (FOR loops).
  • Better Performance: PL/SQL engine processes multiple SQL statements simultaneously as a single block, thereby reducing network traffic.
  • Error Handling: PL/SQL handles errors or exceptions effectively during the execution of a PL/SQL program. Once an exception is caught, specific actions can be taken depending upon the type of the exception or it can be displayed to the user with a message.

PL/SQL Placeholders

Placeholders are temporary storage area. Placeholders can be any of Variables, Constants and Records. Oracle defines placeholders to store data temporarily, which are used to manipulate data during the execution of a PL SQL block.

Depending on the kind of data you want to store, you can define placeholders with a name and a datatype. Few of the datatypes used to define placeholders are as given below.
Number (n,m) , Char (n) , Varchar2 (n) , Date , Long , Long raw, Raw, Blob, Clob, Nclob, Bfile

PL/SQL Variables

These are placeholders that store the values that can change through the PL/SQL Block.
The General Syntax to declare a variable is:

variable_name datatype [NOT NULL := value ];

  • variable_name is the name of the variable.
  • datatype is a valid PL/SQL datatype.
  • NOT NULL is an optional specification on the variable.
  • value or DEFAULT value is also an optional specification, where you can initialize a variable.
  • Each variable declaration is a separate statement and must be terminated by a semicolon.  

For example, if you want to store the current salary of an employee, you can use a variable.  

DECLARE

salary  number (6);

 * “salary” is a variable of datatype number and of length 6.

When a variable is specified as NOT NULL, you must initialize the variable when it is declared.

For example: The below example declares two variables, one of which is a not null.

DECLARE

salary number(4);

dept varchar2(10) NOT NULL := “HR Dept”;

The value of a variable can change in the execution or exception section of the PL/SQL Block. We can assign values to variables in the two ways given below.

1) We can directly assign values to variables.
    The General Syntax is:         

  variable_name:=  value; 

2) We can assign values to variables directly from the database columns by using a SELECT.. INTO statement. The General Syntax is:

 SELECT column_name

INTO variable_name

FROM table_name

[WHERE condition];

Example: The below program will get the salary of an employee with id '1116' and display it on the screen.

DECLARE

 var_salary number(6);

 var_emp_id number(6) := 1116;

BEGIN

 SELECT salary

 INTO var_salary

 FROM employee

 WHERE emp_id = var_emp_id;

 dbms_output.put_line(var_salary);

 dbms_output.put_line('The employee '

        || var_emp_id || ' has  salary  ' || var_salary);

END;

/

NOTE: The backward slash '/' in the above program indicates to execute the above PL/SQL Block.

Scope of Variables

PL/SQL allows the nesting of Blocks within Blocks i.e, the Execution section of an outer block can contain inner blocks. Therefore, a variable which is accessible to an outer Block is also accessible to all nested inner Blocks. The variables declared in the inner blocks are not accessible to outer blocks. Based on their declaration we can classify variables into two types.

  • Local variables - These are declared in an inner block and cannot be referenced by outside Blocks.
  • Global variables - These are declared in an outer block and can be referenced by its itself and by its inner blocks.
    For Example: In the below example we are creating two variables in the outer block and assigning their product to the third variable created in the inner block. The variable 'var_mult' is declared in the inner block, so cannot be accessed in the outer block i.e. it cannot be accessed after line 11. The variables 'var_num1' and 'var_num2' can be accessed anywhere in the block.

 1> DECLARE

2>  var_num1 number;

3>  var_num2 number;

4> BEGIN

5>  var_num1 := 100;

6>  var_num2 := 200;

7>  DECLARE

8>   var_mult number;

9>   BEGIN

10>    var_mult := var_num1 * var_num2;

11>   END;

12> END;

13> / 


PL/SQL Constants
As the name implies, a constant is a value used in a PL/SQL Block that remains unchanged throughout the program. A constant is a user-defined literal value. You can declare a constant and use it instead of actual value.

For example: If you want to write a program which will increase the salary of the employees by 25%, you can declare a constant and use it throughout the program. Next time when you want to increase the salary again you can change the value of the constant which will be easier than changing the actual value throughout the program.

The General Syntax to declare a constant is:

constant_name CONSTANT datatype := VALUE;

• constant_name is the name of the constant i.e. similar to a variable name.
• The word CONSTANT is a reserved word and ensures that the value does not change.
• VALUE - It is a value which must be assigned to a constant when it is declared. You cannot assign a value later.

For example, to declare salary_increase, you can write code as follows:

DECLARE
salary_increase CONSTANT number (3) := 10;
You must assign a value to a constant at the time you declare it. If you do not assign a value to a constant while declaring it and try to assign a value in the execution section, you will get a error. If you execute the below Pl/SQL block you will get error.
DECLARE
 salary_increase CONSTANT number(3);
BEGIN
 salary_increase := 100;
 dbms_output.put_line (salary_increase);
END;

PL/SQL Records

What are records?

Records are another type of datatypes which oracle allows to be defined as a placeholder. Records are composite datatypes, which means it is a combination of different scalar datatypes like char, varchar, number etc.  Each scalar data types in the record holds a value. A record can be visualized as a row of data. It can contain all the contents of a row.

Declaring a record:
To declare a record, you must first define a composite datatype; then declare a record for that type.

The General Syntax to define a composite datatype is:

TYPE record_type_name IS RECORD
(first_col_name column_datatype,
second_col_name column_datatype, ...);
• record_type_name – it is the name of the composite type you want to define.
• first_col_name, second_col_name, etc.,- it is the names the fields/columns within the record.
• column_datatype defines the scalar datatype of the fields.

There are different ways you can declare the datatype of the fields.
1) You can declare the field in the same way, as you declare the field while creating the table.
2) If a field is based on a column from database table, you can define the field_type as follows:
col_name table_name.column_name%type;
By declaring the field datatype in the above method, the datatype of the column is dynamically applied to the field.  This method is useful when you are altering the column specification of the table, because you do not need to change the code again.
NOTE: You can use also %type to declare variables and constants.

The General Syntax to declare a record of a user-defined datatype is:

record_name record_type_name;

The following code shows how to declare a record called employee_rec based on a user-defined type.

DECLARE
TYPE employee_type IS RECORD
(employee_id number(5),
 employee_first_name varchar2(25),
 employee_last_name employee.last_name%type,
 employee_dept employee.dept%type,
 employee_salary employee.salary%type
);
 
If all the fields of a record are based on the columns of a table, we can declare the record as follows:
record_name table_name%ROWTYPE;

For example, the above declaration of employee_rec can be as follows:

DECLARE
 employee_rec employee%ROWTYPE;

The advantages of declaring the record as a ROWTYPE are:
1) You do not need to explicitly declare variables for all the columns in a table.
2) If you alter the column specification in the database table, you do not need to update the code.
The disadvantage of declaring the record as a ROWTYPE is:
1) When u create a record as a ROWTYPE, fields will be created for all the columns in the table and memory will be used to create the datatype for all the fields. So use ROWTYPE only when you are using all the columns of the table in the program.
NOTE: When you are creating a record, you are just creating a datatype, similar to creating a variable. You need to assign values to the record to use them.

Passing Values To and From a Record
When you assign values to a record, you actually assign values to the fields within it.

The General Syntax to assign a value to a column within a record directly is:
record_name.col_name := value;

We can assign values to records using SELECT Statements as shown:

SELECT col1, col2
INTO record_name.col_name1, record_name.col_name2
FROM table_name
[WHERE clause];

If %ROWTYPE is used to declare a record then you can directly assign values to the whole record instead of each column separately. In this case, you must SELECT all the columns from the table into the record as shown:

SELECT * INTO record_name
FROM table_name
[WHERE clause];

Let’s see how we can get values from a record.
The General Syntax to retrieve a value from a specific field into another variable is:
var_name := record_name.col_name;


PL/SQL Operators

Operators
PL/SQL operators are either unary or binary.
Binary operators act on two values. An example of binary operators is the addition operator, which adds two numbers together.
Unary operators only operate on one value. The negation operator is unary.
PL/SQL operators can be divided into the following categories:

Arithmetic Operators
Arithmetic operators are used for mathematical computations.
Operator Example Usage

Operator

Example

Usage

**

10**5

The exponentiation operator. 10**5 = 100,000.

*

2*3

The multiplication operator. 2 * 3 = 6.

/

6/2

The division operator. 6/2 = 3.

+

2+2

The addition operator. 2+2 = 4.

-

4-2

The subtraction operator. 4 -2 = 2.

-

-5

The negation operator.

+

+5

It complements the negation operator.

Logical Operators in PL/SQL

PL/SQL has three logical operators: AND, OR, and NOT. The NOT operator is typically used to negate the result of a comparison expression. The AND and OR operators are typically used to link together multiple comparisons.

The Syntax for the NOT Operator:
NOT boolean_expression

boolean_expression can be any expression resulting in a boolean, or true/false value.

The Syntax for the AND Operator:
boolean_expression AND boolean_expression

boolean_expression can be any expression resulting in a boolean, or true/false value.

The AND operator returns a value of true if both expressions each evaluate to true; otherwise, a value of false is returned.

 Expression

Result

(5 = 5) AND (4 = 2)

true

(5 = 7) AND (5 = 5)

false

'Mon' IN ('Sun','Sat') AND (2 = 2)

false

The Syntax for the OR Operator:
boolean_expression OR boolean_expression

boolean_expression can be any expression resulting in a boolean, or true/false, value.
The OR operator returns a value of true if any one of the expressions evaluates to true. A value of false is returned only if both the expressions evaluate to false.

Expression

Result

(5 5) OR (4 >= 100) OR (2 < 2)

false

(7 = 4) OR (5 = 5)

true

'Mon' IN ('Sun','Sat') OR (2 = 2)

true

x

y

x AND y

x OR y

NOT x

True

True

True

True

False

True

False

False

True

False

False

True

False

True

True

False

False

False

False

True


Relational (Comparison) Operators

Relational (i.e. Comparison) operators are used to compare one value or expression to another and they return Boolean result.

Operator

Example

Usage

=

IF A = B THEN

The equality operator.

 

IF A B THEN

The inequality operator.

!=

IF A != B THEN

Another inequality operator, synonymous with .

~=

IF A ~= B THEN

Another inequality operator, synonymous with .

IF A < B THEN

The less than operator.

IF A > B THEN

The greater than operator.

<=

IF A <= B THEN

The less than or equal to operator.

>=

IF A >= B THEN

The greater than or equal to operator.

LIKE

IF A LIKE B THEN

The pattern-matching operator.

BETWEEN

IF A BETWEEN B AND C THEN

Checks to see if a value lies within a specified range of values.

IN

IF A IN (B,C,D) THEN

Checks to see if a value lies within a specified list of values.

IS NULL

IF A IS NULL THEN

Checks to see if a value is null.

True Expressions

False Expressions

5 = 5

5 = 3

'AAAA' = 'AAAA'

'AAAA ' = 'AAAA'

5 != 3

5 5

'AAAA ' ~= 'AAAA'

'AAAA' ~= 'AAAA'

10 < 200

10.1 < 10.05

'Jeff' < 'Jenny'

'jeff' < 'Jeff'

TO_DATE('15-Nov-61' < '15-Nov-97')

TO_DATE('1-Jan-97' < '1-Jan-96')

10.1 <= 10.1

10 <= 20

'A' <= 'B'

'B' <= 'A'

TO_DATE('1-Jan-97') <= TO_DATE('1-Jan-97)

TO_DATE('15-Nov-61') <= TO_DATE('15-Nov-60)


String Operators

PL/SQL has two operators specifically designed to operate only on character string data. These are the LIKE operator and the concatenation (||) operator.

The Syntax for the Concatenation Operator:
string_1 || string_2

string_1 and string_2 are both character strings and can be string constants, string variables, or string expressions.

When using character strings in comparison expressions, the result depends on several things:
1. Character set
2. Data type
3. Case (upper versus lower)

In the typical ASCII environment,
1. Lowercase letters are greater than all uppercase letters,
2. Digits are less than all letters, and
3. The other characters fall in various places depending on their corresponding ASCII codes.

PL/SQL Operator Precedence

Operator

Description

**

Exponentiation

+, -

Identity, negation (unary operation)

*, /

Multiplication, division

+, -, ||

Addition, subtraction, concatenation

=, , =, , !=, ~= IS NULL, LIKE, BETWEEN, IN

Comparison

NOT

Logical negation

AND

Conjunction

OR

Inclusion

1. Operations with higher precedence are applied first.
2. Operators with the same precedence are applied in their text order.
3. You can change the execution order by using parentheses.
4. If the expression includes parentheses, the execution starts with the innermost pair.

BETWEEN
The BETWEEN operator checks if a value falls within a given range of values.

The Syntax for BETWEEN:
the_value [NOT] BETWEEN low_end AND high_end

1. the_value is the value you are testing,
2. low_end represents the low end of the range,
3. high_end represents the high end of the range.
True is returned if the_value is greater than or equal to the low end of the range and less than or equal to the high end of the range.
The equivalent expression would look like this:
(the_value >= low_end) AND (the_value <= high_end)

IN operator
The IN operator is used to check if a value is contained in a specified list of values. A true result is returned if the value is contained in the list; otherwise, the expression evaluates to false.

The Syntax for IN
the_value [NOT] IN (value1, value2, value3,...)

1. the_value is the value you are testing, and
2. value1, value2, value3,… represents a list of comma-delimited values.

Expression

Result

3 IN (0,1,2,3,)

true

'Sun' IN ('Mon','Tue')

false

'Sun' IN ('Sat','Sun')

true

3 NOT IN (0,1,2,3)

false

IS NULL operator
The IS NULL operator is used to test a NULL value. Variables you declare in a PL/SQL block are also initially null, or have no value. Variables remain null until your code specifically assigns a value to them.

The Syntax for IS NULL:
the_value IS [NOT] NULL

the_value is a variable, or another expression.
If the value is null, then the IS NULL operator returns true. You can also reverse the test by using IS NOT NULL.

LIKE operator
1. LIKE is PL/SQL's pattern-matching operator.
2. LIKE is used to compare a character string against a pattern.
3. LIKE is useful for performing wildcard searches.
4. LIKE can only be used with character strings.
5. LIKE checks to see if the contents of string_variable match the pattern definition.
6. If the string matches the pattern, a result of true is returned;
7. otherwise, the expression evaluates to false.
 The Syntax for LIKE
string_variable LIKE pattern

 


Conditional Statements in PL/SQL
As the name implies, PL/SQL supports programming language features like conditional statements, iterative statements.

The programming constructs are similar to how you use in programming languages like Java and C++. In this section I will provide you syntax of how to use conditional statements in PL/SQL programming.

IF THEN ELSE STATEMENT

1)
IF condition THEN
 statement 1;
ELSE
 statement 2;
END IF;
 
2)
IF condition 1 THEN
 statement 1;
 statement 2;
ELSIF condtion2 THEN
 statement 3;
ELSE
 statement 4;
END IF
 
3)
IF condition 1 THEN
 statement 1;
 statement 2;
ELSIF condtion2 THEN
 statement 3;
ELSE
 statement 4;
END IF;
 
4)
IF condition1 THEN
ELSE
 IF condition2 THEN
 statement1;
 END IF;
ELSIF condition3 THEN
  statement2;
END IF;

Iterative Statements in PL/SQL
An iterative control Statements are used when we want to repeat the execution of one or more statements for specified number of times. These are similar to those in
There are three types of loops in PL/SQL:
• Simple Loop
• While Loop
• For Loop

1) Simple Loop
A Simple Loop is used when a set of statements is to be executed at least once before the loop terminates. An EXIT condition must be specified in the loop, otherwise the loop will get into an infinite number of iterations. When the EXIT condition is satisfied the process exits from the loop.
The General Syntax to write a Simple Loop is:
LOOP
   statements;
   EXIT;
   {or EXIT WHEN condition;}
END LOOP;

These are the important steps to be followed while using Simple Loop.
1) Initialize a variable before the loop body.
2) Increment the variable in the loop.
3) Use EXIT WHEN statement to exit from the Loop. If you use EXIT statement without WHEN condition then the statements in the loop are executed only once.

2) While Loop
A WHILE LOOP is used when a set of statements has to be executed as long as a condition is true. The condition is evaluated at the beginning of each iteration. The iteration continues until the condition becomes false.
The General Syntax to write a WHILE LOOP is:

WHILE
 LOOP statements;
END LOOP;

Important steps to follow when executing a while loop:
1) Initialize a variable before the loop body.
2) Increment the variable in the loop.
3) EXIT WHEN statement and EXIT statements can be used in while loops but it's not done often.

3) FOR Loop
A FOR LOOP is used to execute a set of statements for a predetermined number of times. Iteration occurs between the start and end integer values given. The counter is always incremented by 1. The loop exits when the counter reaches the value of the end integer.
The General Syntax to write a FOR LOOP is:
FOR counter IN val1..val2
  LOOP statements;
END LOOP;

• val1 - Start integer value.
• val2 - End integer value.
Important steps to follow when executing a while loop:
1) The counter variable is implicitly declared in the declaration section, so it's not necessary to declare it explicitly.
2) The counter variable is incremented by 1 and does not need to be incremented explicitly.
3) EXIT WHEN statement and EXIT statements can be used in FOR loops but it's not done often.

NOTE: The above Loops are explained with an example when dealing with Explicit Cursors.


What are Cursors?
A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it. This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called the active set.
There are two types of cursors in PL/SQL:

Implicit cursors:
These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed.

Explicit cursors:
They must be created when you are executing a SELECT statement that returns more than one row. Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row. When you fetch a row the current row position moves to next row.
Both implicit and explicit cursors have the same functionality, but they differ in the way they are accessed.

Implicit Cursors:
When you execute DML statements like DELETE, INSERT, UPDATE and SELECT statements, implicit statements are created to process these statements.
Oracle provides few attributes called as implicit cursor attributes to check the status of DML operations. The cursor attributes available are %FOUND, %NOTFOUND, %ROWCOUNT, and %ISOPEN.
For example, When you execute INSERT, UPDATE, or DELETE statements the cursor attributes tell us whether any rows are affected and how many have been affected.
When a SELECT... INTO statement is executed in a PL/SQL Block, implicit cursor attributes can be used to find out whether any row has been returned by the SELECT statement. PL/SQL returns an error when no data is selected.

The status of the cursor for each of these attributes are defined in the below table. 

Attributes

Return Value

Example

%FOUND

The return value is TRUE, if the DML statements like INSERT, DELETE and UPDATE affect at least one row and if SELECT ….INTO statement return at least one row.

SQL%FOUND

The return value is FALSE, if DML statements like INSERT, DELETE and UPDATE do not affect row and if SELECT….INTO statement do not return a row.

%NOTFOUND

The return value is FALSE, if DML statements like INSERT, DELETE and UPDATE affect at least one row and if SELECT ….INTO statement return at least one row.

SQL%NOTFOUND

The return value is TRUE, if a DML statement like INSERT, DELETE and UPDATE do not affect even one row and if SELECT ….INTO statement does not return a row.

%ROWCOUNT

Return the number of rows affected by the DML operations INSERT, DELETE, UPDATE, SELECT

SQL%ROWCOUNT



For Example: Consider the PL/SQL Block that uses implicit cursor attributes as shown below:

DECLARE  var_rows number(5);
BEGIN
  UPDATE employee
  SET salary = salary + 1000;
  IF SQL%NOTFOUND THEN
    dbms_output.put_line('None of the salaries where updated');
  ELSIF SQL%FOUND THEN
    var_rows := SQL%ROWCOUNT;
    dbms_output.put_line('Salaries for ' || var_rows || 'employees are updated');
  END IF;
END;

In the above PL/SQL Block, the salaries of all the employees in the ‘employee’ table are updated. If none of the employee’s salary are updated we get a message 'None of the salaries where updated'. Else we get a message like for example, 'Salaries for 1000 employees are updated' if there are 1000 rows in ‘employee’ table.

Explicit Cursors
An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row. We can provide a suitable name for the cursor.

The General Syntax for creating a cursor is as given below:
CURSOR cursor_name IS select_statement;
• cursor_name – A suitable name for the cursor.
• select_statement – A select query which returns multiple rows.

How to use Explicit Cursor?
There are four steps in using an Explicit Cursor.
• DECLARE the cursor in the declaration section.
• OPEN the cursor in the Execution Section.
• FETCH the data from cursor into PL/SQL variables or records in the Execution Section.
• CLOSE the cursor in the Execution Section before you end the PL/SQL Block.

1) Declaring a Cursor in the Declaration Section:
   DECLARE
   CURSOR emp_cur IS
   SELECT *
   FROM emp_tbl
   WHERE salary > 5000;
      In the above example we are creating a cursor ‘emp_cur’ on a query which returns the records of all the
      employees with salary greater than 5000. Here ‘emp_tbl’ in the table which contains records of all the
      employees.

2) Accessing the records in the cursor:
      Once the cursor is created in the declaration section we can access the cursor in the execution section of the PL/SQL program.

How to access an Explicit Cursor?

These are the three steps in accessing the cursor.
1) Open the cursor.
2) Fetch the records in the cursor one at a time.
3) Close the cursor.

General Syntax to open a cursor is:
OPEN cursor_name;

General Syntax to fetch records from a cursor is:
FETCH cursor_name INTO record_name;
OR
FETCH cursor_name INTO variable_list;

General Syntax to close a cursor is:
CLOSE cursor_name;

When a cursor is opened, the first row becomes the current row. When the data is fetched it is copied to the record or variables and the logical pointer moves to the next row and it becomes the current row. On every fetch statement, the pointer moves to the next row. If you want to fetch after the last row, the program will throw an error. When there is more than one row in a cursor we can use loops along with explicit cursor attributes to fetch all the records.

Points to remember while fetching a row:
• We can fetch the rows in a cursor to a PL/SQL Record or a list of variables created in the PL/SQL Block.
• If you are fetching a cursor to a PL/SQL Record, the record should have the same structure as the cursor.
• If you are fetching a cursor to a list of variables, the variables should be listed in the same order in the fetch statement as the columns are present in the cursor.

General Form of using an explicit cursor is:
 DECLARE
    variables;
    records;
    create a cursor;
 BEGIN
   OPEN cursor;
   FETCH cursor;
     process the records;
   CLOSE cursor;
 END;

Lets Look at the example below

Example 1:
1> DECLARE
2>    emp_rec emp_tbl%rowtype;
3>    CURSOR emp_cur IS
4>    SELECT *
5>    FROM
6>    WHERE salary > 10;
7> BEGIN
8>    OPEN emp_cur;
9>    FETCH emp_cur INTO emp_rec;
10>      dbms_output.put_line (emp_rec.first_name || '  ' || emp_rec.last_name);
11>   CLOSE emp_cur;
12> END;

In the above example, first we are creating a record ‘emp_rec’ of the same structure as of table ‘emp_tbl’ in line no 2. We can also create a record with a cursor by replacing the table name with the cursor name. Second, we are declaring a cursor ‘emp_cur’ from a select query in line no 3 - 6. Third, we are opening the cursor in the execution section in line no 8. Fourth, we are fetching the cursor to the record in line no 9. Fifth, we are displaying the first_name and last_name of the employee in the record emp_rec in line no 10. Sixth, we are closing the cursor in line no 11.

What are Explicit Cursor Attributes?
Oracle provides some attributes known as Explicit Cursor Attributes to control the data processing while using cursors. We use these attributes to avoid errors while accessing cursors through OPEN, FETCH and CLOSE Statements.

When does an error occur while accessing an explicit cursor?
a) When we try to open a cursor which is not closed in the previous operation.
b) When we try to fetch a cursor after the last operation.

These are the attributes available to check the status of an explicit cursor.

Attributes

Return values

Example

%FOUND

TRUE, if fetch statement returns at least one row.

Cursor_name%FOUND

FALSE, if fetch statement doesn’t return a row.

%NOTFOUND

TRUE, , if fetch statement doesn’t return a row.

Cursor_name%NOTFOUND

FALSE, if fetch statement returns at least one row.

%ROWCOUNT

The number of rows fetched by the fetch statement

Cursor_name%ROWCOUNT

If no row is returned, the PL/SQL statement returns an error.

%ISOPEN

TRUE, if the cursor is already open in the program

Cursor_name%ISNAME

FALSE, if the cursor is not opened in the program.

 
Using Loops with Explicit Cursors:

Oracle provides three types of cursors namely SIMPLE LOOP, WHILE LOOP and FOR LOOP. These loops can be used to process multiple rows in the cursor. Here I will modify the same example for each loop to explain how to use loops with cursors.

Cursor with a Simple Loop:

1> DECLARE
2>   CURSOR emp_cur IS
3>   SELECT first_name, last_name, salary FROM emp_tbl;
4>   emp_rec emp_cur%rowtype;
5> BEGIN
6>   IF NOT sales_cur%ISOPEN THEN
7>      OPEN sales_cur;
8>   END IF;
9>   LOOP
10>     FETCH emp_cur INTO emp_rec;
11>     EXIT WHEN emp_cur%NOTFOUND;
12>     dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
13>     || ' ' ||emp_cur.salary);
14>  END LOOP;
15>  END;
16>  /

In the above example we are using two cursor attributes %ISOPEN and %NOTFOUND.
In line no 6, we are using the cursor attribute %ISOPEN to check if the cursor is open, if the condition is true the program does not open the cursor again, it directly moves to line no 9.

In line no 11, we are using the cursor attribute %NOTFOUND to check whether the fetch returned any row. If there is no rows found the program would exit, a condition which exists when you fetch the cursor after the last row, if there is a row found the program continues.
We can use %FOUND in place of %NOTFOUND and vice versa. If we do so, we need to reverse the logic of the program. So use these attributes in appropriate instances.

Cursor with a While Loop:

Lets modify the above program to use while loop.

1> DECLARE
2>  CURSOR emp_cur IS
3>  SELECT first_name, last_name, salary FROM emp_tbl;
4>  emp_rec emp_cur%rowtype;
5> BEGIN
6>   IF NOT sales_cur%ISOPEN THEN
7>      OPEN sales_cur;
8>   END IF;
9>   FETCH sales_cur INTO sales_rec; 
10>  WHILE sales_cur%FOUND THEN 
11>  LOOP
12>    dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
13>    || ' ' ||emp_cur.salary);
15>    FETCH sales_cur INTO sales_rec;
16>  END LOOP;
17> END;
18> /

In the above example, in line no 10 we are using %FOUND to evaluate if the first fetch statement in line no 9 returned a row, if true the program moves into the while loop. In the loop we use fetch statement again (line no 15) to process the next row. If the fetch statement is not executed once before the while loop the while condition will return false in the first instance and the while loop is skipped. In the loop, before fetching the record again, always process the record retrieved by the first fetch statement, else you will skip the first row.

Cursor with a FOR Loop:

When using FOR LOOP you need not declare a record or variables to store the cursor values, need not open, fetch and close the cursor. These functions are accomplished by the FOR LOOP automatically.

General Syntax for using FOR LOOP:

FOR record_name IN cusror_name
LOOP
    process the row...
END LOOP;

Let’s use the above example to learn how to use for loops in cursors.

1> DECLARE
2>  CURSOR emp_cur IS
3>  SELECT first_name, last_name, salary FROM emp_tbl;
4>  emp_rec emp_cur%rowtype;
5> BEGIN
6>  FOR emp_rec in sales_cur
7>  LOOP 
8>  dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
9>    || ' ' ||emp_cur.salary); 
10> END LOOP;
11>END;
12> /

In the above example, when the FOR loop is processed a record ‘emp_rec’of structure ‘emp_cur’ gets created, the cursor is opened, the rows are fetched to the record ‘emp_rec’ and the cursor is closed after the last row is processed. By using FOR Loop in your program, you can reduce the number of lines in the program.

NOTE: In the examples given above, we are using backward slash ‘/’ at the end of the program. This indicates the oracle engine that the PL/SQL program has ended and it can begin processing the statements.



Stored Procedures

What is a Stored Procedure?

A stored procedure or in simple a proc is a named PL/SQL block which performs one or more specific task. This is similar to a procedure in other programming languages. A procedure has a header and a body. The header consists of the name of the procedure and the parameters or variables passed to the procedure. The body consists or declaration section, execution section and exception section similar to a general PL/SQL Block. A procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.

We can pass parameters to procedures in three ways.

1) IN-parameters
2) OUT-parameters
3) IN OUT-parameters

A procedure may or may not return any value.

General Syntax to create a procedure is:

CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]
IS   
   Declaration section
BEGIN   
   Execution section
EXCEPTION   
  Exception section
END;

IS - marks the beginning of the body of the procedure and is similar to DECLARE in anonymous PL/SQL Blocks. The code between IS and BEGIN forms the Declaration section.

The syntax within the brackets [ ] indicate they are optional. By using CREATE OR REPLACE together the procedure is created if no other procedure with the same name exists or the existing procedure is replaced with the current code.

The below example creates a procedure ‘employer_details’ which gives the details of the employee.

1> CREATE OR REPLACE PROCEDURE employer_details
2> IS
3>  CURSOR emp_cur IS
4>  SELECT first_name, last_name, salary FROM emp_tbl;
5>  emp_rec emp_cur%rowtype;
6> BEGIN
7>  FOR emp_rec in sales_cur
8>  LOOP
9>  dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
10>    || ' ' ||emp_cur.salary);
11> END LOOP;
12>END;
13> /

How to execute a Stored Procedure?
There are two ways to execute a procedure.

1) From the SQL prompt.
 EXECUTE [or EXEC] procedure_name;
2) Within another procedure – simply use the procedure name.
  procedure_name;

NOTE: In the examples given above, we are using backward slash ‘/’ at the end of the program. This indicates the oracle engine that the PL/SQL program has ended and it can begin processing the statements.

PL/SQL Functions

What is a Function in PL/SQL?

A function is a named PL/SQL Block which is similar to a procedure. The major difference between a procedure and a function is, a function must always return a value, but a procedure may or may not return a value.

The General Syntax to create a function is:

CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype
IS 
Declaration_section 
BEGIN 
Execution_section
Return return_variable; 
EXCEPTION 
exception section 
Return return_variable; 
END;

1) Return Type: The header section defines the return type of the function. The return datatype can be any of the oracle datatype like varchar, number etc.
2) The execution and exception section both should return a value which is of the datatype defined in the header section.

For example, let’s create a frunction called ''employer_details_func' similar to the one created in stored proc

1> CREATE OR REPLACE FUNCTION employer_details_func
2>    RETURN VARCHAR(20)
3> IS
5>    emp_name VARCHAR(20);
6> BEGIN
7> SELECT first_name INTO emp_name
8> FROM emp_tbl WHERE empID = '100';
9> RETURN emp_name;
10> END;
11> /

In the example we are retrieving the ‘first_name’ of employee with empID 100 to variable ‘emp_name’.
The return type of the function is VARCHAR which is declared in line no 2.
The function returns the 'emp_name' which is of type VARCHAR as the return value in line no 9.

How to execute a PL/SQL Function?

A function can be executed in the following ways.

1) Since a function returns a value we can assign it to a variable.
employee_name :=  employer_details_func;
If ‘employee_name’ is of datatype varchar we can store the name of the employee by assigning the return type of the function to it.

2) As a part of a SELECT statement
SELECT employer_details_func FROM dual;

3) In a PL/SQL Statements like,
dbms_output.put_line(employer_details_func);

This line displays the value returned by the function.


Parameters in Procedure and Functions

How to pass parameters to Procedures and Functions in PL/SQL?


In PL/SQL, we can pass parameters to procedures and functions in three ways.

1) IN type parameter: These types of parameters are used to send values to stored procedures.
2) OUT type parameter: These types of parameters are used to get values from stored procedures. This is similar to a return type in functions.
3) IN OUT parameter: These types of parameters are used to send values and get values from stored procedures.

NOTE: If a parameter is not explicitly defined a parameter type, then by default it is an IN type parameter.

1) IN parameter:
This is similar to passing parameters in programming languages. We can pass values to the stored procedure through these parameters or variables. This type of parameter is a read only parameter. We can assign the value of IN type parameter to a variable or use it in a query, but we cannot change its value inside the procedure.

The General syntax to pass a IN parameter is

CREATE [OR REPLACE] PROCEDURE procedure_name (
  param_name1 IN datatype, param_name12 IN datatype ... )

• param_name1, param_name2... are unique parameter names.
• datatype - defines the datatype of the variable.
• IN - is optional, by default it is a IN type parameter.


2) OUT Parameter:
The OUT parameters are used to send the OUTPUT from a procedure or a function. This is a write-only parameter i.e, we cannot pass values to OUT paramters while executing the stored procedure, but we can assign values to OUT parameter inside the stored procedure and the calling program can recieve this output value.

The General syntax to create an OUT parameter is

CREATE [OR REPLACE] PROCEDURE proc2 (param_name OUT datatype)

The parameter should be explicity declared as OUT parameter.


3) IN OUT Parameter:
The IN OUT parameter allows us to pass values into a procedure and get output values from the procedure. This parameter is used if the value of the IN parameter can be changed in the calling program.
By using IN OUT parameter we can pass values into a parameter and return a value to the calling program using the same parameter. But this is possible only if the value passed to the procedure and output value have a same datatype. This parameter is used if the value of the parameter will be changed in the procedure.

The General syntax to create an IN OUT parameter is

CREATE [OR REPLACE] PROCEDURE proc3 (param_name IN OUT datatype)


The below examples show how to create stored procedures using the above three types of parameters.

Example1:
Using IN and OUT parameter:


Let’s create a procedure which gets the name of the employee when the employee id is passed.
1> CREATE OR REPLACE PROCEDURE emp_name (id IN NUMBER, emp_name OUT NUMBER)
2> IS
3> BEGIN
4>    SELECT first_name INTO emp_name
5>    FROM emp_tbl WHERE empID = id;
6> END;
7> /

We can call the procedure ‘emp_name’ in this way from a PL/SQL Block.

1> DECLARE
2>  empName varchar(20);
3>  CURSOR id_cur SELECT id FROM emp_ids;
4> BEGIN
5> FOR emp_rec in id_cur
6> LOOP
7>   emp_name(emp_rec.id, empName);
8>   dbms_output.putline('The employee ' || empName || ' has id ' || emp-rec.id);
9> END LOOP;
10> END;
11> /

In the above PL/SQL Block
In line no 3; we are creating a cursor ‘id_cur’ which contains the employee id.
In line no 7; we are calling the procedure ‘emp_name’, we are passing the ‘id’ as IN parameter and ‘empName’ as OUT parameter.
In line no 8; we are displaying the id and the employee name which we got from the procedure ‘emp_name’.

Example 2:
Using IN OUT parameter in procedures:

1> CREATE OR REPLACE PROCEDURE emp_salary_increase
2> (emp_id IN emptbl.empID%type, salary_inc IN OUT emptbl.salary%type)
3> IS
4>    tmp_sal number;
5> BEGIN
6>    SELECT salary
7>    INTO tmp_sal
8>    FROM emp_tbl
9>    WHERE empID = emp_id;
10>   IF tmp_sal between 10000 and 20000 THEN
11>      salary_inout := tmp_sal * 1.2;
12>   ELSIF tmp_sal between 20000 and 30000 THEN
13>      salary_inout := tmp_sal * 1.3;
14>   ELSIF tmp_sal > 30000 THEN
15>      salary_inout := tmp_sal * 1.4;
16>   END IF;
17> END;
18> /

The below PL/SQL block shows how to execute the above 'emp_salary_increase' procedure.

1> DECLARE
2>    CURSOR updated_sal is
3>    SELECT empID,salary
4>    FROM emp_tbl;
5>    pre_sal number;
6> BEGIN
7>   FOR emp_rec IN updated_sal LOOP
8>       pre_sal := emp_rec.salary;
9>       emp_salary_increase(emp_rec.empID, emp_rec.salary);
10>       dbms_output.put_line('The salary of ' || emp_rec.empID ||
11>                ' increased from '|| pre_sal || ' to '||emp_rec.salary);
12>   END LOOP;
13> END;
14> /



Exception Handling

In this section we will discuss about the following,
1) What is Exception Handling?
2) Structure of Exception Handling.
3) Types of Exception Handling.

1) What is Exception Handling?

PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block known as exception Handling. Using Exception Handling we can test the code and avoid it from exiting abruptly. When an exception occurs; a message which explains its cause is received.
PL/SQL Exception message consists of three parts.
1) Type of Exception
2) An Error Code
3) A message
By handling the exceptions we can ensure a PL/SQL block does not exit abruptly.

2) Structure of Exception Handling.

The General Syntax for coding the exception section
 DECLARE
   Declaration section
 BEGIN
   Exception section
 EXCEPTION
 WHEN ex_name1 THEN
    -Error handling statements
 WHEN ex_name2 THEN
    -Error handling statements
 WHEN Others THEN
   -Error handling statements
END;

General PL/SQL statements can be used in the Exception Block.
When an exception is raised, Oracle searches for an appropriate exception handler in the exception section. For example in the above example, if the error raised is 'ex_name1 ', then the error is handled according to the statements under it. Since, it is not possible to determine all the possible runtime errors during testing of the code, the 'WHEN Others' exception is used to manage the exceptions that are not explicitly handled. Only one exception can be raised in a Block and the control does not return to the Execution Section after the error is handled.

If there are nested PL/SQL blocks like this.
 DELCARE
   Declaration section
 BEGIN
    DECLARE
      Declaration section
    BEGIN
      Execution section
    EXCEPTION
      Exception section
    END;
 EXCEPTION
   Exception section
 END;

In the above case, if the exception is raised in the inner block it should be handled in the exception block of the inner PL/SQL block else the control moves to the Exception block of the next upper PL/SQL Block. If none of the blocks handle the exception the program ends abruptly with an error.

3) Types of Exception.

There are 3 types of Exceptions.
a) Named System Exceptions
b) Unnamed System Exceptions
c) User-defined Exceptions

a) Named System Exceptions
System exceptions are automatically raised by Oracle, when a program violates a RDBMS rule. There are some system exceptions which are raised frequently, so they are pre-defined and given a name in Oracle which are known as Named System Exceptions.
For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System exceptions.

Named system exceptions are:
1) Not Declared explicitly,
2) Raised implicitly when a predefined Oracle error occurs,
3) caught by referencing the standard name within an exception-handling routine.

Exception Name

Reason

Error Number

CURSOR_ALREADY_OPEN

When you open a cursor that is already open.

ORA-06511

INVALID_CURSOR

When you perform an invalid operation on a cursor like closing a cursor, fetch data from a cursor that is not opened.

ORA-01001

NO_DATA_FOUND

When a SELECT...INTO clause does not return any row from a table.

ORA-01403

TOO_MANY_ROWS

When you SELECT or fetch more than one row into a record or variable.

ORA-01422

ZERO_DIVIDE

When you attempt to divide a number by zero.

ORA-01476



For Example: Suppose a NO_DATA_FOUND exception is raised in a proc, we can write a code to handle the exception as given below.
BEGIN
  Execution section
EXCEPTION
WHEN NO_DATA_FOUND THEN
 dbms_output.put_line ('A SELECT...INTO did not return any row.');
 END;

b) Unnamed System Exceptions

Those system exception for which oracle does not provide a name is known as unnamed system exception. These exceptions do not occur frequently. These Exceptions have a code and an associated message.

There are two ways to handle unnamed system exceptions:
1. By using the WHEN OTHERS exception handler, or
2. By associating the exception code to a name and using it as a named exception.

We can assign a name to unnamed system exceptions using a Pragma called EXCEPTION_INIT.

EXCEPTION_INIT will associate a predefined Oracle error number to a programmer_defined exception name.

Steps to be followed to use unnamed system exceptions are
• They are raised implicitly.
• If they are not handled in WHEN Others they must be handled explicitly.
• To handle the exception explicitly, they must be declared using Pragma

The general syntax to declare unnamed system exception using EXCEPTION_INIT is:

DECLARE
   exception_name EXCEPTION;
   PRAGMA
   EXCEPTION_INIT (exception_name, Err_code);
BEGIN
Execution section
EXCEPTION
  WHEN exception_name THEN
     handle the exception
END;

For Example: Lets consider the product table and order_items table from sql joins.

Here product_id is a primary key in product table and a foreign key in order_items table.
If we try to delete a product_id from the product table when it has child records in order_id table an exception will be thrown with oracle code number -2292.
We can provide a name to this exception and handle it in the exception section as given below. 

 DECLARE
  Child_rec_exception EXCEPTION;
  PRAGMA
   EXCEPTION_INIT (Child_rec_exception, -2292);
BEGIN
  Delete FROM product where product_id= 104;
EXCEPTION
   WHEN Child_rec_exception
   THEN Dbms_output.put_line('Child records are present for this product_id.');
END;
/

c) User-defined Exceptions

Apart from system exceptions we can explicitly define exceptions based on business rules. These are known as user-defined exceptions.
Steps to be followed to use user-defined exceptions:
• They should be explicitly declared in the declaration section.
• They should be explicitly raised in the Execution Section.
• They should be handled by referencing the user-defined exception name in the exception section.

For Example: Let’s consider the product table and order_items table from sql joins to explain user-defined exception.
Let’s create a business rule that if the total no of units of any particular product sold is more than 20, then it is a huge quantity and a special discount should be provided.

DECLARE
  huge_quantity EXCEPTION;
  CURSOR product_quantity is
  SELECT p.product_name as name, sum(o.total_units) as units
  FROM order_tems o, product p
  WHERE o.product_id = p.product_id;
  quantity order_tems.total_units%type;
  up_limit CONSTANT order_tems.total_units%type := 20;
  message VARCHAR2(50);
BEGIN
  FOR product_rec in product_quantity LOOP
    quantity := product_rec.units;
     IF quantity > up_limit THEN
message := 'The number of units of product ' || product_rec.name || ' is more than 20. Special discounts should be provided. Rest of the records are skipped. '
     RAISE huge_quantity;
     ELSIF quantity < up_limit THEN
      message:= 'The number of unit is below the discount limit.';
     END IF;
     dbms_output.put_line (message);
  END LOOP;
 EXCEPTION
   WHEN huge_quantity THEN
     dbms_output.put_line (message);
 END;
/

RAISE_APPLICATION_ERROR ( )
RAISE_APPLICATION_ERROR is a built-in procedure in oracle which is used to display the user-defined error messages along with the error number whose range is in between -20000 and -20999.

Whenever a message is displayed using RAISE_APPLICATION_ERROR, all previous transactions which are not committed within the PL/SQL Block are rolled back automatically (i.e. change due to INSERT, UPDATE, or DELETE statements).
RAISE_APPLICATION_ERROR raises an exception but does not handle it.

RAISE_APPLICATION_ERROR is used for the following reasons,
a) to create a unique id for an user-defined exception.
b) to make the user-defined exception look like an Oracle error.

The General Syntax to use this procedure is:

RAISE_APPLICATION_ERROR (error_number, error_message);

• The Error number must be between -20000 and -20999
• The Error_message is the message you want to display when the error occurs.

Steps to be followed to use RAISE_APPLICATION_ERROR procedure:
1. Declare a user-defined exception in the declaration section.
2. Raise the user-defined exception based on a specific business rule in the execution section.
3. Finally, catch the exception and link the exception to a user-defined error number in RAISE_APPLICATION_ERROR.

Using the above example we can display an error message using RAISE_APPLICATION_ERROR.

DECLARE
  huge_quantity EXCEPTION;
  CURSOR product_quantity is
  SELECT p.product_name as name, sum(o.total_units) as units
  FROM order_tems o, product p
  WHERE o.product_id = p.product_id;
  quantity order_tems.total_units%type;
  up_limit CONSTANT order_tems.total_units%type := 20;
  message VARCHAR2(50);
BEGIN
  FOR product_rec in product_quantity LOOP
    quantity := product_rec.units;
     IF quantity > up_limit THEN
        RAISE huge_quantity;
     ELSIF quantity < up_limit THEN
      v_message:= 'The number of unit is below the discount limit.';
     END IF;
     Dbms_output.put_line (message);
  END LOOP;
 EXCEPTION
   WHEN huge_quantity THEN
 raise_application_error(-2100, 'The number of unit is above the discount limit.');
 END;
/

]]>
techhelp07@gmail.com (Michael Jordan) frontpage Tue, 20 Oct 2009 16:42:27 +0000
C# FTP client in Secure mode http://www.techfundu.com/2010010980/microsoft-technology/net-technologies/c-ftp-client-in-secure-mode http://www.techfundu.com/2010010980/microsoft-technology/net-technologies/c-ftp-client-in-secure-mode Introduction

The purpose of this article is to create a C# FTP client in Secure mode, so if you don’t have much knowledge of FTPS, I advise you to take a look at this: FTPS.

In the .NET Framework, to upload a file in FTPS mode, we generally use the FtpWebRequest class, but you can not send commands with « quote » arguments, and even if you search on the web, you will not find a concrete example of a secured C# FTP client.

It’s for those reasons I decided to create this article.

SSL Stream:

To send a socket in Secure Socket Layer (SSL) mode, we use the class System.Net.Security.SslStream.

Provides a stream used for client-server communication that uses the Secure Socket Layer (SSL) security protocol to authenticate the server and optionally the client”.

For more information, refer to MSDN.

Using the Code:

1. Pre-Authenticate

FTPFactory ftp = new FTPFactory();
ftp.setDebug(true);
ftp.setRemoteHost(Settings.Default.TargetFtpSource);

//Connect to SSL Port (990)
ftp.setRemotePort(990);
ftp.loginWithoutUser();

//Send "AUTH SSL" Command
string cmd = "AUTH SSL";
ftp.sendCommand(cmd);

 

Before connecting to the FTP server in SSL mode, you have to define the 990 SSL port and send the « AUTH SSL » command authentication using SSL.

 

2. Create SSL Stream

//Create SSL Stream

ftp.getSslStream();

ftp.setUseStream(true);

//Login to FTP Secure

ftp.setRemoteUser(Settings.Default.TargetFtpSecureUser);

ftp.setRemotePass(Settings.Default.TargetFtpSecurePass);

ftp.login();

 

ftp.getSslStream() creates an SSL stream from client socket which will be used for exchange between the client and the server FTPS. Then, you have to enter a login and password to authenticate on the FTPS server.

Note: if the SSL stream is well established, then I display all the information about the server certificate.

 

3. Upload File

//Set ASCII Mode
ftp.setBinaryMode(false);

//Send Arguments if you want
//cmd = "site arg1 arg2";
//ftp.sendCommand(cmd);

//Upload file
ftp.uploadSecure(@"Filepath", false);

ftp.close();

 

Before uploading a file, you have to specify the mode: ftp.setBinaryMode(bool value).

  • value is false --> ASCII mode
  • value is true --> Binary mode

By default, it’s binary. Now, you upload the file using:

ftp.uploadSecure(@"Filepath", false)

Note: you can upload in non secured mode using ftp.upload().

Points of Interest

I learned how an SSL stream and the RAW FTP communication works between a client and an FTP server. Searching on the web, I found many who were stuck on the issue of SSL communication with an FTP server, so I hope this article will be of great help.

]]>
kadaoui_el_mehdi@hotmail.com (kadaoui el mehdi) frontpage Sat, 09 Jan 2010 15:07:57 +0000
FTP Client Implementation in Java http://www.techfundu.com/2009123179/java-technology/core-java/ftp-client-implementation-in-java http://www.techfundu.com/2009123179/java-technology/core-java/ftp-client-implementation-in-java I recently worked on a project where I had to implement a FTP client program in Java. Project requirement was to download a text file from a FTP Server, after that transform that file into an another format that again was a text file and then upload this new transformed text file to another FTP Server. This was the first time that I was working on FTP file download/upload operation in a java program. First task for me was to find a stable Java API for FTP operation and I came across apache foundation’s Jakarta Commons Net project http://commons.apache.org/net/ . Jakarta Commons Net implements the client side of many basic Internet protocols. Currently this library support following protocols:

  • FTP/FTPS
  • NNTP
  • SMTP
  • POP3
  • Telnet
  • TFTP
  • Finger
  • Whois
  • rexec/rcmd/rlogin
  • Time (rdate) and Daytime
  • Echo
  • Discard
  • NTP/SNTP

Now let’s discuss some of the important classes of Jakarta Commons Net library which are required for implementing FTP client program in java:

1.) org.apache.commons.net.SocketClient

SocketClient is an abstract class which provides the basic operations that are required of client objects accessing sockets. It is meant to be subclassed to avoid having to rewrite the same code over and over again to open a socket, close a socket, set timeouts, etc. You can see methods provided by this class on below page.

http://commons.apache.org/net/api/org/apache/commons/net/SocketClient.html

2.) org.apache.commons.net.ftp.FTP

FTP provides the basic the functionality necessary to implement your own FTP client. It extends org.apache.commons.net.SocketClient since extending TelnetClient was causing unwanted behavior (like connections that did not time out properly).

However for most the cases we don’t need to directly use FTP class. The FTPClient class, derived from FTP, implements all the functionality required of an FTP client. The FTP class is made public to provide access to various FTP constants and to make it easier for programmers (or those with special needs) to interact with the FTP protocol and implement their own clients. A set of methods with names corresponding to the FTP command names are provided to facilitate this interaction. You can see methods provided by this class on below page.

http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTP.html

3.) org.apache.commons.net.ftp.FTPClient

FTPClient encapsulates all the functionality necessary to store and retrieve files from an FTP server. This class takes care of all low level details of interacting with an FTP server and provides a convenient higher level interface. You can see methods provided by this class on below page.

http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html

Now let's see a sample program which download a file from FTP server, prints it output on console, transform in output file format and then upload transformed file on another FTP server.

Assumptions:

1.)    This java program uses Java SE 5.0 so Java SE 5.0 or up jars must be in your CLASSPATH.

2.)    You must have FTP server up and running and have access to that.

3.)    Download Jakarta Commons Net library from http://commons.apache.org/downloads/download_net.cgi and put in your CLASSPATH. I am using latest commons-net-2.0.jar for this program.

4.)    This program assumes that you already have an Input text file (Input.txt) on FTP server which you want to download. You can use any free FTP client application like FileZilla to upload your file to FTP server.

package com.techfundu.java;

import java.io.BufferedInputStream;

import java.io.ByteArrayInputStream;

import java.io.InputStream;

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.net.ftp.FTPClient;

import org.apache.commons.net.ftp.FTPReply;

public class FTPTest {

public void ftpFileDownloadUpload() {

FTPClient ftp1 = null;

FTPClient ftp2 = null;

InputStream is = null;

BufferedInputStream bis = null;

StringBuilder sb = new StringBuilder();

try {

//Created FTPClient Object

ftp1 = new FTPClient();

//Connect with FTP Server

ftp1.connect("FTP Server IP address or host name");

//Pass the credentials of FTP User

ftp1.login("username", "password");        

//Check connection Status                 
System.out.println("Status Check1:" + ftp1.getReplyString());

//Set File Type as Binary
ftp1.setFileType(FTP.BINARY_FILE_TYPE);

//Specify name of file which need to be downloaded. This file should already exist on FTP Server.

String input = "Input.txt";

//Download file now..

is = ftp1.retrieveFileStream(input);

//Read content of file and store in StringBuilder sb

bis = new BufferedInputStream(is);

byte[] b = new byte[8];

int j = bis.read(b);

while(j!=-1) {

byte[] data = new byte[j];

for (int x=0;x < data.length;x++)

{

data[x] = b[x];

}

sb.append(new String(data));

j = bis.read(b);

}

//Print content of file..

System.out.println("Print Input File: \n" + sb.toString());

//Transform content of file into output format

String outputData = transform(sb.toString());

// Connect with FTP Server2, Repeat all steps used for FTP Server1

ftp2 = new FTPClient();

ftp2.connect("FTP Server ip address or hostname");

ftp2.login("username", "password");

System.out.println("Status Check2:" + ftp2.getReplyString());

is = new ByteArrayInputStream(outputData.getBytes());

//Specify Output file name

String output = "Output.txt";

//Upload file to FTP Server2

ftp2.storeFile(output, is);

System.out.println("Status Check3:" + ftp2.getReplyString());

} catch(Throwable t) {

System.out.println("Error in FTP Operation: " + t.getMessage());

} finally {

disconnect(ftp1);

disconnect(ftp2);
}

}

private void disconnect(FTPClient ftp) {

try {

// Logout from the FTP server

ftp.logout();

// Now disconnect from FTP server

if(ftp.isConnected()){

ftp.disconnect();

}

} catch(Exception ex) {

System.out.println("Unable to logout/disconnect from FTP Server. Detail: " + ex.getMessage());

}

}

//Transform input file format to output file format

private String transform(String input){

//Write logic for file transformation.

String output = "This is Output File Text....";

return output;

}

public static void main(String [] args){

FTPTest ftp = new FTPTest();

ftp.ftpFileDownloadUpload();

}          
}

Console Output:

Status Check1:230 User cpgtechdev logged in.

Print Input File:

Input File Text....

Status Check2:230 User cpgtechdev logged in.

Status Check3:226 Transfer complete.


Similar you can try other methods of FTPClient as per your requirement.

We discussed only about FTP in this article but Jakarta Commons Net is much more than FTP. You can look on following classes for other protocols supported by this library. CharGenTCPClient, DaytimeTCPClient, DiscardTCPClient, FingerClient, FTP, NNTP, POP3, RExecClient, SMTP, TelnetClient, TimeTCPClient

 

]]>
rsrawat_2000@yahoo.com (Rajesh Pawar) frontpage Thu, 31 Dec 2009 14:56:11 +0000
Advanced QTP Tutorial (VBScript Orientation) http://www.techfundu.com/2010011583/software-qa-testing/automated-testing/advanced-qtp-tutorial-vbscript-orientation http://www.techfundu.com/2010011583/software-qa-testing/automated-testing/advanced-qtp-tutorial-vbscript-orientation
  • Introduction
  • Comments
  • VB Script Variables
  • VB Script Data Types
  • VB Script Operators
  • Input/Output Operations
  • Constants
  • Conditional Statements
  • General Examples
  • Loop Through Code
  • Procedures
  • Built-In Functions
  • VBScript syntax rules and guidelines
  • Errors
  • File System Operations
  • Test Requirements
  • Solutions
  • QTP Add-Ins Information
  • VBScript Glossary
  • 1.  Introduction

    • VBScript is a scripting language.
    • A scripting language is a lightweight programming language.
    • VBScript is a light version of Microsoft's programming language Visual Basic.

    When a VBScript is inserted into a HTML document, the Internet browser will read the HTML and interpret the VBScript. The VBScript can be executed immediately, or at a later event.

    Microsoft Visual Basic Scripting Edition brings active scripting to a wide variety of environments, including Web client scripting in Microsoft Internet Explorer and Web server scripting in Microsoft Internet Information Service.

    1.1 Windows Script Host (WSH)

    It is a Windows administration tool. WSH creates an environment for hosting scripts.
    That is, when a script arrives at your computer, WSH plays the part of the host — it makes objects and services available for the script and provides a set of guidelines within which the script is executed. Among other things, Windows Script Host manages security and invokes the appropriate script engine
    Windows Script Host is built into Microsoft Windows 98, 2000, and Millennium Editions and higher versions.
    A Windows script is a text file. We can create a script with any text editor as long as we save our script with a WSH-compatible script extension (.js, vbs, or .wsf).
    The most commonly available text editor is already installed on our computer — Notepad. We can also use your favorite HTML editor, VbsEdit, Microsoft Visual C++, or Visual InterDev.

    1.2 Creating a script with Notepad

    1. 1.Start Notepad.
    2. 2.Write your script. For example purposes, type Msgbox "Hello VB Script"
    3. 3.Save this text file with a .vbs extension (instead of the default .txt extension). For example, Hello.vbs
    4. 4.Navigate to the file you just saved, and double-click it.
    5. 5.Windows Script Host invokes the VB Script engine and runs your script. In the example, a message box is displayed with the message "Hello VB Script"

    1.3 Hosting Environments and Script Engines

    Scripts are often embedded in Web pages, either in an HTML page (on the client side) or in an ASP page (on the server side).
    In the case of a script embedded in an HTML page, the engine component that interprets and runs the script code is loaded by the Web browser, such as Internet Explorer.
    In the case of a script embedded in an ASP page, the engine that interprets and runs the script code is built into Internet Information Services (IIS).
    Windows Script Host executes scripts that exist outside an HTML or ASP page and that stand on their own as text files.

    1.4 Available Script Engines

    Generally, we write scripts in either Microsoft JScript or VBScript, the two script engines that ship with Microsoft Windows 98, 2000 and Millennium Editions.

    We can use other script engines, such as Perl, REXX, and Python, with Windows Script Host.

    A stand-alone script written in JScript has the .js extension; a stand-alone script written in VBScript has the .vbs extension. These extensions are registered with Windows. When we run one of these types of files, Windows starts Windows Script Host, which invokes the associated script engine to interpret and run the file.

    2. Comments

    The comment argument is the text of any comment we want to include.

    2.0 Purpose of comments:

    • We can use comments for making the script understandable.
    • We can use comments for making one or more statements disable from execution.

    2.1 Syntax

    Rem comment (After the Rem keyword, a space is required before comment.)

    Or

    Apostrophe (') symbol before the comment

    2.2 Comment/Uncomment a block of statements

    • Select block of statement and use short cut key Ctrl + M (for comment)
    • Select comment block and use short cut key Ctrl + Shift + M (for uncomment)

    3. VB Script Variables

    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.

    3.1 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, Top, Bottom, Left, Right

    We can also declare a variable implicitly by simply using its name in our script. That is not generally 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.

    3.2 Option Explicit

    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.

    3.3 Naming Restrictions for Variables

    Variable names follow the standard rules for naming anything in VBScript. A variable name:

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

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

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

    3.6 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

    3.7 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) = 256

    A(1) = 324

    A(2) = 100

    A(3) = 55

    Similarly, the data can be retrieved from any element using an index into the particular array 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 second number is the number of columns.

    3.8 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 eliminated elements.

    4. VB Script Data Types

    VBScript has only one data type called a Variant. A Variant is a special kind of data type that can contain different kinds of information, depending on how it is used.

    Because Variant is the only data type in VBScript, it is also the data type returned by all functions in VBScript.

    4.1 Variant Subtypes

    Beyond the simple numeric or string classifications, a Variant can make further distinctions about the specific nature of numeric information. For example, we can have numeric information that represents a date or a time. When used with other date or time data, the result is always expressed as a date or a time. We can also have a rich variety of numeric information ranging in size from Boolean values to huge floating-point numbers. These different categories of information that can be contained in a Variant are called subtypes. Most of the time, we can just put the kind of data we want in a Variant, and the Variant behaves in a way that is most appropriate for the data it contains.

    The following table shows subtypes of data that a Variant can contain.

    Subtype Description

    Empty Variant is uninitialized. Value is 0 for numeric variables or a zero-length string ("") for string variables.

    Null : Variant intentionally contains no valid data.

    Boolean : Contains either True or False.

    Byte : Contains integer in the range 0 to 255.

    Integer : Contains integer in the range -32,768 to 32,767.

    Currency : -922,337,203,685,477.5808 to 922,337,203,685,477.5807.

    Long : Contains integer in the range -2,147,483,648 to 2,147,483,647.

    Single : Contains a single-precision, floating-point number in the range -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.

    Double : Contains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.

    Date (Time) : Contains a number that represents a date between January 1, 100 to December 31, 9999.

    String : Contains a variable-length string that can be up to approximately 2 billion characters in length.

    Object : Contains an object.

    Error : Contains an error number.

    We can use conversion functions to convert data from one subtype to another. In addition, the VarType function returns information about how your data is stored within a Variant.

    5. VB Script Operators

    Operators are used for performing mathematical, comparison and logical operations. VBScript has a full range of operators, including arithmetic operators, comparison operators, concatenation operators, and logical operators.

    5.1 Operator Precedence

    When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence.

    We can use parentheses to override the order of precedence and force some parts of an expression to be evaluated before others.

    Operations within parentheses are always performed before those outside. Within parentheses, however, standard operator precedence is maintained.

    When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last.

    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.

    5.2 Arithmetic Operators:

    Operators symbols and their 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 floating-point 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.

    5.3 Comparison Operators

    Comparison operators are used to compare expressions.

    Operators Symbols and their Description)
    1. = (Equal to)
    2. (Not equal to)
    3. < (Less than)
    4. > (Greater than)
    5. <= (Less than or equal to)
    6. >= (Greater than or equal to)
    7. Is  (Object equivalence)

    5.4 Concatenation Operators

    Concatenation Operators and their Description

    1) Addition Operator (+) - Sums two numbers

    • If both expressions are numeric then Add
    • If both expressions are strings then Concatenate.
    • If both One expression is numeric and the other is a string then Add.

    2) Concatenation Operator (&) : Forces string concatenation of two expressions.

    5.5 Logical Operators

    Operator Symbol and Description

    1) Not : Performs logical negation on an expression

    Syntax:

    result= Not expression

    2) And : Performs a logical conjunction on two expressions.

    Syntax:

    result= expression1 And expression2

    3) Or : Performs a logical disjunction on two expressions.

    Syntax:

    result= expression1 Or expression2

    4) Xor : Performs a logical exclusion on two expressions.

    Syntax:

    result= expression1 Xor expression2

    5) Eqv : Performs a logical equivalence on two expressions.

    Syntax:

    result= expression1 Eqv expression2

    6) Imp : Performs a logical implication on two expressions.

    Syntax:

    result= expression1 Imp expression2

    6. Input/Output Operations

    6.1 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)

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

    Example:

    Dim MyVar

    MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")

    ' MyVar contains either 1 or 2, depending on which button is

    7.  VB Script Constants

    A constant is a meaningful name that takes the place of a number or string and never changes.

    7.1 Creating Constants

    We create user-defined constants in VBScript using the Const statement. Using the Const statement, we can create string or numeric constants with meaningful names and assign them literal values.

    Const statement

    Declares constants for use in place of literal values.

    Example:

    Const MyString = "This is my string."

    Const MyAge = 49

    Const CutoffDate = #6-1-97#

    Note that String literal is enclosed in quotation marks (" ").

    Represent Date literals and time literals by enclosing them in number signs (#).

    We declare multiple constants by separating each constant name and value with a comma. For example:

    Const price= 100, city= “Hyderabad”, x= 27

    8. 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) If…Then…Else Statement

    2) Select Case Statement

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

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

    8.1.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 "Hello G.C.Reddy"

    msgbox "x value is: "&x

    msgbox "Bye Bye"

    End If

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

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

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

    8.2 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

    8.3 Other Examples

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

    8.3.2 Write a program for finding out whether the given number is, Even number or Odd number?

    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

    8.3.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 " ∑)

    8.3.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)

    8.3.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 " ∑)

    else

    msgbox "Number, you entered is not a 4 digit number"

    End If

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

    8.3.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.3.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

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

    8.3.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:\gcr.txt", 8, true)

    myfile.writeline num

    myfile.close

    Next

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

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

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

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

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

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

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

    9. Looping Through Code

    • Looping allows us to run a group of statements repeatedly.
    • Some loops repeat statements until a condition is False;
    • Others repeat statements until a condition is True.
    • There are also loops that repeat statements a specific number of times.

    The following looping statements are available in VBScript:

    • Do...Loop: Loops while or until a condition is True.
    • While...Wend: Loops while a condition is True.
    • For...Next: Uses a counter to run statements a specified number of times.
    • For Each...Next: Repeats a group of statements for each item in a collection or each element of an array.

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

    9.1.1 Repeating Statements While a Condition is True

    Repeats a block of statements while a condition is True or until a condition becomes True

    a) 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

    b) 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

    9.1.2 Repeating a Statement Until a Condition Becomes True

    c) 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:

    d) 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

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

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

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

    10. Control Flow Examples (Using Conditional and Loop Statements)

    10.1 read a number and verify that number Range weather in between 1 to 100 or 101 to 1000?

    Option explicit

    Dim a,x

    a=Inputbox ("Enter a Vaule")

    a=cdbl(a)

    If a<= 100 Then

    For x= 1 to 100

    If a=x Then

    msgbox "a is in between 1 to 100 range"

    End If

    Next

    else

    For x= 101 to 1000

    If a=x Then

    msgbox "a is in between 101 to 1000 range"

    End If

    Next

    End If

    10.2 read Data and find that data size, If size 4 then display invalid data message, if data size = 4 then verify “a” is there or not in that data?

    Dim x

    x=Inputbox ("Enter 4 digit value")

    x1=Right(x,1)

    x2=Left (x,1)

    x3=mid (x,2,Len(1))

    x4=mid (x,3,Len(1))

    y=len(x)

    If y=4 Then

    If  x1="a" or x2="a" or x3="a" or x4="a" Then

    msgbox "a is there"

    else

    msgbox "a is Not there"

    End If

    else

    msgbox "Invalid Data"

    End If

    11. VB Script Procedures

    In VBScript, there are two kinds of procedures available; the Sub procedure and the Function procedure.

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

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

    11.3 Getting Data into and out of Procedures

    • Each piece of data is passed into our procedures using an argument.
    • Arguments serve as placeholders for the data we want to pass into our procedure. We can name our arguments any valid variable name.
    • When we create a procedure using either the Sub statement or the Function statement, parentheses must be included after the name of the procedure.
    • Any arguments are placed inside these parentheses, separated by commas.

    11.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)

    -Or-

    MsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."

    To call a Sub procedure from another procedure, type the name of the procedure along 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.

    12. VB Script Built in Functions

    Types of Functions

    • Conversions (25)
    • Dates/Times (19)
    • Formatting Strings (4)
    • Input/Output (3)
    • Math (9)
    • Miscellaneous (3)
    • Rounding (5)
    • Strings (30)
    • 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 myday

    mydate=#02-17-2009#

    x=Datediff("d",mydate,Now)

    msgbox x

    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 MyCheck

    MyCheck = VarType(300)          ' Returns 2.

    Msgbox Mycheck

    MyCheck = VarType(#10/19/62#)   ' Returns 7.

    Msgbox Mycheck

    MyCheck = VarType("VBScript")   ' Returns 8.

    Msgbox Mycheck

    14) Left Function

    Dim MyString, LeftString

    MyString = "VBSCript"

    LeftString = Left(MyString, 3) ' LeftString contains "VBS".

    15) 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".

    16) 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

    17) Mid Function

    Returns a specified number of characters from a string.

    Dim MyVar

    MyVar = Mid("VB Script is fun!", 4, 6)

    Msgbox MyVar

    * It Returns ‘Script’ *

    18) 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)

    19) 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 *

    20) 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)

    21) 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")

    13. VBScript syntax rules and guidelines

    13.1 Case-sensitivity:

    By default, VBScript is not case sensitive and does not differentiate between upper case and lower-case spelling of words, for example, in variables, object and method names, or constants.

    For example, the two statements below are identical in VBScript:

    Browser("Mercury").Page("Find a Flight:").WebList("toDay").Select "31"

    browser("mercury").page("find a flight:").weblist("today").select "31"

    13.2 Text strings:

    When we enter a value as a text string, we must add quotation marks before and after the string. For example, in the above segment of script, the names of the Web site, Web page, and edit box are all text strings surrounded by quotation marks.

    Note that the value 31 is also surrounded by quotation marks, because it is a text string that represents a number and not a numeric value.

    In the following example, only the property name (first argument) is a text string and is in quotation marks. The second argument (the value of the property) is a variable and therefore does not have quotation marks. The third argument (specifying the timeout) is a numeric value, which also does not need quotation marks.

    Browser("Mercury").Page("Find a Flight:").WaitProperty("items count", Total_Items, 2000)

    13.3 Variables:

    We can specify variables to store strings, integers, arrays and objects. Using variables helps to make our script more readable and flexible

    13.4 Parentheses:

    To achieve the desired result and to avoid errors, it is important that we use parentheses () correctly in our statements.

    13.5 Indentation:

    We can indent or outdent our script to reflect the logical structure and nesting of the statements.

    13.6 Comments:

    We can add comments to our statements using an apostrophe ('), either at the beginning of a separate line, or at the end of a statement. It is recommended that we add comments wherever possible, to make our scripts easier to understand and maintain.

    13.7 Spaces:

    We can add extra blank spaces to our script to improve clarity. These spaces are ignored by VBScript.

    14. Errors

    We have two types Errors in VB Script; they are VBScript Run-time Errors and VBScript Syntax Errors

    14.1 VBScript Run-time Errors

    VBScript run-time errors are errors that result when our VBScript script attempts to perform an action that the system cannot execute. VBScript run-time errors occur while our script is being executed; when variable expressions are being evaluated, and memory is being dynamic allocated.

    14.2 VBScript Syntax Errors

    VBScript syntax errors are errors that result when the structure of one of our VBScript statements violates one or more of the grammatical rules of the VBScript scripting language. VBScript syntax errors occur during the program compilation stage, before the program has begun to be executed.

    15. File System Operations

    I) Working with Drives and Folders

    a) Creating a Folder

    Option Explicit

    Dim objFSO, objFolder, strDirectory

    strDirectory = "D:\logs"

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    Set objFolder = objFSO.CreateFolder(strDirectory)

    b) Deleting a Folder

    Set oFSO = CreateObject("Scripting.FileSystemObject")

    oFSO.DeleteFolder("E:\FSO")

    c) Copying Folders

    Set oFSO=createobject("Scripting.Filesystemobject")

    oFSO.CopyFolder "E:\gcr6", "C:\jvr", True

    d) Checking weather the folder available or not, if not creating the folder

    Option Explicit

    Dim objFSO, objFolder, strDirectory

    strDirectory = "D:\logs"

    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

    e) 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

    f) Getting available space on a Disk Drive

    Set oFSO = CreateObject("Scripting.FileSystemObject")

    Set oDrive = oFSO.GetDrive("C:")

    MsgBox "Available space: " & oDrive.AvailableSpace

    II) Working with Flat Files

    a)Creating a Flat File

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    Set objFile = objFSO.CreateTextFile("E:\ScriptLog.txt")

    b) Checking weather the File is available or not, if not creating the File

    strDirectory="E:\"

    strFile="Scripting.txt"

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    If objFSO.FileExists(strDirectory & strFile) Then

    Set objFolder = objFSO.GetFolder(strDirectory)

    Else

    Set objFile = objFSO.CreateTextFile("E:\ScriptLog.txt")

    End if

    c) Reading Data character by character from a Flat File

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    Set objFile = objFSO.OpenTextFile("E:\gcr.txt", 1)

    Do Until objFile.AtEndOfStream

    strCharacters = objFile.Read(1)

    msgbox strCharacters

    Loop

    d) Reading Data line by line from a Flat File

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    Set objFile = objFSO.OpenTextFile("E:\gcr.txt", 1)

    Do Until objFile.AtEndOfStream

    strCharacters = objFile.Readline

    msgbox strCharacters

    Loop

    e) Reading data from a flat file and using in data driven testing

    Dim fso,myfile

    Set fso=createobject("scripting.filesystemobject")

    Set myfile= fso.opentextfile ("F:\gcr.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("Password:").SetSecure s(1)

    Dialog("Login").WinButton("OK").Click

    Window("Flight Reservation").Close

    Wend

    f) 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:\gcr.txt", 8, True)

    WriteStuff.WriteLine(Stuff)

    WriteStuff.Close

    SET WriteStuff = NOTHING

    SET myFSO = NOTHING

    g) Delete a text file

    Set objFSO=createobject("Scripting.filesystemobject")

    Set txtFilepath = objFSO.GetFile("E:\gcr.txt")

    txtFilepath.Delete()

    h) 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

    i) Comparing two text files

    Dim f1, f2

    f1="e:\gcr1.txt"

    f2="e:\gcr2.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

    j) 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

    III) Working with Word Docs

    a) Create a word document and enter some data & save

    Dim objWD

    Set objWD = CreateObject("Word.Application")

    objWD.Documents.Add

    objWD.Selection.TypeText  "This is some text." & Chr(13) & "This is some more text"

    objWD.ActiveDocument.SaveAs "e:\gcreddy.doc"

    objWD.Quit

    IV) Working with Excel Sheets

    a) Create an excel sheet and enter a value into first cell

    Dim objexcel

    Set objExcel = createobject("Excel.application")

    objexcel.Visible = True

    objexcel.Workbooks.add

    objexcel.Cells(1, 1).Value = "Testing"

    objexcel.ActiveWorkbook.SaveAs("f:\gcreddy1.xls")

    objexcel.Quit

    b) Compare two excel files

    Set objExcel = CreateObject("Excel.Application")

    objExcel.Visible = True

    Set objWorkbook1= objExcel.Workbooks.Open("E:\gcr1.xls")

    Set objWorkbook2= objExcel.Workbooks.Open("E:\gcr2.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

    16. Test Requirements

    1) Verify Login Boundary (Check all the boundary conditions of the Login window. Checks to see if the correct message appears in the error window (Flight Reservation Message)

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

    3) Verify Addition, Subtraction, Multiplication and Division Operations in Calculator Application.

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

    5)Price Consistency, In Flight Reservation (In Flight Reservation, First class price=3*Economy class price and Business class price=2*Economy class price)

    6) Verify Total, In Flight Reservation (In Flight Reservation, Total = Tickets * Price)

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

    8) Verify Order No Entry in Flight Reservation. (In Open Order dialog box, Order No object accepts numeric values only.)

    9) Get Test Data from a Flat file and use in Data Driven Testing (through Scripting)

    10) Get Test Data From a Database and use in Data Driven Testing (through Scripting)

    11) Count, how many links available in Mercury Tours Home Page?

    12) Count how many Buttons and Edit boxes available in Flight Reservation window?

    13) 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)

    14) In Login Dialog box, Verify Help message (The message is ‘The password is 'MERCURY')

    15) Count all opened Browsers on desktop and close all?

    16) Create an Excel file, enter some data and save the file through VB scripting?

    Solutions:

    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)Reporter.ReportEvent 1,"Res","Multiplecation Failed"

    35)End If

    36)If dRes=v1/v2 Then

    37)Reporter.ReportEvent 0,"Res","Division Passed"

    38)else

    39)Reporter.ReportEvent 1,"Res","Division Failed"

    40)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("Flight Reservations").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)Option explicit

    2)Dim qtp,flight_app,f,t,i,j,x,y

    3)If Not Window("text:=Flight Reservation").Exist (7)= True Then

    4)QTP=Environment("ProductDir")

    5)Flight_app="\samples\flight\app\flight4a.exe"

    6)SystemUtil.Run QTP & Flight_app

    7)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) Get Test Data From a Database and use in Data Driven Testing (through Scripting)

    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\Administrator\My Documents\Gcr.mdb"

    6)rs.open "Select * From Login",con

    7)While rs.eof True

    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 rs.fields ("Agent")

    11)Dialog("Login").WinEdit("Password:").Set rs.fields ("Password")

    12)Dialog("Login").WinButton("OK").Click

    13)Window("Flight Reservation").Close

    14)rs.movenext

    15)Wend

    11) Count, how many links available in Mercury Tours Home Page.

    1)Set oDesc = Description.Create()

    2)oDesc("micclass").Value = "Link"

    3)Set Lists = Browser("Welcome: Mercury").Page("Welcome: Mercury").ChildObjects (oDesc)

    4)NumberOfLinks = Lists.Count()

    5)Reporter.ReportEvent 2,"Res","Number of Links are: "&NumberOfLinks

    12) 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

    13) 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

    14) 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

    15) Count all opened Browsers on desktop and close them all?

    1)Set oDesc = Description.Create()

    2)oDesc("micclass").Value = "Browser"

    3)Set Browsers =Desktop.ChildObjects (oDesc)

    4)NumberofBrowsers = Browsers.Count()

    5)Reporter.ReportEvent 2,"Res","Number of Browsers are: "&NumberOfBrowsers

    6)For Counter=0 to NumberofBrowsers-1

    7)Browsers(Counter).Close

    8)Next

    16) Create an Excel file, enter some data and save the file through VB scripting?

    1)Dim objexcel

    2)Set objExcel = createobject("Excel.application")

    3)objexcel.Visible = True

    4)objexcel.Workbooks.add

    5)objexcel.Cells(1, 1).Value = "Testing"

    6)objexcel.ActiveWorkbook.SaveAs("f:\exceltest.xls")

    7)objexcel.Quit

    18. QTP Add-Ins Information

    I) ActiveX Environment

    Objects and their Description

    ActiveX : An ActiveX control.

    AcxButton : An ActiveX button.

    AcxCalendar : An ActiveX calendar object.

    AcxCheckBox : An ActiveX check box.

    AcxComboBox : An ActiveX combo box object.

    AcxEdit : An ActiveX edit box.

    AcxRadioButton : An ActiveX radio button.

    AcxTable : An ActiveX table.

    AcxUtil : An object that enables you to work with objects returned by performing an operation (usually via the Object property) on an ActiveX test object.

    II) Delphi Environment

    Objects and their Description

    DelphiButton : A Delphi button.

    DelphiCheckBox : A Delphi check box.

    DelphiComboBox : A Delphi combo box.

    DelphiEdit : A Delphi edit box.

    DelphiEditor : A Delphi multi-line editor.

    DelphiList : A Delphi list.

    DelphiListView : A Delphi list-view control.

    DelphiNavigator : A Delphi navigator control.

    DelphiObject : A Delphi object.

    DelphiRadioButton : A Delphi radio button.

    DelphiScrollBar : A Delphi scroll bar.

    DelphiSpin : A Delphi spin box.

    DelphiStatic : A Delphi static control.

    DelphiStatusBar : A Delphi status bar.

    DelphiTable : A Delphi table.

    DelphiTabStrip : A Delphi tab strip.

    DelphiTreeView : A Delphi tree-view control.

    DelphiWindow : A Delphi window or dialog box.

    III) Java Environment

    Objects and their Description

    JavaApplet : A Java applet.

    JavaButton : A Java button.

    JavaCalendar : A Java calendar.

    JavaCheckBox : A Java check box.

    JavaDialog : A Java dialog box.

    JavaEdit : A Java edit box.

    JavaExpandBar : A Java control that contains labeled bar items, which can be expanded or collapsed by the user.

    JavaInternalFrame : An internal frame that can be activated from the Java applet.

    JavaLink : A Java control that displays text with links.

    JavaList : A Java list box with single or multiple selection.

    JavaMenu : A Java menu item.

    JavaObject : A generic Java object.

    JavaRadioButton : A Java radio button.

    JavaSlider : A Java slider.

    JavaSpin : A Java spin object.

    JavaStaticText : A Java static text object.

    JavaTab : A Java tabstrip control containing tabbed panels.

    JavaTable : A Java table.

    JavaToolbar : A Java toolbar.

    JavaTree : A Java tree.

    JavaWindow : A Java window.

    IV) .NET Web Forms Environment

    Objects and their Description

    WbfCalendar : A .NET Web Forms calendar control.

    WbfGrid : A .NET Web Forms DataGrid object.

    WbfTabStrip : A .NET Web Forms tabstrip control.

    WbfToolbar : A .NET Web Forms toolbar control.

    WbfTreeView : A .NET Web Forms tree view object.

    WbfUltraGrid : A .NET Web Forms UltraGrid object.

    V) .NET Windows Forms Environment

    Objects and their Description

    SwfButton : A .NET Windows Forms button object.

    SwfCalendar : A DateTimePicker or a Month Calendar .NET Windows Forms calendar object.

    SwfCheckBox : A .NET Windows Forms check box.

    SwfComboBox : A .NET Windows Forms combo box.

    SwfEdit : A .NET Windows Forms edit box.

    SwfEditor : A .NET Windows Forms multi-line edit box.

    SwfLabel : A .NET Windows Forms static text object.

    SwfList : A .NET Windows Forms list.

    SwfListView : A .NET Windows Forms ListView control.

    SwfObject : A standard .NET Windows Forms object.

    SwfPropertyGrid : A property grid control based on the .NET Windows Forms library.

    SwfRadioButton : A .NET Windows Forms radio button.

    SwfScrollBar : A .NET Windows Forms scroll bar.

    SwfSpin : A .NET Windows Forms spin object.

    SwfStatusBar : A .NET Windows Forms status bar control.

    SwfTab : A .NET Windows Forms tab control.

    SwfTable : A grid control based on the .NET Windows Forms library.

    SwfToolBar : A .NET Windows Forms toolbar.

    SwfTreeView : A .NET Windows Forms TreeView control.

    SwfWindow : A .NET Windows Forms window.

    VI) Windows Presentation Foundation Environment

    Objects and their Description

    WpfButton : A button control in a Windows Presentation Foundation application.

    WpfCheckBox : A check box control in a Windows Presentation Foundation application.

    WpfComboBox : A combo box control in a Windows Presentation Foundation application.

    WpfEdit : A document, rich text box, or text control in a Windows Presentation Foundation application.

    WpfGrid : A grid control in a Windows Presentation Foundation application.

    WpfImage : An image control in a Windows Presentation Foundation application.

    WpfLink : A hyperlink control in a Windows Presentation Foundation application.

    WpfList : A list control in a Windows Presentation Foundation application.

    WpfMenu : A menu control in a Windows Presentation Foundation application.

    WpfObject : An object control in a Windows Presentation Foundation application.

    WpfProgressBar : A progress bar control in a Windows Presentation Foundation application.

    WpfRadioButton : A radio button control in a Windows Presentation Foundation application.

    WpfScrollBar: A scroll bar control in a Windows Presentation Foundation application.

    WpfSlider : A slider control in a Windows Presentation Foundation application.

    WpfStatusBar : A status bar control in a Windows Presentation Foundation application.

    WpfTabStrip : A tab control in a Windows Presentation Foundation application.

    WpfToolbar : A toolbar control in a Windows Presentation Foundation application.

    WpfTreeView : A tree control in a Windows Presentation Foundation application.

    WpfWindow : A window control in a Windows Presentation Foundation application.

    VII) Oracle Environment

    Objects and their Description

    OracleApplications : An Oracle Applications session window.

    OracleButton : An Oracle button.

    OracleCalendar : An Oracle calendar.

    OracleCheckbox : A check box Oracle field.

    OracleFlexWindow : An Oracle flexfield window.

    OracleFormWindow : An Oracle Form window.

    OracleList : An Oracle poplist (combo box) or list.

    OracleListOfValues : An Oracle window containing a list of values for selection.

    OracleLogon : An Oracle Applications sign-on window.

    OracleNavigator : An Oracle Navigator window.

    OracleNotification : An Oracle error or message window.

    OracleRadioGroup : An Oracle option (radio button) group.

    OracleStatusLine : The status line and message line at the bottom of an Oracle Applications window.

    OracleTabbedRegion : An Oracle tabbed region.

    OracleTable : An Oracle block of records.

    OracleTextField : An Oracle text field.

    OracleTree : An Oracle tree.

    VIII) PeopleSoft Environment

    Object and its Description

    PSFrame : A frame object within a PeopleSoft application.

    IX) PowerBuilder Environment

    Objects and their Description

    PbButton : A PowerBuilder button.

    PbCheckBox : A PowerBuilder check box.

    PbComboBox : A PowerBuilder combo box.

    PbDataWindow : A PowerBuilder DataWindow control.

    PbEdit : A PowerBuilder edit box.

    PbList : A PowerBuilder list.

    PbListView : A PowerBuilder listview control.

    PbObject : A standard PowerBuilder object.

    PbRadioButton : A PowerBuilder radio button.

    PbScrollBar : A PowerBuilder scroll bar.

    PbTabStrip : A PowerBuilder tab strip control

    PbTreeView : A PowerBuilder tree-view control.

    PbWindow : A PowerBuilder window.

    X) SAP Web Environment

    Objects and their Description

    SAPButton : An SAP Gui for HTML application button, including icons, toolbar buttons, regular buttons, buttons with text, and buttons with text and image.

    SAPCalendar : A calendar in a Web-based SAP application.

    SAPCheckBox : An SAP Gui for HTML application toggle button, including check boxes and toggle images.

    SAPDropDownMenu : A menu that is opened by clicking a menu icon within an SAP Gui for HTML application.

    SAPEdit : An SAP Gui for HTML application edit box, including single-line edit boxes and multi-line edit boxes (text area).

    SAPFrame : An SAP Gui for HTML application frame.

    SAPiView : An SAP Enterprise Portal application iView frame.

    SAPList : A drop-down or single/multiple selection list in an SAP Gui for HTML application.

    SAPMenu : An SAP Gui for HTML application top-level menu.

    SAPNavigationBar : A navigation bar in a Web-based SAP application.

    SAPOKCode : An OK Code box in an SAP Gui for HTML application.

    SAPPortal : An SAP Enterprise Portal desktop.

    SAPRadioGroup : An SAP Gui for HTML application radio button group.

    SAPStatusBar : An SAP Gui for HTML application status bar.

    SAPTable : An SAP Gui for HTML application table or grid.

    SAPTabStrip : An SAP Gui for HTML application tab strip object (an object that enables switching between multiple tabs).

    SAPTreeView : An SAP Gui for HTML application tree object.

    XI) SAP GUI for Windows Environment

    Objects and their Description

    SAPGuiAPOGrid : An APO grid control in an SAP GUI for Windows application.

    SAPGuiButton : A button in an SAP GUI for Windows application.

    SAPGuiCalendar : A calendar object in an SAP GUI for Windows application.

    SAPGuiCheckBox : A check box in an SAP GUI for Windows application.

    SAPGuiComboBox : A combo box in an SAP GUI for Windows application.

    SAPGuiEdit : An edit box in an SAP GUI for Windows application.

    SAPGuiElement : Any object in an SAP GUI for Windows application.

    SAPGuiGrid : A grid control in an SAP GUI for Windows application.

    SAPGuiLabel : A static text label in an SAP GUI for Windows application.

    SAPGuiMenubar : A menu bar in an SAP GUI for Windows application.

    SAPGuiOKCode : An OK Code box in an SAP GUI for Windows application.

    SAPGuiRadioButton : A radio button in an SAP GUI for Windows application.

    SAPGuiSession : Represents the SAP GUI for Windows session on which an operation is performed.

    SAPGuiStatusBar : A status bar in an SAP GUI for Windows application.

    SAPGuiTable : A table control in an SAP GUI for Windows application.

    SAPGuiTabStrip : A tab strip in an SAP GUI for Windows application.

    SAPGuiTextArea : A text area in an SAP GUI for Windows application.

    SAPGuiToolbar : A toolbar in an SAP GUI for Windows application.

    SAPGuiTree : A column tree, list tree, or simple tree control in an SAP GUI for Windows application.

    SAPGuiUtil : A utility object in an SAP GUI for Windows application.

    SAPGuiWindow : A window or dialog box containing objects in an SAP GUI for Windows application.

    XII) Siebel Environment

    Objects and their Description

    SblAdvancedEdit : An edit box whose value can be set by a dynamic object that opens after clicking on a button inside the edit box

    SblButton : A Siebel button.

    SblCheckBox : A check box with an ON and OFF state.

    SblEdit : An edit box.

    SblPickList : A drop-down pick list.

    SblTable : A Siebel table containing a variable number of rows and columns.

    SblTabStrip : A number of tabs and four arrows that move its visible range to the left and to the right.

    SblTreeView : A tree view of specific screen data.

    SiebApplet : An applet in a Siebel test automation environment.

    SiebApplication : An application in a Siebel test automation environment.

    SiebButton : A button control in a Siebel test automation environment.

    SiebCalculator : A calculator control in a Siebel test automation environment.

    SiebCalendar : A calendar control in a Siebel test automation environment.

    SiebCheckbox : A checkbox in a Siebel test automation environment.

    SiebCommunicationsToolbar : The communications toolbar in a Siebel test automation environment.

    SiebCurrency : A currency calculator in a Siebel test automation environment.

    SiebList : A list object in a Siebel test automation environment.

    SiebMenu : A menu or menu item in a Siebel test automation environment.

    SiebPageTabs : A page tab in a Siebel test automation environment.

    SiebPDQ : A predefined query in a Siebel test automation environment.

    SiebPicklist : A pick list in a Siebel test automation environment.

    SiebRichText : A rich text control in a Siebel test automation environment.

    SiebScreen : A screen object in a Siebel test automation environment.

    SiebScreenViews : A screen view in a Siebel test automation environment.

    SiebTaskAssistant : The Task Assistant in a Siebel test automation environment.

    SiebTaskUIPane : The task UI pane in a Siebel test automation environment.

    SiebText : A text box in a Siebel test automation environment.

    SiebTextArea : A text area in a Siebel test automation environment.

    SiebThreadbar : A threadbar in a Siebel test automation environment.

    SiebToolbar : A toolbar in a Siebel test automation environment.

    SiebTree : A tree view object in a Siebel test automation environment.

    SiebView : A view object in a Siebel test automation environment.

    SiebViewApplets : A view applet in a Siebel test automation environment.

    XIII) Standard Windows Environment

    Objects and their Description

    Desktop : An object that enables you to access top-level items on your desktop.

    Dialog : A Windows dialog box.

    Static : A static text object.

    SystemUtil : An object used to control applications and processes during a run session.

    WinButton : A Windows button.

    WinCalendar : A Windows calendar.

    WinCheckBox : A Windows check box.

    WinComboBox : A Windows combo box.

    Window : A standard window.

    WinEdit : A Windows edit box.

    WinEditor : A Windows multi-line editor.

    WinList : A Windows list.

    WinListView : A Windows list-view control.

    WinMenu : A Windows menu.

    WinObject : A standard (Windows) object.

    WinRadioButton : A Windows radio button.

    WinScrollBar : A Windows scroll bar.

    WinSpin : A Windows spin box.

    WinStatusBar : A Windows status bar.

    WinTab : A Windows tab strip in a dialog box.

    WinToolbar : A Windows toolbar.

    WinTreeView : A Windows tree-view control.

    XIV) Stingray Environment

    Objects and their Description

    WinTab : A Windows tab strip in a dialog box.

    WinTable : A Stingray grid.

    WinToolbar : A Windows toolbar.

    WinTreeView : A Stingray tree control.

    XV) Terminal Emulators Environment

    Objects and their Description

    TeField : A terminal emulator field that fully supports HLLAPI.

    TeScreen : A terminal emulator screen that fully supports HLLAPI.

    TeTextScreen : A terminal emulator screen that uses text-only HLLAPI or does not support HLLAPI.

    TeWindow : A terminal emulator window.

    XVI) Visual Basic Environment

    Objects and their Description

    VbButton : A Visual Basic button.

    VbCheckBox : A Visual Basic check box.

    VbComboBox : A Visual Basic combo box.

    VbEdit : A Visual Basic edit box.

    VbEditor : A Visual Basic multi-line editor.

    VbFrame : A Visual Basic frame.

    VbLabel : A static text object.

    VbList : A Visual Basic list.

    VbListView : A Visual Basic list-view control.

    VbRadioButton : A Visual Basic radio button.

    VbScrollBar : A Visual Basic scroll bar.

    VbToolbar : A Visual Basic toolbar.

    VbTreeView : A Visual Basic tree-view control.

    VbWindow : A Visual Basic window.

    XVII) VisualAge Smalltalk Environment

    Objects and their Description

    WinButton : A button in the VisualAge Smalltalk application.

    WinEdit : An edit box in the VisualAge Smalltalk application.

    WinList : A list in the VisualAge Smalltalk application.

    WinObject : An object in the VisualAge Smalltalk application.

    WinTab : A tab strip in the VisualAge Smalltalk application.

    WinTable : A table in the VisualAge Smalltalk application.

    WinTreeView : A tree-view control in the VisualAge Smalltalk application.

    XVIII) Web Environment

    Objects and their Description

    Browser : A Web browser (or browser tab).

    Frame : An HTML frame.

    Image : An image with or without a target URL link.

    Link : A hypertext link.

    Page : An HTML page.

    ViewLink : A Viewlink object.

    WebArea : A section of an image (usually a section of a client-side image map).

    WebButton : An HTML button.

    WebCheckBox : A check box with an ON and OFF state.

    WebEdit : An edit box, usually contained inside a form.

    WebElement : A general Web object that can represent any Web object.

    WebFile : An edit box with a browse button attached, used to select a file from the File dialog box.

    WebList : A drop-down box or multiple selection list.

    WebRadioGroup : A set of radio buttons belonging to the same group.

    WebTable : A table containing a variable number of rows and columns.

    WebXML : An XML document contained in a Web page.

    XIX) Web Services Environment

    Objects and  their Description

    Attachments : An object that supports attachment-related test object operations.

    Configuration : An object that supports configuration-related test object operations.

    Headers : An object that supports header-related test object operations.

    Security : An object that supports security-related test object operations.

    WebService : A test object representing a Web service.

    WSUtil : A utility object used to check WSDL files.

    B) Utility Objects

     

     

    • Crypt Object
    • DataTable Object
    • Description Object
    • DotNetFactory Object
    • DTParameter Object
    • DTSheet Object
    • Environment Object
    • Extern Object
    • LocalParameter Object
    • MercuryTimers Object (Collection)
    • MercuryTimer Object
    • Parameter Object
    • PathFinder Object
    • Properties Object (Collection)
    • QCUtil Object
    • RandomNumber Object
    • Recovery Object
    • Reporter Object
    • RepositoriesCollection Object
    • Repository Object
    • Services Object
    • Setting Object
    • SystemMonitor Object
    • TextUtil Object
    • TSLTest Object
    • XMLUtil Object

     

    The following utility statements help you control your test.

     

    • DescribeResult Statement
    • ExecuteFile Statement
    • ExitAction Statement
    • ExitActionIteration Statement
    • ExitComponent Statement
    • ExitComponentIteration Statement
    • ExitTest Statement
    • ExitTestIteration Statement
    • GetLastError Statement
    • InvokeApplication Statement
    • LoadAndRunAction Statement
    • ManualStep Statement
    • Print Statement
    • RegisterUserFunc Statement
    • RunAction Statement
    • SetLastError Statement
    • UnregisterUserFunc Statement
    • Wait Statement

     

    C) Supplemental Objects

     

    • DbTable Object
    • VirtualButton Object
    • VirtualCheckBox Object
    • VirtualList Object
    • VirtualObject Object
    • VirtualRadioButton Object
    • VirtualTable Object
    • XMLAttribute Object
    • XMLAttributesColl Object
    • XMLData Object
    • XMLElement Object
    • XMLElementsColl Object
    • XMLFile Object
    • XMLItemColl Object

     

    19. VBScript Glossary

    ActiveX control : An object that you place on a form to enable or enhance a user's interaction with an application. ActiveX controls have events and can be incorporated into other controls. The controls have an .ocx file name extension.

    ActiveX object : An object that is exposed to other applications or programming tools through Automation interfaces.

    Argument : A constant, variable, or expression passed to a procedure.

    Array : A set of sequentially indexed elements having the same type of data. Each element of an array has a unique identifying index number. Changes made to one element of an array do not affect the other elements.

    ASCII Character Set : American Standard Code for Information Interchange (ASCII) 7-bit character set widely used to represent letters and symbols found on a standard U.S. keyboard. The ASCII character set is the same as the first 128 characters (0–127) in the ANSI character set.

    Automation object : An object that is exposed to other applications or programming tools through Automation interfaces.

    Bitwise comparison : A bit-by-bit comparison of identically positioned bits in two numeric expressions.

    Boolean expression : An expression that evaluates to either True or False.

    By reference : A way of passing the address, rather than the value, of an argument to a procedure. This allows the procedure to access the actual variable. As a result, the variable's actual value can be changed by the procedure to which it is passed.

    By value : A way of passing the value, rather than the address, of an argument to a procedure. This allows the procedure to access a copy of the variable. As a result, the variable's actual value can't be changed by the procedure to which it is passed.

    character code : A number that represents a particular character in a set, such as the ASCII character set.

    Class : The formal definition of an object. The class acts as the template from which an instance of an object is created at run time. The class defines the properties of the object and the methods used to control the object's behavior.

    Class module : A module containing the definition of a class (its property and method definitions).

    Collection : An object that contains a set of related objects. An object's position in the collection can change whenever a change occurs in the collection; therefore, the position of any specific object in the collection may vary.

    Comment : Text added to code by a programmer that explains how the code works. In Visual Basic Scripting Edition, a comment line generally starts with an apostrophe ('), or you can use the keyword Rem followed by a space.

    Comparison operator :  A character or symbol indicating a relationship between two or more values or expressions. These operators include less than (=), not equal (), and equal (=).

    Is is also a comparison operator, but it is used exclusively for determining if one object reference is the same as another.

    Constant : A named item that retains a constant value throughout the execution of a program. Constants can be used anywhere in your code in place of actual values. A constant can be a string or numeric literal, another constant, or any combination that includes arithmetic or logical operators except Is and exponentiation. For example:

    Const A = "MyString"

    Data ranges : Each Variant subtype has a specific range of allowed values:

    Subtype and their Range

    Byte : 0 to 255.

    Boolean : True or False.

    Integer : -32,768 to 32,767.

    Long : -2,147,483,648 to 2,147,483,647.

    Single : -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.

    Double : -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.

    Currency : -922,337,203,685,477.5808 to 922,337,203,685,477.5807.

    Date : January 1, 100 to December 31, 9999, inclusive.

    Object : Any Object reference.

    String : Variable-length strings may range in length from 0 to approximately 2 billion characters.

    Date expression : Any expression that can be interpreted as a date. This includes any combination of date literals, numbers that look like dates, strings that look like dates, and dates returned from functions. A date expression is limited to numbers or strings, in any combination, that can represent a date from January 1, 100 through December 31, 9999.

    Dates are stored as part of a real number. Values to the left of the decimal represent the date; values to the right of the decimal represent the time. Negative numbers represent dates prior to December 30, 1899.

    Date literal : Any sequence of characters with a valid format that is surrounded by number signs (#). Valid formats include the date format specified by the locale settings for your code or the universal date format. For example, #12/31/99# is the date literal that represents December 31, 1999, where English-U.S. is the locale setting for your application.

    In VBScript, the only recognized format is US-ENGLISH, regardless of the actual locale of the user. That is, the interpreted format is mm/dd/yyyy.

    Date separators : Characters used to separate the day, month, and year when date values are formatted.

    Empty : A value that indicates that no beginning value has been assigned to a variable. Empty variables are 0 in a numeric context, or zero-length in a string context.

    Error number : A whole number in the range 0 to 65,535, inclusive, that corresponds to the Number property of the Err object. When combined with the Name property of the Err object, this number represents a particular error message.

    Expression : A combination of keywords, operators, variables, and constants that yield a string, number, or object. An expression can perform a calculation, manipulate characters, or test data.

    Intrinsic constant : A constant provided by an application. Because you can't disable intrinsic constants, you can't create a user-defined constant with the same name.

    Keyword : A word or symbol recognized as part of the VBScript language; for example, a statement, function name, or operator.

    Locale : The set of information that corresponds to a given language and country. A locale affects the language of predefined programming terms and locale-specific settings. There are two contexts where locale information is important:

     

    • The code locale affects the language of terms such as keywords and defines locale-specific settings such as the decimal and list separators, date formats, and character sorting order.
    • The system locale affects the way locale-aware functionality behaves, for example, when you display numbers or convert strings to dates. You set the system locale using the Control Panel utilities provided by the operating system.

     

    Nothing : The special value that indicates that an object variable is no longer associated with any actual object.

    Null : A value indicating that a variable contains no valid data. Null is the result of:

     

    • An explicit assignment of Null to a variable.
    • Any operation between expressions that contain Null.

     

    Numeric expression : Any expression that can be evaluated as a number. Elements of the expression can include any combination of keywords, variables, constants, and operators that result in a number.

    Object type : A type of object exposed by an application, for example, Application, File, Range, and Sheet. Refer to the application's documentation (Microsoft Excel, Microsoft Project, Microsoft Word, and so on) for a complete listing of available objects.

    Pi : Pi is a mathematical constant equal to approximately 3.1415926535897932.

    Private : Variables that are visible only to the script in which they are declared.

    Procedure : A named sequence of statements executed as a unit. For example, Function and Sub are types of procedures.

    Procedure level : Describes statements located within a Function or Sub procedure. Declarations are usually listed first, followed by assignments and other executable code. For example:

    Sub MySub() ' This statement declares a sub procedure block.

    Dim A ' This statement starts the procedure block.

    A = "My variable" ' Procedure-level code.

    Debug.Print A ' Procedure-level code.

    End Sub ' This statement ends a sub procedure block.

    Note that script-level code resides outside any procedure blocks.

    Property : A named attribute of an object. Properties define object characteristics such as size, color, and screen location, or the state of an object, such as enabled or disabled.

    Public : Variables declared using the Public Statement are visible to all procedures in all modules in all applications.

    Run time : The time when code is running. During run time, you can't edit the code.

    Run-time error : An error that occurs when code is running. A run-time error results when a statement attempts an invalid operation.

    Scope : Defines the visibility of a variable, procedure, or object. For example, a variable declared as Public is visible to all procedures in all modules. Variables declared in procedures are visible only within the procedure and lose their value between calls.

    SCODE : A long integer value that is used to pass detailed information to the caller of an interface member or API function. The status codes for OLE interfaces and APIs are defined in FACILITY_ITF.

    Script level : Any code outside a procedure is referred to as script-level code.

    Seed : An initial value used to generate pseudorandom numbers. For example, the Randomize statement creates a seed number used by the Rnd function to create unique pseudorandom number sequences.

    String comparison : A comparison of two sequences of characters. Unless specified in the function making the comparison, all string comparisons are binary. In English, binary comparisons are case-sensitive; text comparisons are not.

    String expression : Any expression that evaluates to a sequence of contiguous characters. Elements of a string expression can include a function that returns a string, a string literal, a string constant, or a string variable.

    Type library : A file or component within another file that contains standard descriptions of exposed objects, properties, and methods.

    Variable : A named storage location that can contain data that can be modified during program execution. Each variable has a name that uniquely identifies it within its level of scope.

    Variable names:

    • Must begin with an alphabetic character.
    • Can't contain an embedded period or type-declaration character.
    • Must be unique within the same scope.
    • Must be no longer than 255 characters.
    ]]>
    gcrqtp@gmail.com (G.C.Reddy) frontpage Fri, 15 Jan 2010 18:44:06 +0000