Web TEch

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 94

UNIT I

VBScript

VBScript is a subset of VBA and it allows usage of most familiar functions of


these one but there are some important differences:
1. provides no support for classes as used in Visual Basic;
2. control arrays not allowed;
3. do not support data access using JET or RDO. The data access is
allowed for back-end purposes by using Internet Service API (ISAPI)
provided with Internet Information Server (IIS);
4. provides no debugging features (you can use MsgBox function to show
important information for you; when finishing the job these can be
transformed in comments);
5. do not support file operations found in Visual Basic;
6. does not allow access to the Windows Help file system;
7. does not support VB intrinsic constants (such as vbOKOnly, vbCancel
etc);
8. there is no concept of Multiple Document Interface (MDI) in VBScript;
9. do not support the Screen, Printer, App, Debug and Clipboard objects. It
support only the Err object.
Microsoft says that VBScript is integrated with World Wide Web browsers
(more exactly with Internet Explorer versions of Microsoft) and designed to
work with ActiveX controls and other objects embedded in active HTML
documents.
The code modules are supported through the <SCRIPT></SCRIPT> tag. Each
script section forms an independent code module that may have its own
variables, functions and subroutines (they are similarly to the standard .bas
modules found in Visual Basic).
The forms are created using the <FORM></FORM> tag and they are not
visible as separate windows in the application. The forms are ways to group
controls together for the purpose of addressing their properties and methods in
code or to submit data to back-end process.

What is VBScript?

VBScript is a Microsoft scripting language.


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 . Add VBScript to your HTML pages, to make your web
site more dynamic and interactive.
How Does it Work?
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.
How to Put VBScript Code in an HTML Document
<html>
<head>
</head>
<body>
<script type="text/vbscript">
document.write("Hello from VBScript!")
</script>
</body>
</html>

And it produces this output:

Hello from VBScript!

To insert a script in an HTML document, use the <script> tag. Use the type
attribute to define the scripting language.
<script type="text/vbscript">
Then comes the VBScript: The command for writing some text on a page is
document.write: 
document.write("Hello from VBScript!")
The script ends:
</script>
How to Handle Older Browsers
Older browsers that do not support scripts will display the script as page content.
To prevent them from doing this, you can use the HTML comment tag:

<script type="text/vbscript">
<!--
some statements
-->
</script>

Example 1 :

<html>

<body>

<script type="text/vbscript">

document.write("Hello from VBScript!")

</script>
</body>

</html>

Output : Hello from VBScript!

Example 2 :

<html>

<body>

<script type="text/vbscript">

document.write("<h1>Hello World!</h1>")

document.write("<h2>Hello World!</h2>")

</script>

</body>

</html>

Output :

Hello World!

Hello World!

Where to Put the VBScript

Examples
Head section
Scripts can be placed in the head section. Usually we put all the "functions" in the
head section. The reason for this is to be sure that the script is loaded before the
function is called.
Body section
Execute a script that is placed in the body section. Scripts in the body section are
executed when the page is loading.

Scripts in a page will be executed immediately while the page loads into the
browser. This is not always what we want. Sometimes we want to execute a script
when a page loads, other times when a user triggers an event.
Scripts in the head section: Scripts to be executed when they are called or when
an event is triggered go in the head section. When you place a script in the head
section you will assure that the script is loaded before anyone uses it:
<html>
<head>
<script type="text/vbscript">
some statements
</script>
</head>
Scripts in the body section: Scripts to be executed when the page loads go in the
body section. When you place a script in the body section it generates the content
of the page:

<html>
<head>
</head>
<body>
<script type="text/vbscript">
some statements
</script>
</body>

Scripts in both the body and the head section: You can place an unlimited
number of scripts in your document, so you can have scripts in both the body and
the head section.
<html>
<head>
<script type="text/vbscript">
some statements
</script>
</head>
<body>
<script type="text/vbscript">
some statements
</script>
</body>

Create a variable
Variables are used to store information. This example demonstrates how you can
create a variable, and assign a value to it.

<html>
<body>
<script type="text/vbscript">
dim name
name="India"
document.write(name)
</script>
</body>
</html>
Jan Egil

Insert a variable value in a text


This example demonstrates how you can insert a variable value in a text.

<html>
<body>
<script type="text/vbscript">
dim name
name="Jan Egil"
document.write("My name is: " & name)
</script>
</body>
</html>
My name is: Jan Egil

Create an array
Arrays are used to store a series of related data items. This example demonstrates
how you can make an array that stores names. ( We are using a "for loop" to
demonstrate how you write the names. )
<html>
<body>

<script type="text/vbscript">
dim famname(5)
famname(0)="india"
famname(1)="pakistan"
famname(2)="australlia "
famname(3)="America"
famname(4)="Africa "
for i=0 to 4
document.write(famname(i) & "<br />")
next
</script>
What is a Variable?
A variable is a "container" for information you want to store. A variable's value
can change during the script. You can refer to a variable by name to see its value
or to change its value. In VBScript, all variables are of type variant, that can store
different types of data. 
Rules for Variable Names:

 Must begin with a letter 


 Cannot contain a period (.)
 Cannot exceed 255 characters

Declaring Variables
You can declare variables with the Dim, Public or the Private statement. Like
this: 
option explicit
dim name
name=some value
Lifetime of Variables
HOW LONG A VARIABLE EXISTS IS ITS LIFETIME.

When you declare a variable within a procedure, the variable can only be
accessed within that procedure. When the procedure exits, the variable is
destroyed. These variables are called local variables. You can have local
variables with the same name in different procedures, because each is recognized
only by the procedure in which it is declared.

If you declare a variable outside a procedure, all the procedures on your page can
access it. The lifetime of these variables starts when they are declared, and ends
when the page is closed.
Array Variables
Sometimes you want to assign more than one value to a single variable. Then you
can create a variable that can contain a series of values. This is called an array
variable. The declaration of an array variable uses parentheses ( ) following the
variable name. In the following example, an array containing 3 elements is
declared:
dim names(2)

The number shown in the parentheses is 2. We start at zero so this array contains
3 elements. This is a fixed-size array. You assign data to each of the elements of
the array like this:
names(0)="Tove"
names(1)="Jani"
names(2)="Stale"
Examples
Sub procedure
The sub procedure does not return a value.

<html>
<head>
<script type="text/vbscript">
sub mySub()
msgbox("This is a sub procedure")
end sub
</script>
</head>
<body>
<script type="text/vbscript">
call mySub()
</script>
<p>A sub procedure does not return a result.</p>
</body>
</html>
A sub procedure does not return a result.

Function procedure
The function procedure is used if you want to return a value.
<html>

<head>
<script type="text/vbscript">
function myFunction()
myFunction = "BLUE"
end function
</script>
</head>
<body>
<script type="text/vbscript">
document.write("My favorite color is " & myFunction())
</script>
<p>A function procedure CAN return a result.</p>
</body>
</html>

My favorite color is BLUE

A function procedure CAN return a result.

VBScript Procedures
We have two kinds of procedures: The Sub procedure and the Function
procedure.
A Sub procedure:
 is a series of statements, enclosed by the Sub and End Sub statements
 can perform actions, but does not return a value
 can take arguments that are passed to it by a calling procedure
 without arguments, must include an empty set of parentheses ()
Sub mysub()
some statements
End Sub
or
Sub mysub(argument1,argument2)
some statements
End Sub

A Function procedure:
 is a series of statements, enclosed by the Function and End Function
statements
 can perform actions and can return a value
 can take arguments that are passed to it by a calling procedure
 without arguments, must include an empty set of parentheses ()
 returns a value by assigning a value to its name
Function myfunction()
some statements
myfunction=some value
End Function
or
Function myfunction(argument1,argument2)
some statements
myfunction=some value
End Function

Function myfunction()
some statements
myfunction=some value
End Function
or
Function myfunction(argument1,argument2)
some statements
myfunction=some value
End Function

Call a Sub or Function Procedure


When you call a Function in your code, you do like this:
name = findname()

Here you call a Function called "findname", the Function returns a value that will
be stored in the variable "name".
Or, you can do like this:
msgbox "Your name is " & findname()

Here you also call a Function called "findname", the Function returns a value that
will be displayed in the message box.
When you call a Sub procedure you can use the Call statement, like this:
Call MyProc(argument)

Or, you can omit the Call statement, like this:


MyProc argument

Conditional Statements
Very often when you write code, you want to perform different actions for
different decisions. You can use conditional statements in your code to do this.
In VBScript we have three conditional statements:

The if...then...else statement

This example demonstrates how to write the if...then..else statement.


<html>

<head>
<script type="text/vbscript">
function greeting()
i=hour(time)
if i < 10 then
document.write("Good morning!")
else
document.write("Have a nice day!")
end if
end function
</script>
</head>

<body onload="greeting()">
</body>

</html>
Have a nice day!

The if...then...elseif... statement

This example demonstrates how to write the if...then...elseif statement.

<html>
<head>
<script type="text/vbscript">
function greeting()
i=hour(time)
If i = 10 then
document.write("Just started...!")
elseif i = 11 then
document.write("Hungry!")
elseif i = 12 then
document.write("Ah, lunch-time!")
elseif i = 16 then
document.write("Time to go home!")
else
document.write("Unknown")
end if
end function
</script>
</head>
<body onload="greeting()">
</body>
</html>

Unknown

The select case statement

This example demonstrates how to write the select case statement.

<html>

<body>
<script type="text/vbscript">
d=weekday(date)

select case d
case 1
document.write("Sleepy Sunday")
case 2
document.write("Monday again!")
case 3
document.write("Just Tuesday!")
case 4
document.write("Wednesday!")
case 5
document.write("Thursday...")
case 6
document.write("Finally Friday!")
case else
document.write("Super Saturday!!!!")
end select
</script>

<p>This example demonstrates the "select case" statement.<br />


You will receive a different greeting based on what day it is.<br />
Note that Sunday=1, Monday=2, Tuesday=3, etc.</p>
</body>
</html>

Output:

Finally Friday!

This example demonstrates the "select case" statement.


You will receive a different greeting based on what day it is.
Note that Sunday=1, Monday=2, Tuesday=3, etc

 if statement - use this statement if you want to execute a set of code when
a condition is true
 if...then...else statement - use this statement if you want to select one of
two sets of lines to execute
 if...then...elseif statement - use this statement if you want to select one of
many sets of lines to execute
 select case statement - use this statement if you want to select one of
many sets of lines to execute

If....Then.....Else
You should use the If...Then...Else statement if you want to
 execute some code if a condition is true
 select one of two blocks of code to execute
If you want to execute only one statement when a condition is true, you can write
the code on one line:
if i=10 Then msgbox "Hello"
There is no ..else.. in this syntax. You just tell the code to perform one action if
the condition is true (in this case if i=10).
If you want to execute more than one statement when a condition is true, you
must put each statement on separate lines and end the statement with the keyword
"End If":
if i=10 Then
msgbox "Hello"
i = i+1
end If

There is no ..else.. in this syntax either. You just tell the code to perform multiple
actions if the condition is true.
If you want to execute a statement if a condition is true and execute another
statement if the condition is not true, you must add the "Else" keyword:
if i=10 then
msgbox "Hello"
else
msgbox "Goodbye"
end If

The first block of code will be executed if the condition is true, and the other
block will be executed otherwise (if i is not equal to 10).

If....Then.....Elseif
You can use the if...then...elseif statement if you want to select one of many
blocks of code to execute:

if payment="Cash" then
msgbox "You are going to pay cash!"
elseif payment="Visa" then
msgbox "You are going to pay with visa."
elseif payment="AmEx" then
msgbox "You are going to pay with American Express."
else
msgbox "Unknown method of payment."
end If

Select Case
You can also use the SELECT statement if you want to select one of many blocks
of code to execute:
select case payment
case "Cash"
msgbox "You are going to pay cash"
case "Visa"
msgbox "You are going to pay with visa"
case "AmEx"
msgbox "You are going to pay with American Express"
case Else
msgbox "Unknown method of payment"
end select

This is how it works: First we have a single expression (most often a variable),
that is evaluated once. The value of the expression is then compared with the
values for each Case in the structure. If there is a match, the block of code
associated with that Case is executed.

Looping Statements
Very often when you write code, you want to allow the same block of code to run
a number of times. You can use looping statements in your code to do this.
In VBScript we have four looping statements:
 For...Next statement - runs statements a specified number of times. 

 For Each...Next statement - runs statements for each item in a collection


or each element of an array
 Do...Loop statement - loops while or until a condition is true
 While...Wend statement - Do not use it - use the Do...Loop statement
instead

Examples
For...next loop

