Professional Documents
Culture Documents
Web TEch
Web TEch
Web TEch
VBScript
What is 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">
</script>
</body>
</html>
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!
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
<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:
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>
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
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)
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:
<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!
<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
<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>
Output:
Finally Friday!
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.
Examples
For...next loop
<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
</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"
</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"
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
DateSerial Returns the date for a specified year, month, and day
Function Description
Function Description
Function Description
Function Description
Function Description
Trim Removes spaces on both the left and the right side of a
string
Function Description
InputBox Displays a dialog box, where the user can write some
input and/or click on a button, and returns the contents
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
Example : 1
<html>
<body>
<script type="text/vbscript">
document.write("<br />")
</script>
</body>
</html>
<html>
<body>
<script type="text/vbscript">
document.write("<p>")
document.write(WeekDayName(1))
document.write("<br />")
document.write(WeekDayName(2))
document.write("</p><p>")
document.write("<br />")
document.write(WeekDayName(1,true))
document.write("<br />")
document.write(WeekDayName(2,true))
document.write("</p><p>")
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>
<script type="text/vbscript">
document.write("<p>")
document.write(MonthName(1))
document.write("<br />")
document.write(MonthName(2))
document.write("</p><p>")
document.write("<br />")
document.write(MonthName(1,true))
document.write("<br />")
document.write(MonthName(2,true))
document.write("</p><p>")
document.write("<br />")
document.write(MonthName(month(date)))
document.write("<br />")
document.write(MonthName(month(date), true))
document.write("</p>")
</script>
</body>
</html>
body>
<script type="text/vbscript">
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">
document.write(Mid(sometext, 9, 2))
</script>
</body>
</html>
to
Example : 6
<html>
<body>
<script type="text/vbscript">
</script>
</body>
</html>
Example : 7
<html>
<body>
<script type="text/vbscript">
document.write(ucase(txt))
document.write("<br />")
document.write(lcase(txt))
</script>
</body>
</html>
VBScript Operators
Comparison Logical
Arithmetic
Addition + Object Is
equivalen
ce
Subtraction -
String &
concatenati
on
Examples:
Constant Type
You do not have to call ReDim to change the size of the Dictionary
object
<%
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:
Properties
Property Description
CompareMode Sets or returns the comparison mode for comparing keys in a Dic
object
Key Sets a new key value for an existing key value in a Dictionary
Object
Methods
Method Description
Exists Returns a Boolean value that indicates whether a specified key exists
Dictionary object
Remove Removes one specified key/item pair from the Dictionary object
UNIT II
JAVASCRIPT
JavaScript is:
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>
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:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
Hello World!
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.
But when formatted in a single line as follows, the semicolons are required:
Case Sensitivity:
So identifiers Time, TIme and TIME will have different meanings in JavaScript.
Comments in JavaScript:
JavaScript Variables:
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
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.
|| 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.
C %= A is equivalent to C = C
%A
Miscellaneous Operator
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
}
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:
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
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
}
Syntax:
do{
Statement(s) to be executed;
} while (expression);
You can put all the three parts in a single line separated by a semicolon.
Syntax:
In each iteration one property from object is assigned to variablename and this
loop continues till all the properties of the object are exhausted.
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.
<head>
<script type="text/javascript">
<!--
alert("Warning Message");
//-->
</script>
</head>
<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>
<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>
<head>
<script type="text/javascript">
<!--
void func()
javascript:void func()
or:
void(func())
javascript:void(func())
//-->
</script>
</head>
<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.
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:
<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>
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>
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>
<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>
<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>
<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 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:
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.
<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>
<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 )
{
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>
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.
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
Syntax:
Creating a String object:
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.
String Methods
Here is a list of each method and its description.
Method Description
Here is a list of each method which returns a copy of the string wrapped inside
the appropriate
HTML tag.
Method Description
The Array object let's you store multiple values in a single variable.
Syntax:
Creating a Array object:
You will use ordinal numbers to access and to set values inside an array as
follows:
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
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).
filter() Creates a new array with all of the elements of this array
for which the provided filtering function returns true.
indexOf() Returns the first (least) index of an element within the array
equal to the specified value, or -1 if none is found.
lastIndexOf() Returns the last (greatest) index of an element within the array
equal to the specified value, or -1 if none is found.
pop() Removes the last element from an array and returns that
element.
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 ])
Date Properties:
Here is a list of each property and their description.
Property Description
Date Methods:
Here is a list of each method and its description.
Method Description
getDay() Returns the day of the week for the specified date
according to local time.
setFullYear() Sets the full year for a specified date according to local
time.
Method Description
Date.parse( ) Parses a string representation of a date and time and
returns the internal millisecond representation of that
date.
Syntax:
Math Properties:
Here is a list of each property and their description.
Property Description
Math Methods
Here is a list of each method and its description.
Method Description
pow() Returns base to the exponent power, that is, base exponent.
Window
|->document
|->anchor
|->link
|->form
|->textbox
|->textarea
|->radiabutton
|->checkbox
|->select
|->button
Javascript’s DOM
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.
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
ObjectName.MethodName
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
Javascript approach to working with web page element is a multi step process;
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.
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.
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:
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
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.
Tags with which an html form can be created to capture user input..
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.
ACTION:
The HTML form elements that can be specified as attributes to the <INPUT> tags
are…
<OPTION>OPTION2</SELECT>
Hidden A field that may contain a value but is not displayed within a
form (<INPUT Type =”HIDDEN”>)
Text
Password
Textarea
Button
Reset
Hidden
Fileupload
Text
Password
Textarea
Checkbox
Select
Submit
Reset
Hidden
Textarea
Textarea
Text
Button
Radio
Reset
UNIT IV
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
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"
>
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
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
<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>
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"
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.
<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.
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>
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.
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
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
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.