This example demonstrates how to make a simple For....Next loop.


<html>
<body>

<script type="text/vbscript">
for i = 0 to 5
document.write("The number is " & i & "<br />")
next
</script>

</body>
</html>

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

Looping through headers


This example demonstrates how you can loop through the 6 headers in html.
<html>
<body>
<script type="text/vbscript">
for i=1 to 6
document.write("<h" & i & ">This is header " & i & "</h" & i & ">")
next
</script>

</body>
</html>
This is header 1

This is header 2

This is header 3
This is header 4
This is header 5
This is header 6
For...each loop
This example demonstrates how to make a simple For.....Each loop.
<html>
<body>

<script type="text/vbscript">
dim names(2)
names(0) = "Tove"
names(1) = "Jani"
names(2) = "Hege"

for each x in names


document.write(x & "<br />")
next
</script>

</body>
</html>

Tove
Jani
Hege

Do...While loop
This example demonstrates how to make a simple Do...While loop.

<html>
<body>

<script type="text/vbscript">
i=0
do while i < 10
document.write(i & "<br />")
i=i+1
loop
</script>

</body>
</html>

0
1
2
3
4
5
6
7
8
9
For...Next
You can use a For...Next statement to run a block of code, when you know how
many repetitions you want.
You can use a counter variable that increases or decreases with each repetition of
the loop, like this:
For i=1 to 10
some code
Next

The For statement specifies the counter variable (i) and its start and end values.
The Next statement increases the counter variable (i) by one.
Step Keyword
Using the Step keyword, you can increase or decrease the counter variable by the
value you specify.
In the example below, the counter variable (i) is increased by two each time the
loop repeats.
For i=2 To 10 Step 2
some code
Next

To decrease the counter variable, you must use a negative Step value. You must
specify an end value that is less than the start value.
In the example below, the counter variable (i) is decreased by two each time the
loop repeats.
For i=10 To 2 Step -2
some code
Next
Exit a For...Next
You can exit a For...Next statement with the Exit For keyword.

For Each...Next
A For Each...Next loop repeats a block of code for each item in a collection, or
for each element of an array.
The For Each...Next statement looks almost identical to the For...Next statement.
The difference is that you do not have to specify the number of items you want to
loop through.
dim names(2)
names(0)="Tove"
names(1)="Jani"
names(2)="Hege"

For Each x in names


document.write(x & "<br />")
Next

Do...Loop
You can use Do...Loop statements to run a block of code when you do not know
how many repetitions you want. The block of code is repeated while a condition
is true or until a condition becomes true.
Repeating Code While a Condition is True
You use the While keyword to check a condition in a Do...Loop statement.
Do While i>10
some code
Loop

If i equals 9, the code inside the loop above will never be executed.
Do
some code
Loop While i>10

The code inside this loop will be executed at least one time, even if i is less than
10.
Repeating Code Until a Condition Becomes True
You use the Until keyword to check a condition in a Do...Loop statement.
Do Until i=10
some code
Loop

If i equals 10, the code inside the loop will never be executed.
Do
some code
Loop Until i=10

The code inside this loop will be executed at least one time, even if i is equal to
10.
Exit a Do...Loop
You can exit a Do...Loop statement with the Exit Do keyword.
Do Until i=10
i=i-1
If i<10 Then Exit Do
Loop

The code inside this loop will be executed as long as i is different from 10, and as
long as i is greater than 10.

Inbuilt functions

Date/Time Functions
Function Description

CDate Converts a valid date and time expression to the variant


of subtype Date

Date Returns the current system date

DateAdd Returns a date to which a specified time interval has


been added

DateDiff Returns the number of intervals between two dates

DatePart Returns the specified part of a given date

DateSerial Returns the date for a specified year, month, and day

DateValue Returns a date

Day Returns a number that represents the day of the month


(between 1 and 31, inclusive)

FormatDateTime Returns an expression formatted as a date or time

Hour Returns a number that represents the hour of the day


(between 0 and 23, inclusive)

IsDate Returns a Boolean value that indicates if the evaluated


expression can be converted to a date

Minute Returns a number that represents the minute of the hour


(between 0 and 59, inclusive)

Month Returns a number that represents the month of the year


(between 1 and 12, inclusive)

MonthName Returns the name of a specified month

Now Returns the current system date and time

Second Returns a number that represents the second of the


minute (between 0 and 59, inclusive)

Time Returns the current system time

Timer Returns the number of seconds since 12:00 AM

TimeSerial Returns the time for a specific hour, minute, and


second

TimeValue Returns a time

Weekday Returns a number that represents the day of the week


(between 1 and 7, inclusive)

WeekdayName Returns the weekday name of a specified day of the


week

Year Returns a number that represents the year

Conversion Functions Top

Function Description

Asc Converts the first letter in a string to ANSI code

CBool Converts an expression to a variant of subtype Boolean

CByte Converts an expression to a variant of subtype Byte

CCur Converts an expression to a variant of subtype


Currency

CDate Converts a valid date and time expression to the variant


of subtype Date

CDbl Converts an expression to a variant of subtype Double

Chr Converts the specified ANSI code to a character

CInt Converts an expression to a variant of subtype Integer

CLng Converts an expression to a variant of subtype Long

CSng Converts an expression to a variant of subtype Single

CStr Converts an expression to a variant of subtype String

Hex Returns the hexadecimal value of a specified number


Oct Returns the octal value of a specified number

Format Functions Top

Function Description

FormatCurrency Returns an expression formatted as a currency value

FormatDateTime Returns an expression formatted as a date or time

FormatNumber Returns an expression formatted as a number

FormatPercent Returns an expression formatted as a percentage

Math Functions Top

Function Description

Abs Returns the absolute value of a specified number

Atn Returns the arctangent of a specified number

Cos Returns the cosine of a specified number (angle)

Exp Returns e raised to a power

Hex Returns the hexadecimal value of a specified number

Int Returns the integer part of a specified number

Fix Returns the integer part of a specified number

Log Returns the natural logarithm of a specified number

Oct Returns the octal value of a specified number

Rnd Returns a random number less than 1 but greater or


equal to 0

Sgn Returns an integer that indicates the sign of a specified


number

Sin Returns the sine of a specified number (angle)


Sqr Returns the square root of a specified number

Tan Returns the tangent of a specified number (angle)

Array Functions Top

Function Description

Array Returns a variant containing an array

Filter Returns a zero-based array that contains a subset of a


string array based on a filter criteria

IsArray Returns a Boolean value that indicates whether a


specified variable is an array

Join Returns a string that consists of a number of substrings


in an array

LBound Returns the smallest subscript for the indicated


dimension of an array

Split Returns a zero-based, one-dimensional array that


contains a specified number of substrings

UBound Returns the largest subscript for the indicated


dimension of an array

String Functions Top

Function Description

InStr Returns the position of the first occurrence of one


string within another. The search begins at the first
character of the string

InStrRev Returns the position of the first occurrence of one


string within another. The search begins at the last
character of the string

LCase Converts a specified string to lowercase


Left Returns a specified number of characters from the left
side of a string

Len Returns the number of characters in a string

LTrim Removes spaces on the left side of a string

RTrim Removes spaces on the right side of a string

Trim Removes spaces on both the left and the right side of a
string

Mid Returns a specified number of characters from a string

Replace Replaces a specified part of a string with another string


a specified number of times

Right Returns a specified number of characters from the right


side of a string

Space Returns a string that consists of a specified number of


spaces

StrComp Compares two strings and returns a value that


represents the result of the comparison

String Returns a string that contains a repeating character of a


specified length

StrReverse Reverses a string

UCase Converts a specified string to uppercase

Other Functions Top

Function Description

CreateObject Creates an object of a specified type

Eval Evaluates an expression and returns the result

GetLocale Returns the current locale ID

GetObject Returns a reference to an automation object from a file

GetRef Allows you to connect a VBScript procedure to a


DHTML event on your pages

InputBox Displays a dialog box, where the user can write some
input and/or click on a button, and returns the contents

IsEmpty Returns a Boolean value that indicates whether a


specified variable has been initialized or not

IsNull Returns a Boolean value that indicates whether a


specified expression contains no valid data (Null)

IsNumeric Returns a Boolean value that indicates whether a


specified expression can be evaluated as a number

IsObject Returns a Boolean value that indicates whether the


specified expression is an automation object

LoadPicture Returns a picture object. Available only on 32-bit


platforms

MsgBox Displays a message box, waits for the user to click a


button, and returns a value that indicates which button
the user clicked

RGB Returns a number that represents an RGB color value

Round Rounds a number

ScriptEngine Returns the scripting language in use

ScriptEngineBuildVersion Returns the build version number of the scripting


engine in use

ScriptEngineMajorVersion Returns the major version number of the scripting


engine in use

ScriptEngineMinorVersionReturns the minor version number of the scripting


engine in use

SetLocale Sets the locale ID and returns the previous locale ID

TypeName Returns the subtype of a specified variable

VarType Returns a value that indicates the subtype of a


specified Variable

VBScript Keywords
Keyword Description
Empty Used to indicate an uninitialized variable value. A
variable value is uninitialized when it is first created
and no value is assigned to it, or when a variable value
is explicitly set to empty.
dim x   'the variable x is uninitialized!
x="ff"   'the variable x is NOT uninitialized anymore
x=empty   'the variable x is uninitialized!
Note: This is not the same as Null!!
False Has a value equal to 0

Nothing Used to disassociate an object variable from an object


to release system resources.

Example: set myObject=Nothing


Null Used to indicate that a variable contains no valid data.

Note: This is not the same as Empty!!


True Has a value equal to -1

Example : 1

<html>

<body>

<script type="text/vbscript">

document.write("Today's date is " & date())

document.write("<br />")

document.write("The time is " & time())

</script>

</body>

</html>

Today's date is 1/13/06


The time is 9:02:20 PM
Example : 2

<html>

<body>

<p>VBScripts' function <b>WeekdayName</b> is used to get a weekday:</p>

<script type="text/vbscript">

document.write("<p>")

document.write(WeekDayName(1))

document.write("<br />")

document.write(WeekDayName(2))

document.write("</p><p>")

document.write("Get the abbreviated name of a weekday:")

document.write("<br />")

document.write(WeekDayName(1,true))

document.write("<br />")

document.write(WeekDayName(2,true))

document.write("</p><p>")

document.write("Get the current weekday:")

document.write("<br />")

document.write(WeekdayName(weekday(date)))

document.write("<br />")

document.write(WeekdayName(weekday(date), true))

document.write("</p>")

</script>

</body>

</html>
VBScripts' function WeekdayName is used to get a weekday:
Sunday
Monday
Get the abbreviated name of a weekday:
Sun
Mon
Get the current weekday:
Friday
Fri

Example : 3

<html>

<body>

<p>VBScripts' function <b>MonthName</b> is used to get a month:</p>

<script type="text/vbscript">

document.write("<p>")

document.write(MonthName(1))

document.write("<br />")

document.write(MonthName(2))

document.write("</p><p>")

document.write("Here is how you get the abbreviated name of a month:")

document.write("<br />")

document.write(MonthName(1,true))

document.write("<br />")

document.write(MonthName(2,true))

document.write("</p><p>")

document.write("Here is how you get the current month:")

document.write("<br />")

document.write(MonthName(month(date)))

document.write("<br />")

document.write(MonthName(month(date), true))
document.write("</p>")

</script>

</body>

</html>

VBScripts' function MonthName is used to get a month:


January
February
Here is how you get the abbreviated name of a month:
Jan
Feb
Here is how you get the current month:
January
Jan
Example : 4

body>

<script type="text/vbscript">

sometext="Welcome to our Web Site!!"

document.write(Left(sometext,5))

document.write("<br />")

document.write(Right(sometext,5))

</script>

</body>

</html>

Welco
ite!!

Example : 5

<html>

<body>
<script type="text/vbscript">

sometext="Welcome to our Web Site!!"

document.write(Mid(sometext, 9, 2))

</script>

</body>

</html>

to

Example : 6

<html>

<body>

<script type="text/vbscript">

sometext="Welcome to this Web!!"

document.write(Replace(sometext, "Web", "Page"))

</script>

</body>

</html>

Welcome to this Page!!

Example : 7

<html>

<body>

<script type="text/vbscript">

txt="Have a nice day!"

document.write(ucase(txt))

document.write("<br />")

document.write(lcase(txt))

</script>
</body>

</html>

HAVE A NICE DAY!


have a nice day!

Using VBScript with Forms


As the popularity of web page forms increase, so does the need to be able to
validate data before the client browser submits it to the web server. As a scripting
language, VBScript is well suited for this task. Once the form has been validated,
the same script can be used to forward the data on to the server. We will look at
both the process of validating and submitting forms.
Validating Your Forms
The process of validating forms involves checking the form to see if:
 All of the required data is proved
 The data provided is valid
Meticulous data validation scripts can be tedious to code but are well worth their
return in verifying the quality of the data.
The validation example that we will be examining does not contain anything new
in the way of VBScript. We are simply using the elements that we have learned
previously in a new way. Before reading any further you may find if beneficial to
ponder how you would validate an HTML form using the VBScript techniques
that you have learned.

VBScript Operators

Comparison Logical
Arithmetic

Description Symb Descripti Symb Descripti Symb


ol on ol on ol

Exponentiat ^ Equality = Negation Not


ion

Unary - Inequality<>  Conjuncti And


negation on

Multiplicati * Less than <  Disjuncti Or


on on

Division / Greater >  ExclusionXor


than

Integer \ Less than<= EquivalenEqv


division or equal ce
to

Modulo Mod Greater >= Implicati Imp


arithmetic than or on
equal to

Addition + Object Is    
equivalen
ce

Subtraction -        

String &        
concatenati
on

Constants: can appear as such anywhere as literals, intrinsic constants available


in VBscript, or as declarations in the declarative part of the script.

Examples:

Constant Type

"Welcome to the information century !" string


$25,000.00 currency
3.14 positive real number
-123 negative integer number
0.123e+3 number written in the scientific notation
“11/12/2002” date

- can be defined as a declaration by using the syntax:


Const constantName=expression[,…]
where:

 constantName is an user identifier defined by following the naming rules;


 expression an expression evaluated to an agreed data type whose
evaluation is considered the default value for the constant.
Examples:
            Const Pi = 3.14159
The Dictionary Object

The Dictionary object is used to store information in name/value pairs


(referred to as key and item). The Dictionary object might seem similar to
Arrays, however, the Dictionary object is a more desirable solution to
manipulate related data.

Comparing Dictionaries and Arrays:

 Keys are used to identify the items in a Dictionary object

 You do not have to call ReDim to change the size of the Dictionary
object

 When deleting an item from a Dictionary, the remaining items will


automatically shift up. Dictionaries cannot be multidimensional,
Arrays can

 Dictionaries have more built-in functions than Arrays

 Dictionaries work better than arrays on accessing random elements


frequently

 Dictionaries work better than arrays on locating items by their


content

The following example creates a Dictionary object, adds some key/item


pairs to it, and retrieves the item value for the key gr:

<%
Dim d
Set d=Server.CreateObject("Scripting.Dictionary")
d.Add "re","Red"
d.Add "gr","Green"
d.Add "bl","Blue"
d.Add "pi","Pink"
Response.Write("The value of key gr is: " & d.Item("gr"))
%>

Output:

The value of key gr is: Green

The Dictionary object's properties and methods are described below:

Properties
Property Description

CompareMode Sets or returns the comparison mode for comparing keys in a Dic
object

Count Returns the number of key/item pairs in a Dictionary object

Item Sets or returns the value of an item in a Dictionary object

Key Sets a new key value for an existing key value in a Dictionary

Object

Methods

Method Description

Add Adds a new key/item pair to a Dictionary object

Exists Returns a Boolean value that indicates whether a specified key exists
Dictionary object

Items Returns an array of all the items in a Dictionary object

Keys Returns an array of all the keys in a Dictionary object

Remove Removes one specified key/item pair from the Dictionary object

RemoveAll Removes all the key/item pairs in the Dictionary object

UNIT II
JAVASCRIPT

JavaScript is:

 JavaScript is a lightweight, interpreted programming language


 Designed for creating network-centric applications
 Complementary to and integrated with Java
 Complementary to and integrated with HTML
 Open and cross-platform

JavaScript Syntax:
A JavaScript consists of JavaScript statements that are placed within the
<script>... </script> HTML tags in a web page.
You can place the <script> tag containing your JavaScript anywhere within
you web page but it is preferred way to keep it within the <head> tags.
The <script> tag alert the browser program to begin interpreting all the text
between these tags as a script. So simple syntax of your JavaScript will be as
follows

<script ...>
JavaScript code
</script>

The script tag takes two important attributes:

 language: This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of
HTML (and XHTML, its successor) have phased out the use of this
attribute.
 type: This attribute is what is now recommended to indicate the
scripting language in use and its value should be set to "text/javascript".
So your JavaScript segment will look like:

<script language="javascript" type="text/javascript">


JavaScript code
</script>

Your First JavaScript Script:


Let us write our class example to print out "Hello World".

<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

Above code will display following result:

Hello World!

Whitespace and Line Breaks:

JavaScript ignores spaces, tabs, and newlines that appear in


JavaScript programs.

Because you can use spaces, tabs, and newlines freely in your program so
you are free to format and indent your programs in a neat and consistent
way that makes the code easy to read and understand.

Semicolons are Optional:


Simple statements in JavaScript are generally followed by a semicolon
character, just as they are in C, C++, and Java. JavaScript, however,
allows you to omit this semicolon if your statements are each placed on a
separate line. For example, the following code could be written without
semicolons

<script language="javascript" type="text/javascript">


<!--
var1 = 10
var2 = 20
//-->
</script>

But when formatted in a single line as follows, the semicolons are required:

<script language="javascript" type="text/javascript">


<!--
var1 = 10; var2 = 20;
//-->
</script>

Note: It is a good programming practice to use semicolons.

Case Sensitivity:

JavaScript is a case-sensitive language. This means that language keywords,


variables, function names, and any other identifiers must always be typed with a
consistent capitalization of letters.

So identifiers Time, TIme and TIME will have different meanings in JavaScript.

Comments in JavaScript:

JavaScript supports both C-style and C++-style


comments, Thus:
 Any text between a // and the end of a line is treated as a comment
and is ignored by JavaScript.
 Any text between the characters /* and */ is treated as a comment.
This may span multiple lines.
 JavaScript also recognizes the HTML comment opening sequence
<!--. JavaScript treats this as a single-line comment, just as it does the
// comment.
 The HTML comment closing sequence --> is not recognized by
JavaScript so it should be written as //-->.

JavaScript Placement in HTML File:


There is a flexibility given to include JavaScript code anywhere in an HTML
document. But there are following most preferred ways to include JavaScript in
your HTML file.

 Script in <head>...</head> section.


 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in and external file and then include in <head>...</head> section.
JavaScript DataTypes:

JavaScript allows you to work with three primitive


data types:

 Numbers eg. 123, 120.50 etc.


 Strings of text e.g. "This text string" etc.
 Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of
which defines only a single value.

JavaScript Variables:

Like many other programming languages, JavaScript has variables. Variables


can be thought of as named containers. You can place data into these
containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it.
Variables are declared with the var keyword as follows:

<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>

JavaScript Variable Scope:


The scope of a variable is the region of your program in which it is defined.
JavaScript variable will have only two scopes.

 Global Variables: A global variable has global scope which means


it is defined everywhere in your JavaScript code.
 Local Variables: A local variable will be visible only within a
function where it is defined. Function parameters are always local to
that function.

JavaScript Variable Names:

While naming your variables in JavaScript keep following rules in mind.

 You should not use any of the JavaScript reserved keyword as variable
name. These keywords are mentioned in the next section. For example,
break or boolean variable names are not valid.
 JavaScript variable names should not start with a numeral (0-9). They
must begin with a letter or the underscore character. For example,
123test is an invalid variable name but _123test is a valid one.
 JavaScript variable names are case sensitive. For example, Name and
name are two different variables.

JavaScript Reserved Words:


The following are reserved words in JavaScript. They cannot be used as
JavaScript variables, functions, methods, loop labels, or any object names.
abstract instanceof intswit
boolean interface long ch
break native new null syn
byte case package private chr
catch protected public oniz
char return short static ed
class super this
const throw
continue transient
debugger tr
default y
delete t
do y
double p
else e
enum o
export f
extends va
false r
final vo
finally id
float vo
for lat
function ile
goto
if
implements
import
in
The Arithmatic Operators:
There are following arithmatic operators supported by
JavaScript language:
Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example


+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by denumerator B / A will give 2
% Modulus Operator and remainder of after an integer division
B % A will give 0

++ Increment operator, increases integer value by one A++ will give 11


-- Decrement operator, decreases integer A-- will give 9
value by one

The Comparison Operators:

There are following comparison operators supported by JavaScript language


Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example


== Checks if the value of two operands are (A == B) is not true.
equal or not, if yes then condition
becomes true.
!= Checks if the value of two operands are (A != B) is true.
equal or not, if values are not equal then
condition becomes true.
> Checks if the value of left operand is (A > B) is not true.
greater than the value of right operand, if
yes then condition becomes true.
< Checks if the value of left operand is less (A < B) is true.
than the value of right operand, if yes
then condition becomes true.
>= Checks if the value of left operand is (A >= B) is not true.
greater than or equal to the value of right
operand, if yes then condition becomes
true.
<= Checks if the value of left operand is (A <= B) is true.
less than or equal to the value of right
operand, if yes then condition becomes
true.
THE LOGICAL OPERATORS:

There are following logical operators supported by JavaScript language


Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example


&& Called Logical AND operator. If both the operands are non zero then
then condition becomes true. (A && B) is true.

|| Called Logical OR Operator. If any of the two operands are non zero
then then condition becomes true.
(A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its
operand. If a condition is true then Logical NOT operator will make
false.
!(A && B) is false.

The Bitwise Operators:


There are following bitwise operators supported by JavaScript language

Assume variable A holds 2 and variable B holds 3 then:

Operator Description Example


& Called Bitwise AND operator. It performs (A & B) is 2 .
a Boolean
AND operation on each bit of its
integer arguments.
| Called Bitwise OR Operator. It performs (A | B) is 3.
a Boolean
OR operation on each bit of its integer
arguments.
^ Called Bitwise XOR Operator. It (A ^ B) is 1.
performs a Boolean exclusive OR
operation on each bit of its integer
arguments. Exclusive OR means that
either operand one is true or operand two
is true, but not both.
~ Called Bitwise NOT Operator. It is a is (~B) is -4 .
a unary operator and operates by
reversing all bits in the operand.
<< Called Bitwise Shift Left Operator. It
moves all bits in its first operand to the
left by the number of places specified in
the second operand. New bits are filled
with zeros. Shifting a value left by one
position is equivalent to multiplying by 2,
shifting two positions is equivalent to multiplying by 4, etc.
(A << 1) is 4.
>> Called Bitwise Shift Right with Sign (A >> 1) is 1.
Operator. It moves all bits in its first
operand to the right by the number of
places specified in the second
operand. The bits filled in on the left
depend on the sign bit of the original
operand, in order to
preserve the sign of the result. If the first
operand is positive, the result has zeros
placed in the high bits; if the first operand
is negative, the result has
ones placed in the high bits. Shifting a
value right one place is equivalent to
dividing by 2 (discarding the remainder),
shifting right two places is equivalent to
integer division by 4, and so on.
>>> Called Bitwise Shift Right with Zero
Operator. This operator is just like the >>
operator, except that the bits shifted in on
the left are always zero,
(A >>> 1) is 1.
THE ASSIGNMENT OPERATORS:
There are following assignment operators supported by JavaScript language:

Operator Description Example


= Simple assignment operator, Assigns values from right side operands to
left side operand
C = A + B will assigne value of
A + B into C
+= Add AND assignment operator, It adds right operand to the left
operand and assign the result to left operand
C += A is equivalent to C = C
+A
-= Subtract AND assignment operator, It subtracts right operand from the
left operand and assign the result to left operand
C -= A is equivalent to C = C - A
*= Multiply AND assignment operator, It multiplies C *= A is
equivalent to C = C * right operand with the left operand and assign the A
result to left operand
/= Divide AND assignment operator, It C /= A is equivalent to C
divides left operand with the right =C/A
operand and assign the result to left
operand
%= Modulus AND assignment operator, It
takes modulus using two operands and
assign the result to left operand

C %= A is equivalent to C = C
%A
Miscellaneous Operator

The Conditional Operator (? :)

There is an oprator called conditional operator. This first evaluates an


expression for a true or false value and then execute one of the two given
statements depending upon the result of the evaluation. The conditioanl
operator has this syntax:

Operator Description Example


?: Conditional Expression If Condition is true ? Then
value X : Otherwise value Y
The typeof Operator
The typeof is a unary operator that is placed before its single operand, which
can be of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its
operand is a number, string, or boolean value and returns true or false based on
the evaluation.

If statement:
The if statement is the fundamental control statement that allows JavaScript to
make decisions and execute statements conditionally.

Syntax:

if (expression){
Statement(s) to be executed if expression is true
}

If...else statement:
The if...else statement is the next form of control statement that allows
JavaScript to execute statements in more controlled way.

Syntax:

if (expression){
Statement(s) to be executed if expression is true
}else{
Statement(s) to be executed if expression is false
}

If...else if... Statement:

The if...else if... statement is the one level advance form of control
statement that allows
JavaScript to make correct decision out of several conditions.

Syntax:

if (expression 1){
Statement(s) to be executed if expression 1 is true
}else if (expression 2){
Statement(s) to be executed if expression 2 is true
}else if (expression 3){
Statement(s) to be executed if expression 3 is true
}else{
Statement(s) to be executed if no expression is true
}

Switch statement:

The basic syntax of the switch statement is to give an expression to


evaluate and several different statements to execute based on the value of the
expression. The interpreter checks each case against the value of the
expression until a match is found. If nothing matches, a default condition will
be used.

switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}

The while Loop

The most basic loop in JavaScript is the while loop which would be discussed in
this tutorial.

Syntax:

while (expression){
Statement(s) to be executed if expression is true
}

The do...while Loop:


The do...while loop is similar to the while loop except that the condition check
happens at the end of the loop. This means that the loop will always be
executed at least once, even if the condition is false.

Syntax:

do{
Statement(s) to be executed;
} while (expression);

The for Loop


The for loop is the most compact form of looping and includes the following
three important parts:
 The loop initialization where we initialize our counter to a
starting value. The initialization statement is executed before the loop
begins.
 The test statement which will test if the given condition is true or not.
If condition is true then code given inside the loop will be executed
otherwise loop will come out.
 The iteration statement where you can increase or decrease your counter.

You can put all the three parts in a single line separated by a semicolon.

Syntax:

for (initialization; test condition; iteration statement){


Statement(s) to be executed if test condition is true
}

The for...in Loop


for (variablename in object){
statement or block to execute
}

In each iteration one property from object is assigned to variablename and this
loop continues till all the properties of the object are exhausted.

The break Statement:


The break statement, which was briefly introduced with the switch statement, is
used to exit a loop early, breaking out of the enclosing curly braces.

The continue Statement:


The continue statement tells the interpreter to immediately start the next
iteration of the loop and skip remaining code block.

When a continue statement is encountered, program flow will move to


the loop check expression immediately and if condition remain true then it
start next iteration otherwise control comes out of the loop.

Function Definition:

Before we use a function we need to define that function. The most common
way to define a function in JavaScript is by using the function keyword,
followed by a unique function name, a list of parameters (that might be
empty), and a statement block surrounded by curly braces. The basic syntax is
shown here:

<script type="text/javascript">

<!--
function functionname(parameter-list)
{
statements
}
//-->
</script>
Calling a Function:
To invoke a function somewhere later in the script, you would simple need to
write the name of that function as follows:

<script type="text/javascript">
<!--
sayHello();
//-->
</script>

Exceptions
Exceptions can be handled with the common try/catch/finally block structure.

<script type="text/javascript">
<!--
try {
statementsToTry
} catch ( e ) {
catchStatements
} finally {
finallyStatements
}
//-->
</script>

The try block must be followed by either exactly one catch block or one
finally block (or one of both). When an exception occurs in the catch block,
the exception is placed in e and the catch block is executed. The finally block
executes unconditionally after try/catch.

Alert Dialog Box:


An alert dialog box is mostly used to give a warning message to the users. Like
if one input field requires to enter some text but user does not enter that field
then as a part of validation you can use alert box to give warning message as
follows:

<head>
<script type="text/javascript">
<!--
alert("Warning Message");
//-->
</script>
</head>

Confirmation Dialog Box:


A confirmation dialog box is mostly used to take user's consent on any
option. It displays a dialog box with two buttons: OK and Cancel.
You can use confirmation dialog box as follows:

<head>
<script type="text/javascript">
<!--
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
alert("User wants to continue!");
return true;
}else{
alert("User does not want to continue!");
return false;
}
//-->
</script>
</head>

Prompt Dialog Box:


You can use prompt dialog box as follows:

<head>
<script type="text/javascript">
<!--
var retVal = prompt("Enter your name : ", "your name here");
alert("You have entered : " + retVal );
//-->
</script>
</head>

Page Re-direction
This is very simple to do a page redirect using JavaScript at client side. To
redirect your site visitors to a new page, you just need to add a line in your
head section as follows:

<head>
<script type="text/javascript">
<!--
window.location="http://www.newlocation.com"
;
//-->
</script>
</head>

The void Keyword:


The void is an important keyword in JavaScript which can be used as a
unary operator that appears before its single operand, which may be of any
type.
This operator specifies an expression to be evaluated without returning a value.
Its syntax could be one of the following:

<head>
<script type="text/javascript">
<!--
void func()
javascript:void func()
or:
void(func())
javascript:void(func())
//-->
</script>
</head>

The Page Printing:

JavaScript helps you to implement this functionality using print function of


window object.
The JavaScript print function window.print() will print the current web page
when executed. You can call this function directly using onclick event as
follows:

<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<form>
<input type="button" value="Print" onclick="window.print()" />
</form>
</body>

Storing Cookies:
The simplest way to create a cookie is to assign a string value to the
document.cookie object, which looks like this:

Syntax:
document.cookie = "key1=value1;key2=value2;expires=date";

Reading Cookies:

Reading a cookie is just as simple as writing one, because the value of the
document.cookie
object is the cookie. So you can use this string whenever you want to access the
cookie.

The document.cookie string will keep a list of name=value pairs separated by


semicolons, where
name is the name of a cookie and value is its string value.

JavaScript - Page Redirection


What is page redirection ?

When you click a URL to reach to a page X but internally you are directed to
another page Y that simply happens because of page re-direction. This
concept is different from JavaScript Page Refresh.
.
How Page Re-direction works ?
Example 1:

This is very simple to do a page redirect using JavaScript at client side. To


redirect your site visitors to a new page, you just need to add a line in your
head section as follows:

<head>
<script type="text/javascript">
<!--
window.location="http://www.newlocation.com"
;
//-->
</script>
</head>

Example 2:

You can show an appropriate message to your site visitors before redirecting
them to a new page. This would need a bit time delay to load a new page.
Following is the simple example to implement the same:

<head>
<script type="text/javascript">
<!--
function Redirect()
{
window.location="http://www.newlocation.com";
}
document.write("You will be redirected to main page in 10 sec.");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>

Here setTimeout() is a built-in JavaScript function which can be used to


execute another function after a given time interval.

Example 3:
Following is the example to redirect site visitors on different pages based on
their browsers :

<head>
<script type="text/javascript">
<!--
var browsername=navigator.appName;
if( browsername == "Netscape" )
{
window.location="http://www.location.com/ns.htm";
}
else if ( browsername =="Microsoft Internet Explorer")
{
window.location="http://www.location.com/ie.htm";
}
else
{
window.location="http://www.location.com/other.htm";
}
//-->
</script>
</head>

JavaScript - Errors & Exceptions Handling


There are three types of errors in programming: (a) Syntax Errors and (b)
Runtime Errors (c) Logical Errors:

Syntax errors:
Syntax errors, also called parsing errors, occur at compile time for
traditional programming languages and at interpret time for JavaScript.
For example, the following line causes a syntax error because it is
missing a closing parenthesis:

<script type="text/javascript">
<!--
window.print(;
//-->
</script>

When a syntax error occurs in JavaScript, only the code contained within the
same thread as the syntax error is affected and code in other threads gets
executed assuming nothing in them depends on the code containing the error.

Runtime errors:
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).

For example, the following line causes a run time error because here syntax is
correct but at run time it is trying to call a non existed method:

<script type="text/javascript">
<!--
window.printme();
//-->
</script>

Exceptions also affect the thread in which they occur, allowing other
JavaScript threads to continue normal execution.

Logical errors:

Logic errors can be the most difficult type of errors to track down. These
errors are not the result of a syntax or runtime error. Instead, they occur when
you make a mistake in the logic that drives your script and you do not get the
result you expected.
You can not catch those errors, because it depends on your business
requirement what type of logic you want to put in your program.
The try...catch...finally Statement:
The latest versions of JavaScript added exception handling capabilities.
JavaScript implements the try...catch...finally construct as well as the throw
operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot
catch JavaScript syntax errors.
Here is the try...catch...finally block
syntax:

<script type="text/javascript">
<!--
try {
// Code to run
[break;]
} catch ( e ) {
// Code to run if an exception occurs
[break;]
}[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>

The try block must be followed by either exactly one catch block or one finally
block (or one of both). When an exception occurs in the try block, the
exception is placed in e and the catch block is executed. The optional finally
block executes unconditionally after try/catch.

Examples:
Here is one example where we are trying to call a non existing function
this is causing an exception raise. Let us see how it behaves without with
try...catch:

<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

To understand it in better way you can Try it yourself.


Now let us try to catch this exception using try...catch and display a user
friendly message. You can also suppress this message, if you want to hide this
error from a user.

<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
try {
alert("Value of variable a is : " + a );
} catch ( e ) {
alert("Error: " + e.description );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

To understand it in better way you can Try it yourself.


You can use finally block which will always execute unconditionally after
try/catch. Here is an example:

<html>

<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
try {
alert("Value of variable a is : " + a );
}catch ( e ) {
alert("Error: " + e.description );
}finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

To understand it in better way you can Try it yourself.

The throw Statement:


You can use throw statement to raise your built-in exceptions or your
customized exceptions. Later these exceptions can be captured and you can take
an appropriate action.
Following is the example showing usage of throw statement.

<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
var b = 0;
try{
if ( b == 0 ){
throw( "Divide by zero error." );
}else{
var c = a / b;
}
}catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

You can raise an exception in one function using a string, integer, Boolean or
an object and then you can capture that exception either in the same function as
we did above, or in other function using try...catch block.

The onerror() Method

The onerror event handler was the first feature to facilitate error handling for
JavaScript. The
errorevent is fired on the window object whenever an exception occurs on the
page. Example:
<html>
<head>
<script type="text/javascript">
<!--
window.onerror = function () {
alert("An error occurred.");
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

The onerror event handler provides three pieces of information to identify the
exact nature of the error:

 Error message . The same message that the browser would display for the
given error
 URL . The file in which the error occurred
 Line number . The line number in the given URL that caused the error
Here is the example to show how to extract this information

<html>
<head>
<script type="text/javascript">
<!--
window.onerror = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url ); alert("Line
number : " + line );
}
//-->

</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc(); />
</form>
</body>
</html>

You can display extracted information in whatever way you think it is better.
You can use onerror method to show an error message in case there is any
problem in loading an image as follows:

<img src="myimage.gif"onerror="alert('An error occurred loading the


image.')"/>

You can use onerror with many HTML tags to display appropriate messages
in case of errors.

JavaScript-Form Validation

Form validation used to occur at the server, after the client had entered all
necessary data and then pressed the Submit button. If some of the data that
had been entered by the client had been in the wrong form or was simply
missing, the server would have to send all the data back to the client and
request that the form be resubmitted with correct information. This was really
a lengthy process and over burdening server.
JavaScript, provides a way to validate form's data on the client's computer
before sending it to the web server. Form validation generally performs two
functions.

 Basic Validation - First of all, the form must be checked to make


sure data was entered into each form field that required it. This would
need just loop through each field in the form and check for data.
 Data Format Validation - Secondly, the data that is entered must be
checked for correct form and value. This would need to put more logic to
test correctness of data.
We will take an example to understand the process of validation. Here is the
simple form to proceed :

<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm"
onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>

<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>

Basic Form Validation:

First we will show how to do a basic form validation. In the above


form we are calling validate() function to validate data when onsubmit
event is occurring. Following is the implementation of this validate()
function:

<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{

alert( "Please provide a zip in the format #####." );


document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>

Data Format Validation:


Now we will see how we can validate our entered form data before
submitting it to the web server.

This example shows how to validate an entered email address which means
email address must contain at least an @ sign and a dot (.). Also, the @ must
not be the first character of the email address, and the last dot must at least be
one character after the @ sign:

<script type="text/javascript">
<!--
function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>

Javascript - Browsers Compatibility


It is important to understand the differences between different browsers in
order to handle each in the way it is expected. So it is important to know which
browser your Web page is running in.

To get information about the browser your Web page is currently running in,
use the built-in
navigator object.

Navigator Properties:
There are several Navigator related properties that you can use in your Web
page. The following is a list of the names and descriptions of each:

Property Description

appCodeName This property is a string that contains the code name of the
browser, Netscape
for Netscape and Microsoft Internet Explorer for Internet Explorer.

appVersion This property is a string that contains the version of the


browser as well as other useful information such as its
language and compatibility.

language This property contains the two-letter abbreviation for the


language that is used by the browser. Netscape only.

mimTypes[] This property is an array that contains all MIME types supported
by the client.
Netscape only.

platform[] This property is a string that contains the platform for which the
browser was compiled."Win32" for 32-bit Windows operating
systems

plugins[] This property is an array containing all the plug-ins that have
been installed on the client. Netscape only.

userAgent[] This property is a string that contains the code name and
version of the browser. This value is sent to the originating
server to identify the client

Navigator Methods:
There are several Navigator-specific methods. Here is a list of their names and
descriptions:

Method Description

javaEnabled() This method determines if JavaScript is enabled in the


client. If
JavaScript is enabled, this method returns true;
otherwise, it returns false.

plugings.refresh This method makes newly installed plug-ins available


and populates the plugins array with all new plug-in
names. Netscape only.

preference(name,value) This method allows a signed script to get and set


some Netscape preferences. If the second parameter is
omitted, this method will return the value of the
specified preference; otherwise, it sets the
value. Netscape only.

taintEnabled() This method returns true if data tainting is enabled


and false otherwise.
Browser Detection:
There is a simple JavaScript which can be used to find out the name of a
browser and then accordingly an HTML page can be served to the user.
<html>
<head>
<title>Browser Detection Example</title>
</head>
<body>
<script type="text/javascript">
<!--
var userAgent = navigator.userAgent;
var opera = (userAgent.indexOf('Opera') != -1);
var ie = (userAgent.indexOf('MSIE') != -1); var
gecko = (userAgent.indexOf('Gecko') != -1); var
netscape = (userAgent.indexOf('Mozilla') != -1);
var version = navigator.appVersion;
if (opera){
document.write("Opera based browser");
// Keep your opera specific URL here.
}else if (gecko){
document.write("Mozilla based browser");
// Keep your gecko specific URL here.
}else if (ie){
document.write("IE based browser");
// Keep your IE specific URL here.
}else if (netscape){
document.write("Netscape based browser");
// Keep your Netscape specific URL here.
}else{
document.write("Unknown browser");
}
// You can include version to along with any above condition.
document.write("<br /> Browser version info : " + version );
//-->
</script>
</body>
</html>

Javascript - The String Object


The String object let's you work with a series of characters and wraps
Javascript's string primitive data type with a number of helper methods.
Because Javascript automatically converts between string primitives and String
objects, you can call any of the helper methods of the String object on a string
primitive.

Syntax:
Creating a String object:

var val = new String(string);

The string parameter is series of characters that has been properly encoded.

String Properties:
Here is a list of each property and their description.
Property Description

constructor Returns a reference to the String function that created the object.

length Returns the length of the string.

prototype The prototype property allows you to add properties and


methods to an object.

String Methods
Here is a list of each method and its description.

Method Description

charAt() Returns the character at the specified index.


charCodeAt() Returns a number indicating the Unicode value of the
character at the given index.
concat() Combines the text of two strings and returns a new string.
indexOf() Returns the index within the calling String object of the first
occurrence of the specified value, or -1 if not found.
lastIndexOf() Returns the index within the calling String object of the last
occurrence of the specified value, or -1 if not found.
localeCompare() Returns a number indicating whether a reference string
comes before or after or is the same as the given string in
sort order.
match() Used to match a regular expression against a string.
replace() Used to find a match between a regular expression and a
string, and to replace the matched substring with a new
substring.
search() Executes the search for a match between a regular
expression and a specified string.

slice() Extracts a section of a string and returns a new string.


split() Splits a String object into an array of strings by separating
the string into substrings.
substr() Returns the characters in a string beginning at the
specified location through the specified number of
characters.
substring() Returns the characters in a string between two indexes into the
string.
toLocaleLowerCase() The characters within a string are converted to
lower case while respecting the current locale.
toLocaleUpperCase() The characters within a string are converted to
upper case while respecting the current locale.
toLowerCase() Returns the calling string value converted to lower case.
toString() Returns a string representing the specified object.
toUpperCase() Returns the calling string value converted to uppercase.

valueOf() Returns the primitive value of the specified object.

String HTML wrappers

Here is a list of each method which returns a copy of the string wrapped inside
the appropriate
HTML tag.

Method Description

anchor() Creates an HTML anchor that is used as a hypertext target.

big() Creates a string to be displayed in a big font as if it were in a


<big> tag.

blink() Creates a string to blink as if it were in a <blink> tag.

bold() Creates a string to be displayed as bold as if it were in a <b> tag.

fixed() Causes a string to be displayed in fixed-pitch font as if it were in


a <tt> tag

fontcolor() Causes a string to be displayed in the specified color as if it


were in a <font color="color"> tag.

fontsize() Causes a string to be displayed in the specified font size as if it


were in a
<font size="size"> tag.

italics() Causes a string to be italic, as if it were in an <i> tag.

link() Creates an HTML hypertext link that requests another URL.

small() Causes a string to be displayed in a small font, as if it were in a


<small>
tag.

strike() Causes a string to be displayed as struck-out text, as if it were in


a <strike>
tag.

sub() Causes a string to be displayed as a subscript, as if it were in a


<sub> tag

sup() Causes a string to be displayed as a superscript, as if it were in a


<sup> tag

Javascript - The Arrays Object

The Array object let's you store multiple values in a single variable.

Syntax:
Creating a Array object:

var fruits = new Array( "apple", "orange", "mango" );

The Array parameter is a list of strings or integers. When you specify a


single numeric parameter with the Array constructor, you specify the initial
length of the array. The maximum length allowed for an array is
4,294,967,295.
You can create array by simply assigning values
as follows:

var fruits = [ "apple", "orange", "mango" ];

You will use ordinal numbers to access and to set values inside an array as
follows:

 fruits[0] is the first element


 fruits[1] is the second element
 fruits[2] is the third element

Array Properties:
Here is a list of each property and their description.

Property Description

constructor Returns a reference to the array function that created the object.

index The property represents the zero-based index of the match in the
string

input This property is only present in arrays created by regular


expression matches.

length Reflects the number of elements in an array.


prototype The prototype property allows you to add properties and
methods to an object.

Array Methods
Here is a list of each method and its description.

Method Description

concat() Returns a new array comprised of this array joined with other
array(s)
and/or value(s).

every() Returns true if every element in this array satisfies the


provided testing function.

filter() Creates a new array with all of the elements of this array
for which the provided filtering function returns true.

forEach() Calls a function for each element in the array.

indexOf() Returns the first (least) index of an element within the array
equal to the specified value, or -1 if none is found.

join() Joins all elements of an array into a string.

lastIndexOf() Returns the last (greatest) index of an element within the array
equal to the specified value, or -1 if none is found.

map() Creates a new array with the results of calling a provided


function on every element in this array.

pop() Removes the last element from an array and returns that
element.

push() Adds one or more elements to the end of an array and


returns the new length of the array.

reduce() Apply a function simultaneously against two values of the


array (from left- to-right) as to reduce it to a single value.

reduceRight() Apply a function simultaneously against two values of the


array (from right- to-left) as to reduce it to a single value.

reverse() Reverses the order of the elements of an array -- the first


becomes the last, and the last becomes the first.
shift() Removes the first element from an array and returns that
element.

slice() Extracts a section of an array and returns a new array.

some() Returns true if at least one element in this array satisfies


the provided testing function.

toSource() Represents the source code of an object

sort() Sorts the elements of an array.

splice() Adds and/or removes elements from an array.

toString() Returns a string representing the array and its elements.

unshift() Adds one or more elements to the front of an array and


returns the new length of the array.

JavaScript -The Date Object


The Date object is a datatype built into the JavaScript language. Date objects
are created with the new Date( ) as shown below.

Once a Date object is created, a number of methods allow you to operate on it.
Most methods simply allow you to get and set the year, month, day, hour,
minute, second, and millisecond fields of the object, using either local time or
UTC (universal, or GMT) time.

Syntax:
Here are different variant of Date()
constructor:
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])

Note: Paramters in the brackets are always optional

Here is the description of the parameters:

 No Argument: With no arguments, the Date( ) constructor creates a Date


object set to the current date and time.
 milliseconds: When one numeric argument is passed, it is taken as
the internal numeric representation of the date in milliseconds, as
returned by the getTime( )
o method. For example, passing the argument 5000 creates a date
that represents five
o seconds past midnight
on 1/1/70.
 datestring:When one string argument is passed, it is a string
representation of a date, in the format accepted by the Date.parse( )
method.
 7 agruments: To use the last form of constructor given above, Here is the
description of each argument:
1. year: Integer value representing the year. For compatibility (in
order to avoid
the Y2K problem), you should always specify the year in full;
use 1998, rather than 98.
2. month: Integer value representing the month, beginning with 0 for
January to
11 for
December.
3. date: Integer value representing the day of the month.
4. hour: Integer value representing the hour of the day (24-hour
scale).
5. minute: Integer value representing the minute segment of a time
reading.
6. second: Integer value representing the second segment of a time
reading.
7. millisecond: Integer value representing the millisecond
segment of a time reading.

Date Properties:
Here is a list of each property and their description.

Property Description

constructor Specifies the function that creates an object's prototype.

prototype The prototype property allows you to add properties and


methods to an object.

Date Methods:
Here is a list of each method and its description.

Method Description

Date() Returns today's date and time


getDate() Returns the day of the month for the specified date
according to local time.

getDay() Returns the day of the week for the specified date
according to local time.

getFullYear() Returns the year of the specified date according to local


time.

getHours() Returns the hour in the specified date according to local


time.

getMilliseconds() Returns the milliseconds in the specified date


according to local time.

getMinutes() Returns the minutes in the specified date according to


local time.

getMonth() Returns the month in the specified date according to


local time.

getSeconds() Returns the seconds in the specified date according to


local time.

getTime() Returns the numeric value of the specified date as the


number of milliseconds since January 1, 1970,
00:00:00 UTC.

getTimezoneOffset() Returns the time-zone offset in minutes for the current


locale.

getUTCDate() Returns the day (date) of the month in the


specified date according to universal time.

getUTCDay() Returns the day of the week in the specified date


according to universal time.

getUTCFullYear() Returns the year in the specified date according to


universal time.

getUTCHours() Returns the hours in the specified date according


to universal time.

getUTCMilliseconds() Returns the milliseconds in the specified date


according to universal time.

getUTCMinutes() Returns the minutes in the specified date according


to universal time.

getUTCMonth() Returns the month in the specified date according


to universal time.

getUTCSeconds() Returns the seconds in the specified date according


to universal time.

getYear() Deprecated - Returns the year in the specified date


according to local time. Use getFullYear instead.

setDate() Sets the day of the month for a specified date


according to local time.

setFullYear() Sets the full year for a specified date according to local
time.

setHours() Sets the hours for a specified date according to local


time.

setMilliseconds() Sets the milliseconds for a specified date according to


local time.

setMinutes() Sets the minutes for a specified date according to local


time.

setMonth() Sets the month for a specified date according to local


time.

setSeconds() Sets the seconds for a specified date according to local


time.

setTime() Sets the Date object to the time represented by a


number of milliseconds since January 1, 1970,
00:00:00 UTC.

setYear() Deprecated - Sets the year for a specified date


according to local time. Use setFullYear instead.

toDateString() Returns the "date" portion of the Date as a human-


readable string.

toLocaleDateString() Returns the "date" portion of the Date as a string,


using the current locale's conventions.

toLocaleFormat() Converts a date to a string, using a format string.

toLocaleString() Converts a date to a string, using the current locale's


conventions.

toLocaleTimeString() Returns the "time" portion of the Date as a string,


using the current locale's conventions.

toSource() Returns a string representing the source for an


equivalent Date object; you can use this value to
create a new object.

toString() Returns a string representing the specified Date object.

toTimeString() Returns the "time" portion of the Date as a human-


readable string.

valueOf() Returns the primitive value of a Date object.

Date Static Methods:


In addition to the many instance methods listed previously, the Date object
also defines two static methods. These methods are invoked through the Date( )
constructor itself:

Method Description
Date.parse( ) Parses a string representation of a date and time and
returns the internal millisecond representation of that
date.

Javascript - The Math Object


The math object provides you properties and methods for mathematical
constants and functions.
Unlike the other global objects, Math is not a constructor. All properties and
methods of Math are static and can be called by using Math as an object
without creating it.
Thus, you refer to the constant pi as Math.PI and you call the sine function as
Math.sin(x), where x is the method's argument.

Syntax:

Here is the simple syntax to call properties and methods of Math.

var pi_val = Math.PI;


var sine_val = Math.sin(30);

Math Properties:
Here is a list of each property and their description.

Property Description

E Euler's constant and the base of natural logarithms,


approximately 2.718.

LN2 Natural logarithm of 2, approximately 0.693.

LN10 Natural logarithm of 10, approximately 2.302.

LOG2E Base 2 logarithm of E, approximately 1.442.

LOG10E Base 10 logarithm of E, approximately 0.434.

PI Ratio of the circumference of a circle to its diameter,


approximately
3.14159.

SQRT1_2 Square root of 1/2; equivalently, 1 over the square root of 2,


approximately
0.707.

SQRT2 Square root of 2, approximately 1.414.

Math Methods
Here is a list of each method and its description.

Method Description

abs() Returns the absolute value of a number.

acos() Returns the arccosine (in radians) of a number.

asin() Returns the arcsine (in radians) of a number.

atan() Returns the arctangent (in radians) of a number.

atan2() Returns the arctangent of the quotient of its arguments.

ceil() Returns the smallest integer greater than or equal to a number.

cos() Returns the cosine of a number.

exp() Returns EN, where N is the argument, and E is Euler's


constant, the base of the natural logarithm.

floor() Returns the largest integer less than or equal to a number.

log() Returns the natural logarithm (base E) of a number.

max() Returns the largest of zero or more numbers.

min() Returns the smallest of zero or more numbers.

pow() Returns base to the exponent power, that is, base exponent.

random() Returns a pseudo-random number between 0 and 1.

round() Returns the value of a number rounded to the nearest integer.

sin() Returns the sine of a number.

sqrt() Returns the square root of a number.

tan() Returns the tangent of a number.

toSource() Returns the string "Math".


UNIT III
THE JAVASCRIPT DOCUMENT OBJECT MODEL:

To create an interactive web page it is imperative that the browser


continues to recognize individual HTML objects even after they are rendered in
the browser window. This allow the browser to access the properties of these
objects using the buil-in methods of the objects. Once the properties of an object
are accessible then the functionality of the object can be controlled at will.

Javascript enabled browser are capable of recognizing individual


objects in an html page after the page has been rendered in the browser because
the javascript enabled browser recognizes and uses the Document Object Model
(DOM)

Using the document object model(DOM) javascript enabled browser identify


the collection of webpage objects that have to be dealt with while rendering an
HTML based webpage in the browser window

The HTML objects which belong to the DOM have a descending


relationship with each other.

The topmost object which belong to the DOM is the browser’s


window the next level in the DOM is the document displayed in the browser’s
window.

The navigator :- netscape navigator, internet explorer ,opera, mosaic and so


on.

Window

|->document

|->anchor

|->link

|->form

|->textbox

|->textarea

|->radiabutton

|->checkbox

|->select

|->button

Javascript’s DOM

UNDERSTANDING OBJECTS IN HTML:


HTML can be used to create a graphical user interface ( GUI) IN A WEB
PAGE. HTML IS CAPABLE OF THE ACCESSING AND USING A NUMBER
OF OBJECTS THAT ACTUALLY BELONG TO THE OPERATING SYATEM
.ONE SUCH OBJECT IS A TEXTBOX. A ‘TEXTBOX’ IS USED IN AN
HTML FORM TO ACCEPT USER INPUT.

Java script facilities access to all the methods of a text. One of the methods of the
textbox permits access to the contents of the text box hence. Javascript can
process the contents of any textbox in an html form.

PROPERTIES OF HTML OBJECTS:

Just like real world objects, html objects have number of properties that
determine the behavior of that object. An object properties can be referenced as:

ObjectName.Property.Name

METHODS OF HTML OBJECTS:

Methods of an objects are used to set or get a value of an object’s property.


Thus determining how an objects behaves. An object method can be referenced
as:

ObjectName.MethodName

HOW A JAVASCRIPT ENABL;ED BROWSER HANDLES THE DOCUMENT


OBJECT:

 IMAGES
 Image maps
 Hyperlinks
 Frames
 Anchors
 Applets
 Multimedia objects such a audio files, streaming video files
 A from with various from element

The browser creates one array in memory per html object in the document thus
registering each of these html objects.
HANDLING (WEB PAGE) EVENTS USING JAVASCRIPT:

A web page event could be associated with the action of the mouse cursor on
the web page. such as

 A mouse-click on an object in a web page


 The movement of the mouse cursor across a webpage
 The mouse cursor hovering at a specific place on a web page and so on

These will be events recognized by the window object of the DOM.

Javascript approach to working with web page element is a multi step process;

 Identify a webpage object


 Choose an appropriate event associated with the object
 Have a standard method of connecting an object’s event and javascript
code snippets. Javascript event handlers mapped to an objects event do
this.

Javascript, event handlers can be divided into two types interactive and non-
interactive.

An interactive event handler depends on user interaction with an html page. For
example the javascript on mouseover event handler is an interactive event
handler. This requires the user to move the mouse cursor over a web page.

NAMED JAVASCRIPT EVENT HANDLERS:

JAVASCRIPT EVENT WILL BE CALLED WHEN


HANDLER

On abort The loading of an image is aborted as a


result of user action

onblur A document window, frame set, or form


element loses current input focus.

On change A text field,textarea, file-uploaded,field


or selection is modified and loses the
current input focus.

On click A link, client-side image map area or


document is cliked

On dbclick A link, client-side image map area or


document is double clicked

onDragDrop A dragged object id dropped in a


window or frame

onError An error occurs is dropped in a window


or frame

onFocus A document , window, frameset, or


form element receives the current input
focus

onKeyDown The user presses a key

onKeyPress The user presses and releases a key

onKeyUp The user releases a key

onLoad An image, document or frame set is


loaded

onMouseDown The user moves the mouse

onMouseMove The user moves the mouse

onMouseOut The mouse is moved out of a link or an


area of client side image map

onMouseOver The mouse is moved over a link or an


area of a client side image map

onMouseUp The user releases a mouse button

onReset The user resizes a from by clicking on


the form’s reset button

onResize The user resizes a window or frame

Onselect Text is selected in a text field or a text


area

onSubmit The user presses a form’s submit


button

onUnload The user exits a document or frame set


COOKIES

That is after a user sends a request to the server and a web page is returned.
The server forgets all about the user and the page that has been downloaded. If the
user clicks on link the server doesn’t have background information about what
page the user is coming from and more importantly, if the user returns to the page
at a later date there is no information available to the server about the user’s
previous action on the page.

Maintaining state can be important to developing complex interactive


applications. However browsers address this problem with cookies which is a
method of storing information locally in the browser and sending it to the sever
whenever the appropriate pages are requested by the user.

The term cookies has no special significance it is just a name in the same way
java is just a name for sun’s object-oriented programming language.

When a user request a page an HTTP request is sent to the server. The request
includes a header that defines several pieces of information including the page
being requested.

The server returns an HTTP response that also includes a header. The header
contains information about the document being returned including its MIME
type . these header all contain one or more fields of information in a basic format.

FieldName:Information

Cookie information is hared between the client browser and a server using fields
in the HTTP headers when the user requests a page for the first time a cookie can
be stored in the browser by a set-cookie entry in the header of the response from
the server . the set-cookie field includes the information to be stored in the cookie
along with several optional pieces of information including an expiry date,path,
and server information and if the cookie requires security..

SETTING A COOKIE:

SYNTAX:

Set-cookie: NAME=value ; EXPIRES =date ; PATH= path ;DOMAIN


=domain; SECURE

The NAME= value is the only required piece of information that must be
included in the set-cookie field all other entries are optional

NAME DESCRIPTION

NAME = value Specifies the name of the cookie

PATH= path Specifies the path portion of the URLs for which the cookie
is valid if the URL matches both the PATH and the
DOMAIN then the cookie is sent to the server in the request
header.(if left unset the value of the PATH is the same as
the document that set the cookie

EXPIRES =date Specifies the expiry date of the cookie. After this date the
cookie will no longer be stored by the client or sent to the
server( DATE takes the form weekday, DD-MON-YY
HH:MM:SS GMT- dates are only stored in Greenwich
mean time) . by default the value of expires is set to the end
of current navigator session.

DOMAIN= Specifies the domain portion of the URLs for which the
domain cookie is valid. The default values for this attribute is the
domain of the current document setting the cookie.

SECURE Specifies that the cookie should only be transmitted over a


secure link (i.e.. to HTTP server using the SSL protocol-
know as HTTPS server)

FORMS USED BY A WEB SITE:

 The javascript FORM object created when the HTML <FORM>


</FORM> tags are encountered in an HTML program.
 Describes how javascript can be associated with an HTML form’s GUI
controls

THE FORM OBJECT:

User input is captured in a FORM. HTML provides the


<FORM>…</FORM>

Tags with which an html form can be created to capture user input..

As soon as the <FORM>….</FORM> tags are encountered in an html


programs by a javaScript enabled browser the browser creates a ‘forms array’ in
memory. This array tracks the number of form objects described in the html
program.

Common HTML objects used between the <FROM>…</FORM> tags are


text . TEXTAREA,RADIO BUTTONS, CHECK BOXES and so on..

THE FORM OBJECT’S METHOD:

The form object has properties like NAME, METHOD AND ACTION

METHOD:
The METHOD property of form is used to specify the method used to send
data captured by various form elements back to the web server . the method used
can be either GET or POST.

The GET method sends the data captured by form element to the web server
encoded into a URL, which points to wed server. The data captured in form
element is appended to the URL

The POST method sends the data captured by form elements back to the web
server as a separate bit-stream of data. When there is a large amount of data to be
sent back to the web server, this is the methos used.

If the method attribute is not specified within the


<FORM>…</FORM> tags the default method used by the browser to send data
back to the web server is the get method, i.e., as an encoded URL

ACTION:

The ACTION attribute of the <FORM>..</FORM> tags points to the URL of


a program on the web server that will process the form data captured and being
sent back..

Commonly used wed server side scripting languages are :

 Javascript-( used with the Netscape suite of web servers)


 Vb script and ASP –(used with the Microsoft suite of web server)
 Perl, ANSI C- (used with the Unix based suite of web server)…

The HTML form elements that can be specified as attributes to the <INPUT> tags
are…

FORM DESCRIPTION & SYNTAX


ELEMENTS

Text A text field (<INPUT Type=”TEXT”>)

Password A password text field in which each keystroke appears as an


asterisk(*) (<INPUT Type =”password”>)

Button A new element that provides a button other than a submit or


reset button (<INPUT Type =”BUTTON”>)

Checkbox A checkbox (<INPUT Type =”CHECKBOX”>)

Radio A radio button (<INPUT Type =”RADIO”>)

Reset A reset button (<INPUT Type =”RESET”>)


Submit A submit button (<INPUT Type =”SUBMIT”>)

Select A selection list (<SELECT><OPTION>option1</OPTION>

<OPTION>OPTION2</SELECT>

TextArea A multi line text entry field (<TEXTAREA>default text


</TEXTAREA>)

Hidden A field that may contain a value but is not displayed within a
form (<INPUT Type =”HIDDEN”>)

PROPERTIES OF FORM ELEMENTS:

FORM ELEMENT PROPERTY NAME DESCRIPTION


NAME

Text

Password

Textarea

Button

Radio Name Indicates the name of


object. This name can be
Checkbox used for referencing the
Select object in the future, when
required
Submit

Reset

Hidden

Fileupload

Text

Password

Textarea

Button Indicates the current


value of the element.
Radio Value

Checkbox
Select

Submit

Reset

Hidden

Fileupload It contains any value


indicated in the option
Select tag.

Text Indicates the default


value of the object.
Password Default value

Textarea

Button Indicates the current


status of the object ,
Radio checked
whether checked or
Checkbox unchecked.

Radio Default checked Indicates the default


status of the element
Checkbox

Radio Length Indicates the number of


radio buttons in a group.

Radio button Index Indicates the index value


of the currently selected
radio button.

Contains the index value


In the current option of
the options array.
METHODS OF FORM ELEMENTS:

FORM ELEMENT METHOD NAME DESCRIPTION


METHOD

Text Fires when the form


cursor enters into an
Password onFocus()
object.
Textarea

Text Fires when the form


cursor is moved away
Password onBlur()
from an object.
Textarea

Text Fires when text is


selected in an object.
Password onSelect()

Textarea

Text

Password onChange() Fires when text is


changed in an object.
Textarea

Button

Radio

Checkbox onClick() Fires when an object is


clicked on.
Submit

Reset
UNIT IV

ASP.NET LANGUAGE STRUCTURE

1. Define page structure?


The page simply some text to the visitor through their browser
<%@ page language=VB debug=true %>
The first line on the page is called a compiler directive. We define a script block.
Notice that we indicate that the code
Should run on their browser.
<script runat=server>
Within the opening and closing script tags, all the code is contained within
procedures .Here, a sub procedure is defined as opposed to a function.

2. Define Page?
Every ASP.NET page you create inherits the page class. That means that the Structure of
your ASP.NET page is based on the structure of an object called page.

PAGE EVENTS
Page _Load Event
Every time your page loads, either initially when the visitor browses to it or when the
page is called additionally through a button being clicked.
Sub page_load (ByVal sender as object, Byval E as EventArgs)
'Code goes here.
End sub

Page_UnloadEvent
When the compiler is totally done with running your page, you have one last place to put
clean-up or any terminating code, and that is in the Page_UnloadEvent.
The procedure is defined as a sub and contains two parameters. The first is of type
object, and the second is of type EventArgs.

IspostBackProperty
As already explained, the page_Load event time a page is loaded.
If IspostBack = false Then

IsValidProperty
This property is used inconjunction with validation controls.
If IsValid = True

3. Directives of Asp.Net?

1. Compiler directives
Compiler directives are special tags that you add to your ASP.NET page that indicate
how the page should run or be compiled.
@page directive
You have already seen the @page directive used in the two samples cited in the previous
sections like this:
<%@ page
Language=VB
Debug=true
%>
Language=VB
Debug=true
Buffer=false

2.@Import Directive
The @Import Directive allows you to include additional libraries or namespace in your
page so that you can instantiate controls or object from that namespace.
<%@ Import Namespace="system.data" %>
<%@ Import Namespace="system.data.SQLclient"%>

3.@OutputCache Directive
Your page will run over again displaying the exact same data for an hour.
<%@ OutPutCache Duration=3600 VaryByparam="none" %>
Chapter-2
HTML Server control

4. Define HTML Anchor control?


The HTML Anchor control allows you to directly render the HTML Anchor
element,<A></A>.The control can be used in two ways;it can be used as a standard
anchor that links to some other page
<a
runat=server
id="control Name"
'other properties
>

Standard text displayed in link.


</a>
<a
But with this control, we indicate that we want it processed by the server before
rendering it to the client browser:
runat=server
id="control Name"
That is followed by the closing tag of the element:
</a>
<a
id="Anchor1"
runat=server
>
</a>

5. DefineHTMLForm and Form Input Controls?

HTMLForm Control
The HTML Form control will be found on almost all of your ASP.NET pages. It
provides a way for you maintain the state between calls. The control automatically links
the page back to itself for processing
<form
id="My Form"
Method="post"
runat="server"
>
'Body of the page goes here.
</Form>

Input Controls
Within an HTMLForm control, you need to define other controls that allow the visitor
to enter information that you wish to receive and process.
To create a text box, you would use an HTMLInputText control:
<Input
id="MyTextBox"
runat="server"
Type="text"
Max Length="50"
size="20"
>
<Input
id="password"
runat="server"
Type="password"
MaxLength="50"
size="20"
>
Another type of text box that you see in html forms is the TextArea form element.
<Text Area
id="my TextArea"
runat="server"
cols="20"
Rows="4"
>

Submitting the form


Once you have your controls on the form, you need a way to submit the form for
processing.
<input
runat="server"
Type="submit"
Value="Text on button"
Onserverclick="submitbtn_click"
>

Basic Web server control

1. Label control
One of the most basic controls in the system.Web.UI.Web controls namespace is the
Label control. The control is very useful for statically or dynamically placing text onto
as ASP.NET page.
<asp:Label
id="labelName"
runat="server"
'Other properties
/>
As with all the other controls in this namespace the opening tag for the controlsdefinition
includes the text"asp:" and is followed by the name of the control:
<asp:label
We then follow that with the name of the control so that we can refer to it in code:
id="Label Name"
Next, we indicate that the control should be run by the server:
runat="server"
That is followed by the inclusion of other properties here, or you can define them in
code:
'Other properties
/>

Other properties

The control also includes numerous properties that allow you to format the style of the
control .You can select the font style of the control:
<asp:Label
id="Label Name"
runat="sever"
font-Size="12pt"
font-Bold="True"
font-Italic="True"
font-underline="false"
font-Strikeout="True"
font-name="Lucida console"
/>

2. Textbox Control
Based on the properties you set, the control can be rendered as a standard textbox, a
password text box, or a Text area HTML form element
<asp:Textbox
id="my TextBox"
runat=server
'other properties
/>
The definition begins with the "asp:"text followed by the name of the control,
Text Box:
<asp:Text box
Then you give your Text Box control a name so that you can refer to it in code:
id="My Textbox"
You also indicate that it will run on the server:
runat=server
Typically, you will then set any other style attributes within the tag definition:
'Other properties
/>
<asp:TextBox
id="my TextBox"
runat=server
Text Mode="Multiline"
Rows="7"
Columns="60"
/>

3. Button Control

The Button control is rendered as either a standard submit button control or as


aCommand button control. The way each is defined is similar.
<asp: button
id="but submit"
text="text on button"
on click="procedure Name"
runat="server"
/>

You start by stating the type of control that we are defining with the"asp"text:
<asp: button
You can give the control a name so that you can reference it in code:
id="but submit"
The Text property is used to set the text the visitor sees on the surface of the button:
text="text on button"
The next property, onclick is set to the name of the procedure that you want to run when
the button is clicked:
Onclick="procedureName"
You also need to indicate that the button is to be run on
the server:
runat="server"
/>
other properties
<asp:button
id="butcommand"
text="control text"
CommandName="passedtoprocedure"
Commandargument="passedtoprocedure"
Oncommand="procedureName"
runat="server"
/>

4. Link buttonControl
Almost identical to the button control is the link button control. Just like the button
control,the linkbutton control can be rendered as a submit type or a command type. Here
is the basic structure of the control definition:
<asp:LinkButton
id="myLinkButton"
runat="server"
'other properties
/>

<asp:linkButton
You then give the control a name,
id="MyLinkButton"
Indicate that the server should run it,
runat="server"
and supply values for other properties:
'other properties
/>
Other properties:
<asp:linkButton
id="butsortD"
text="sort z-a"
CommandName="sort"
CommandArgument="D"
on command="submitbtn2_click"
runat="server"
/>
5. ImageButtoncontrol
Another way that you can create a submit type of button or a command type of button is
through the image button control.The control differs from the button control in two
important ways.First,the control displays an image instead of a
standardbutton. Second when you create a submit type of image button, you can also
retrieve the position on the images where the visitor clicked.
<asp:imageButton
id="myImageButton"
runat="server"
'Other properties
/>

Other properties:
ImageURL="pathtoImage"
ImageAlign="Alignmentposition"
AlternateText="some Text"

6. Checkbox control
It provides for the mechanism to retrieve a yes/no type of response form the visitor to
the page.This basic tag for the control is as follows:
<asp:checkBox
id="mycheckbox"
runat="server"
'other properties
/>
You start by defining the control as a checkbox control:
<asp"checkbox
You can then supply the checkbox control with a name:
id="mycheckbox"
Then you indicate that it is to be run by the server,
runat="server"
and supply any other property values:
'other properties
/>

Other properties
<asp:checkbox
id="chk1"
text="do you like the colour blue?"
textalign="left"
font-size="12pt"
font-name="comic sans ms"
runat="server"
/>

7.Radiobutton control
The radio Button control renders itself as an HTML Radio form element. As in the case
of the CheckBox control, the text that appears with the Radiobutton can be placed before
or after the RadioButton and is rendered in the HTML within a Span tag.
<asp:RadioButton
id="MyRadio"
runat="server"
'Other properties
/>
Other properties
<asp:Radiobutton
id="rdcolorRed"
text="red"
font-size="12pt"
font-name="comic sans ms"
GroupName="rgcolor"
Checked="true"
runat="server"
/>

8. Hyperlink control
This control allows you to place an Anchor HTML tag into your ASP.NET page
<asp:HyperLink
id="hyp1"
runat="server"
'Other properties
/>
<asp:HyperLink
We then give the control a name,
id="htp1"
Indicate that it runs on the server,
runat='="sever"
and supply other properties, such as font and colour properties that we reviewed earlier
in this chapter:
'Other properties
/>
Other properties
<asp:HyperLink
id="hyp2"
runat="server"
text="click to go to google"
imageURL="./button.gif"
target="new"
navigateURL="HTTP://www.google.com"
/>

9. Image control
This control allows you to dynamically display an image tag on anASP.NET page.
The control has this basic structure:
<asp:Image
id="imgmyimage"
runat="server"
/>
You define the control with the “asp:" text followed by the control name "Image";
<asp:image
You then define the name of the control,
id="imgMyImage"
and indicate that it should run on the server:
runat="server"
/>
DataListWebServerControl

Checkbox list control


The control is rendered as a series of HTML Check box tags with span tags for the text
labels.The HTML Checkbox tags can then be contained with an HTML table to make
them appear more orderly.

<asp:checkBox List
id="MyCBL"
runat="server"
'Other properties
>
</asp:CheckBoxlist>
<asp:chechBoxList
you then give the control a name so that you can refer to it in code:
id="MYCBL"
After that,you need to indicate that the control will run on the server.
runat="server"
You can then specify other properties of the control:
'Other properties
>
</asp:checkboxList>
MyCBL.RepeatLayout="table"
MYCBL.RepeatLayout="flow"
MYCBL.RepeatColumns="4"
MYCBL>RepeatDirection="Horizontal"

Other properties

<asp:CheckBoxList
id="MYCBL"
runat="server"
Font-name="Arial"
Font-bold="true"
>
</asp:checkBoxList>
The checkbox list control contains an items collection to which listitem controlare
added.Each of the List Itemcontrols is what is rendered as the individuals
chechBox elements.
<asp:CheckBoxList
id="MYCBL"
runat="server"
>
<asp:Listitem>Item1</asp:Listitem>
<asp:Listitem>Item2</aps:Listitem>
</asp:CheckBoxList>

Radio Button List Control

Also as with the Check BoxList control, with the radiobuttonlist control you can set
the font and colour properties of the control, and the control render a radio button along
with a text label.
<asp:RadioButton List
if="rbl"
runat="server"
'other properties
>
</asp:RadioButtonList>
<asp:RadioButtonList>
you then give the radioButtonList control a name:
id="rbl"
and indicate that it should run on the server:
runat="server"
you can then supply other property values:
'Other properties
As with the Check box List control,you can define items between the tags or bind the
control to a data source:
>
<asp:listItem selected>Gold,/asp:ListItem>
rbl2.Items(3).selected=True

DropDownList control
The control is similar to the RadioButton List control in that he visitor is presented
with a list of option and must select one of them.But it does not contain any radio
elements.Instead the visitor can pull down a list of available items and select one of
them.The control is also different form the two previously mentioned in that it does not
have the same formatting Repeat properties.
<asp:DropDownList
id="ddl2"
runat="server"
'other properties
>
</asp:DropDownlist>

ListBoxControl
The number of rows that appear at one time in the list and you can set whether the
visitor may select only one item in the list or many items.
<asp"ListBox
id="lb2"
runat="server"
'other properties
>
</asp:ListBox>
<asp:Listbox
We then give the control a name so that we can reference it in code.
id="ld2"
and indicate that it should run on the server side:
runat="server"
We can then specify other properties here or in code:
'other properties
Between the opening and closing tags, we can define the items that appear in the
list.These items are rendered as option tags for the select control just as with the
DropDownList control:
>
We then close the control definition:
</asp:LsitBox>
Selectionmode="multiple"
<asp:ListItem>blue</asp:LsitItem>
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Green</sp:LsitItem>
<asp:LsitItem>black</asp:ListItem>
<asp:ListItem>Gold</asp:ListItem>

DataGrid Control
Data such as a database table or result of a query as a well formatted HTML table. With
the table, you can set the colour and font styles you can format columns of data you can
allow the visitor to sort the data, and you can allow the visitor to page through long list
of records.

A basic Data Grid that displays employee data. Thedata is populated when the page is
first loaded and the DataGrid is bound to the data. Within the body of the page, we
define the datagrid control:

<asp:Datagrid
id="dg1"
runat="server"
/>
<asp:Datagrid
That is followed with the name of the control,
id="dg1"
and that we want the compiler to run the control:
runat="server"

Dim MYDT as new datable


Dim MYRow as Datarow
getType(Int32)
getType(String)

Repeater control

The difference between the two lies in how they are rendered.The DataGrid control is
specifically designed to render your data within an HTML table.The repeater control
does not provide that structure for you instead;it is a lower-level control where you
define templates that are used to render the data for that particular row.

The page displays a single Repeater control that is implemented as an HTML Table. The
contents of the repeater control are formatted through five different templates.
The first templates you see on this page is the header templates.This template contains
the columns headers and defines the colour and font for that row.
The second template you see is the item template.This template is used to render the
odd-numbered data rows. Similar to this template is the alternatingItem template.
This template defines the contents and layout of the even-numbered data rows.
Between each of the data rows is an empty row.The empty rows are generated through
the Separator Template. This template is repeated between each pair of data rows.
The last row in the Repeater control is rendered through the formatting defined in the
footer template.
OtherWebServerControl

Calendar control
The calendar control provides a simple way for you to render a calendar on your
ASP.NET page. You can allow the visitor to the page to select a date in the calendar to
scroll through dates and months, and to select a week or month at a time very basic
rendition of the calendar control.
They can select different months and eventually a different year,by clicking the
forward and back links.These are the >and <links,respectively

<asp:calendar
id="mycal"
runat="server"
/>

forecolor="darkBlue:
Backcolor="white"
TitleStyle-backcolor="red"
TitleStyle-font="arial"
nextprevstyle-font-italic="true"
DayStyle-foreclolr="red"
othermonthdaystyle-font-bold="true"
selecteddaystyle-backcolor="blue"
todaydaystyle-font-bold="true"
selectorystyle-forecolor="yellow"
Daynameformat="short"
firstdayofweek="monday"
nextmonthtext="next"
prevmonthtext="previous"
selectmode="dayweek"
titleforamt="month"

AdRotator Control

The AdRotator control provides a way for you to display a different image on a page
each time it is loaded.The images are displayed randomly, but the random is based on an
ad schedule.

Typically,the AdRotator control is used as the name implies.The control is usedto


display banner ads on a rotating basis.With the schedule file it provides,along with other
properties,you can control how often one ad is displayed compared to
another ad,and you can record an impression of the ad through the visitor's browser.

<asp:adrotator
id="MyAd"
runat="server"
'other properties
/>
Advertisementfile="bannerads.xml"
Another helpful property to set is the keyword filter property.On the group of
pages,you may want to use the same schedule file.
Keywordfilter="sports"
target="-black"
onAdCreated="AdCreated_event"
onAdCreated="Adcreated_event"

Example:
<asp:adrotator
AdvertisementFile="bannerads.xml"
Keywordfilter="showme"
target="_black"
onAdcreated="Adcreated_event"
bordercolor="blue"
borderwidth=3
runat="server"
/>

Example:
Schedule file:
<advertisement>
<ad>
<iamgeurl./samplebanner.gif</imageurl>
<navigateurl>http://www.google.com</navigateurl>
<AlternateText>click me now!</AlternateText>
<keyword>showme</keyword>
<impressions>71</Impressions>
<accountName>BLR</AccountName>
</Ad>

Validation Controls
The system.web.uI.Webcontrols namespace includes a variety of control to validate the
input entered by visitors. These controls can be used to make sure that a value
was entered or that it falls within a range, and much more.

Required FieldValidator Control


The Required FieldValidator control provides a way for you to make sure that the
visitor enters a value into a filed or that they change the initial value of a filed.
<asp:requiredFieldvalidator
id="rfv1"
runat=server
'other properties
>

CompareValidator Control
The Compare Validator control allows you to compare a value entered into a field
against a value entered into another field or to a value entered in code, or to a specific
data type.

<asp:CompareValidator
id="cv1"
runat="server"
>
message Text
</asp:CompareValidator>
RangeValidatorControl
The RangeValidator control tests to make sure that a value entered into a control, like a
textbox, falls within an expect range.
<asp:RangeValidator
id="MyRNG"
runat="server">
Message Text
</asp:RangeValidator>

CustomValidator Control

The Custom Validator control allows you to create your own procedure that you want to
run to test the value entered into the test control.The procedure is typically placed on the
server and thus runs on the server side.

<asp:CustomValidator
id="custom9"
runat="server"
Error message
</asp:custom validator>

Validation Summary control


you need to specify a value in an additional property of the validation controlscalled
ErrorMessage:
ErrorMessage="Message Text"
UNIT V
Request and Response object

Request Object
This object provides information about the visitor to your site, what they are requesting,
and the parameters that they pass in with their request.
The Request object provides the mechanism for you to find information about your
visitor and their request.
Request.Saveas(pathtofile,saveHeaders)

Response object
The Response object use to send information back to the visitor.The object properties
and method are helpful to become familiar with

Response.Write("some text")
The write file method provides similar functionality.It allows you to write the contents
of a physical file to the browser
Response.Writefile("pathtofile")
The redirect method of the Response object does just that. Here is its syntax:
Respone.Redirect("./shopping cart.aspx")
Is still Connected property of the Response object
x=Response.Isstillconnected

Collection

1.QueryString Collection
http://LocalHsot/dg/mypage.aspx?empID=10
Here,the name of the page is "mypage.aspx".That name is followed by a question
mark,which indicates that what follows are parameters to the page.The parameters are
paired with their name and then the value, separated by= if you needed to
include more than one parameter, you would separate each with the & character, like
this:
http://LocalHost/dg/mypage/aspx?Expid=10&dept=12
x=Request.querystring("EmpId")
y=Request.QueryString("Dept")

2.Form Collection
The QueryString collection allows you to access the values of parameters passed into
the page through the url or the link to the page required to retrieve the values of
parameters that were passed into the page through from controls, such as
HTML select elements and HTML Textbox elements on the page. You retrieve those
values through the Form collection of the Request object.

<input name=”Myfield” type="text" value" "/>


Request.Form("myfield")

3. ServerVariablesCollection
The server Variables collection of the request object returns a name value collection
object.Within that collection, you can retrieve various items of information about the
visitor and the request that they are making,The information available includes security
information, security certificates, page
requested, parameters passed into the page, and much more.

x=Request.ServerVariables("All_RAW")
4. Accept Types Collection
The AcceptTypes collection returns a string array that contains the MIME types
accepted by the visitor browser.The Accept Types.aspx page demonstrates how you can
iterate through this string array collection.
For I=0 toReqest.AcceptTypes.GetUpperbound (0)

Object
1. Browser Object
The Browser object of the Request object returns an HttpBrowserCapabilities
object.This object has properties that tell you things about the visitor browser
X=Bcaps.paltform
This type of information is helpful because you may define more than one version of a
web site.

2. Headers Object
The Headers object of the request object returns a namevalue collection that contain the
name and values of all the HTTP Headers that are include with the
visitor's request.The Headers.aspx ASP.NET page shows how you can iterate through
the items in this collection and display them on the ASP.NET page

For I=0 to request.Headers.count-1


lblMessage1.Text=lblMessage1.Text_
&"<TR><TD><B>"&Request.Headers.GETKEY(I)_
&"</B></TD><TD>"&Request.Headers(I)_
&"</TD></TR>"

Visitor and Referrer Information

The UrlReferrer object of the Request object provides you with the location of the
visitor prior to coming to your site.
Sub page_Load(Byval sender as object, ByVal E as EventArgs)
Dim TheRef As uri
TheRef=Request.urlReferrer
lblMessage1.Text=_
"port:"&TheRef.port&"<BR>"
&"path:"&TheRef.Absolutepath&"<BR>"_
&"protocol:"&TheRef.Scheme& "<Br>"_
&"user Agent:"&Request.userAgen&"<BR>"_
&"user HostAddress:"&Request.UserHostAddress&"<BR>"
&"user Host Name:" &Request.userhostname&"<BR>"
End sub
Cookies
Cookies are typically very small files stored in a browser specific location. They
typically have a name a date that they expire and a value you use the Response object to
write Cookies to the visitor browser and the Request object to read
them back when the visitor returns.

Dim I as Integer
For I=0 to Request.Cookie.Count-1
lblMessage1.Text=lblMessage1.Text_
&Request.Cookies.Items(I).Name & ":"_
&Request.Cookies.Items(I).value &"<br>"
Next
End sub
System.Data.OLEDB
OLEDBConnection Class
The OLEDBConnection object provides the means to connect to a database.This is done
through a connect string.Typically, you will declare an object of this class like this:
Dim MyConnection as OLEDBconnection
A connect string is made up of parameters that are needed to connect to the database
successfully.Each of the parameters contain the name of the parameter followed by its
value preceded by an equal sign. Each parameter in the connect
string is separated by a semicolon.

Example:
Myconnection=New OLEDBconnection("PROVIDER="_
&"microsoft.jet.oLEDB.4.0;"_
&"Data SOURCE="_
&"C:\somefolder\DBName.MDB")

OLEDBCommand class
Create an instance of the OLEDBCommand class to manipulate the data in a database
through a SQL insert, update,or Delete statement.An instance of the OLEDB
Command class relies on a connection to the database to manipulate its contents.

Properties
Dim MyCommand As New OLEDBCommand
MyCommand.Commandtype="storedprocedure"
Mycommand.Commandtype="TableDirect"
Mycommand.commandtext="text"
The command object connects to the database through the instance of the
OLEDBConnection object called MyConnection.
MyCommand.connection.open
MyCommand.ExecuteNonquery()

OLEDBTransaction class
Sometimes you may need to nest changes to the data in a database in a transaction so
that they will succeed or fail as a group.
A transaction is implemented in the system data OLEDB namespace through the
OLEDBTransaction class.
An instance of the class is returned by calling the begin transaction method of the
OLEDBConnection class.
Dim MyTransaction as OLEDBTranscation
MYTranscation=Myconnection.Begintransaction()
MYCommand.Transaction=MyTransaction
MyTransaction.RollBack()

OLEDBDataAdapter class
The OLEDBDataAdapter class provides a mechanism for you to retrieve data from a
database that you will eventually place into Dataset classes’ ad bind to ASP.NET
controls or display on ASp.NET pages
myDataAdapter=new OLEDBAdapter
("select field1, fileld2"_
& "from MYTable",DBconn)
Dataset Class
This next class,Dataset, can be found in the system.Data namespace.This class is how
you retrieve the data from a database so that it can be bound to a control or displayed on
as asp.net page

Dim dspagedata as new dataset


Data Table within a dataset and place data into it by calling the fill method of the
OLEDBDataAdapter class
mydataadapter.fill(mydataset,_"courses")

Error handling
No error handling
A simple asp.net page will be used. the page allows the visitor to enter two
numbers and the integer result of dividing the two numbers is displayed when the button
on the page is clicked.
Resume next
One of the most basic things that you can da is to add an On Error Resume Next
statement to your asp.net pages.
On Error Resume Next
This approach is basic and doesn’t allow you to do much about the error.it basically just
blows past the error by skipping any erring lines and moves on directly to the next
line;so suppose we modify the code block from the first sample page so that it includes
the On Error Resume Next statement;
Sub submitbtn-Click(sender As Object, e As EventArgs)
On Error Resume Next
Dim Tempresult as Integer
TempResult=txtNumber1.text/txtNumber2.text
iblResult.text=”result:” & Tempresult
End sub
On Error Resume Next
TempResult=txtNumber1.Text / txtNumber2.Text
On Error Goto 0
On Error Goto Handler
A better to use the On Error Statement is to direct your code to a special
error handler block when an error occurs. You da that through this statement:
On Error Goto TheHandler
iblError.Text= ” Unable to calculate due to this error : ” - & Err.Description.
Resume From Handler:
A Resume Next Statement in your error handler:
Notice the addition of the Resume Next Line. This means that the code will flow back to
this line after the error is thrown
Err Object
One of the properties of the err object is the description property:
TheMessage = Err.description
Number property of the err object
If Err.Number = 10 Then
The source property of the Err object
TheSource = Err.Source
Returns the name of the object or application that threw the error. One of the method
that the err object contains is the clear method
Err. Clear
This method clears out the error that the err object contains. Another helpful method of
the err object is the Raise method.
Err.Raise(16000)
Use the raise method when you want to generate an error in your own code.

Using the customErrors Section of Web .config:


<configuration>
<system.web>
<coustomerrors
defaultRedirect=”theerror.html”
mode=”on”
>
<error
Statuscode= “404”
Redirect =”pagenotfound.html”
/>
</customErrors>
</system.web>
</configuration>
We start off with the opening configuration and system.web tags:
<configuration>
<system.web>
Here we set the path to the default error message page that should be displayed
Defaultrediect=”TheError.html”
We also set the mode to “on” meaning that the redirection will occur on the both the
client side and the server side when an error occurs.
Mode= ”On”
We then close each of the section of the file:
/>
</customErrors>
</system.web>
</configuration>

You might also like