Download as pdf or txt
Download as pdf or txt
You are on page 1of 86

Web Technology

SNO TITLE OF THE EXCERCISES

1 HTML
2 VB Script
3 Java Script

4 XML with HTML,


XML with XSLT & DTD,
XML with CSS
5 ASP Program Using Components
6 Student Mark List Using Servlets

7 Order Processing Using JSP

8 C# Programming in .Net platform

1
Ex.No.01 WEB PAGE DESIGN USING HTML

AIM
To design web page using HTML tags.

DESCRIPTION ABOUT THE HTML


WHAT IS HTML ?

HTML is a language for describing web pages.

• HTML stands for Hyper Text Markup Language


• HTML is not a programming language, it is a markup language
• A markup language is a set of markup tags
• HTML uses markup tags to describe web pages
• Html file is stored with the extension .htm or .html

HTML TAGS

HTML markup tags are usually called HTML tags

• HTML tags are keywords surrounded by angle brackets like <html>


• HTML tags normally come in pairs like <b> and </b>
• The first tag in a pair is the start tag, the second tag is the end tag
• Start and end tags are also called opening tags and closing tags

1) <html> The text between <html> and </html> describes the web page

2) <body> The text between <body> and </body> is the visible page content

3) HTML Headings

HTML headings are defined with the <h1> to <h6> tags.

Example

<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>

4) HTML Paragraphs

HTML paragraphs are defined with the <p> tag.

Example

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

3
5) HTML Links

HTML links are defined with the <a> tag.

Example

<a href="http://www.w3schools.com">This is a link</a>

6) HTML Images

HTML images are defined with the <img> tag.

Example

<img src="w3schools.jpg" width="104" height="142" />

HTML Elements

An HTML element is everything from the start tag to the end tag:

Start tag * Element content End tag *


<p> This is a paragraph </p>
<a href="default.htm" > This is a link </a>
<br />

• The start tag is often called the opening tag. The end tag is often called the closing tag.

7) HTML Elements

HTML Element Syntax

• An HTML element starts with a start tag / opening tag


• An HTML element ends with an end tag / closing tag
• The element content is everything between the start and the end tag
• Some HTML elements have empty content
• Empty elements are closed in the start tag
• Most HTML elements can have attributes

Nested HTML Elements

Most HTML elements can be nested (can contain other HTML elements).

HTML documents consist of nested HTML elements.

HTML Document Example

4
<html>

<body>
<p>This is my first paragraph.</p>
</body>

</html>

8) HTML Attributes
Attributes provide additional information about HTML elements.

HTML Attributes

• HTML elements can have attributes


• Attributes provide additional information about an element
• Attributes are always specified in the start tag
• Attributes come in name/value pairs like: name="value"

Attribute Example

HTML links are defined with the <a> tag. The link address is specified in the href attribute:

Example

<a href="http://www.w3schools.com">This is a link</a

Always Quote Attribute Values

Attribute values should always be enclosed in quotes.

Double style quotes are the most common, but single style quotes are also allowed.

Below is a list of some attributes that are standard for most HTML elements:

Attribute Value Description


class classname Specifies a classname for an element
id id Specifies a unique id for an element
style style_definition Specifies an inline style for an element
title tooltip_text Specifies extra information about an element (displayed as a
tool tip)

9) HTML Lines

The <hr /> tag creates a horizontal line in an HTML page.

The hr element can be used to separate content:

5
Example

<p>This is a paragraph</p>
<hr />
<p>This is a paragraph</p>
<hr />
<p>This is a paragraph</p>

10) HTML Comments

Comments can be inserted into the HTML code to make it more readable and understandable.
Comments are ignored by the browser and are not displayed.

Comments are written like this:

Example

<!-- This is a comment -->

11) HTML Line Breaks

Use the <br /> tag if you want a line break (a new line) without starting a new paragraph:

Example

<p>This is<br />a para<br />graph with line breaks</p>

Note: The <br /> element is an empty HTML element. It has no end tag.

<br> or <br />

In XHTML, XML, and future versions of HTML, HTML elements with no end tag (closing tag) are not
allowed.

12) HTML Text Formatting

HTML uses tags like <b> and <i> for formatting output, like bold or italic text.

These HTML tags are called formatting tags.

HTML Text Formatting Tags

Tag Description
<b> Defines bold text
<big> Defines big text
<em> Defines emphasized text

6
<i> Defines italic text
<small> Defines small text
<strong> Defines strong text
<sub> Defines subscripted text
<sup> Defines superscripted text
<ins> Defines inserted text
<del> Defines deleted text

13) HTML Styles


The style attribute is used to style HTML elements.

Look! Styles and colors

This text is in Verdana and red

This text is in Times and blue

This text is 30 pixels high

The HTML Style Attribute

The purpose of the style attribute is:

To provide a common way to style all HTML elements.

Styles was introduced with HTML 4, as the new and preferred way to style HTML elements. With
HTML styles, styles can be added to HTML elements directly by using the style attribute, or indirectly
in separate style sheets (CSS files).

Tags Description
<center> Defines centered content
<font> and <basefont> Defines HTML fonts
<s> and <strike> Defines strikethrough text
<u> Defines underlined text
Attributes Description
align Defines the alignment of text
bgcolor Defines the background color
color Defines the text color

7
HTML Style Example - Background Color

The background-color property defines the background color for an element:

Example

<html>

<body style="background-color:yellow">
<h2 style="background-color:red">This is a heading</h2>
<p style="background-color:green">This is a paragraph.</p>
</body>

</html>

The style attribute makes the "old" bgcolor attribute obsolete.

HTML Style Example - Font, Color and Size

The font-family, color, and font-size properties defines the font, color, and size of the text in an
element:

Example

<html>

<body>
<h1 style="font-family:verdana">A heading</h1>
<p style="font-family:arial;color:red;font-size:20px;">A paragraph.</p>
</body>

</html>

The style attribute makes the old <font> tag obsolete.

HTML Style Example - Text Alignment

The text-align property specifies the horizontal alignment of text in an element:

Example

<html>

<body>
<h1 style="text-align:center">This is a heading</h1>

8
<p>The heading above is aligned to the center of this page.</p>
</body>

</html>

14) HTML Links

Links are found in nearly all Web pages. Links allow users to click their way from page to page. HTML
Hyperlinks (Links)

A hyperlink (or link) is a word, group of words, or image that you can click on to jump to a new
document or a new section within the current document.

When you move the cursor over a link in a Web page, the arrow will turn into a little hand.

Links are specified in HTML using the <a> tag.

The <a> tag can be used in two ways:

1. To create a link to another document, by using the href attribute


2. To create a bookmark inside a document, by using the name attribute

HTML Link Syntax

The HTML code for a link is simple. It looks like this:

<a href="url">Link text</a>

The href attribute specifies the destination of a link.

Example

<a href="http://www.w3schools.com/">Visit W3Schools</a>

HTML Links - The target Attribute

The target attribute specifies where to open the linked document.

The example below will open the linked document in a new browser window:

Example

<a href="http://www.w3schools.com/" target="_blank">Visit W3Schools!</a>

9
15) HTML The <img> Tag and the Src Attribute

In HTML, images are defined with the <img> tag. The <img> tag is empty, which means that it
contains attributes only, and has no closing tag.

To display an image on a page, you need to use the src attribute. Src stands for "source". The value of
the src attribute is the URL of the image you want to display.

Syntax for defining an image:

<img src="url" alt="some_text"/>

The browser displays the image where the <img> tag occurs in the document. If you put an image tag
between two paragraphs, the browser shows the first paragraph, then the image, and then the second
paragraph.

16) HTML The Alt Attribute

The required alt attribute specifies an alternate text for an image, if the image cannot be displayed.

The value of the alt attribute is an author-defined text:

<img src="boat.gif" alt="Big Boat" />

The alt attribute provides alternative information for an image if a user for some reason cannot view it
(because of slow connection, an error in the src attribute, or if the user uses a screen reader).

17) HTML Tables

Tables are defined with the <table> tag.

A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with the <td>
tag). td stands for "table data," and holds the content of a data cell. A <td> tag can contain text, links,
images, lists, forms, other tables, etc.

Table Example

<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

10
How the HTML code above looks in a browser:

row 1, cell 1 row 1, cell 2


row 2, cell 1 row 2, cell 2

HTML Tables and the Border Attribute

If you do not specify a border attribute, the table will be displayed without borders. Sometimes this can
be useful, but most of the time, we want the borders to show.

To display a table with borders, specify the border attribute:

<table border="1">
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
</table>

HTML Table Headers

Header information in a table are defined with the <th> tag.

The text in a th element will be bold and centered.

<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

How the HTML code above looks in a browser:

Header 1 Header 2
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2

11
HTML Table Tags

Tag Description
<table> Defines a table
<th> Defines a table header
<tr> Defines a table row
<td> Defines a table cell
<caption> Defines a table caption
<colgroup> Defines a group of columns in a table, for formatting
<col> Defines attribute values for one or more columns in a table
<thead> Groups the header content in a table
<tbody> Groups the body content in a table
<tfoot> Groups the footer content in a table

18) HTML Lists


The most common HTML lists are ordered and unordered lists:

HTML Lists

An ordered list: An unordered list:

1. The first list item • List item


2. The second list item • List item
3. The third list item • List item

HTML Unordered Lists

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.

The list items are marked with bullets (typically small black circles).

<ul>
<li>Coffee</li>
<li>Milk</li>
</ul>

How the HTML code above looks in a browser:

• Coffee
• Milk

12
HTML Ordered Lists

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.

The list items are marked with numbers.

<ol>
<li>Coffee</li>
<li>Milk</li>
</ol>

How the HTML code above looks in a browser:

1. Coffee
2. Milk HTML Definition Lists

A definition list is a list of items, with a description of each item.

The <dl> tag defines a definition list.

The <dl> tag is used in conjunction with <dt> (defines the item in the list) and <dd> (describes the item
in the list):

<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>

How the HTML code above looks in a browser:

Coffee
- black hot drink
Milk
- white cold drink

HTML List Tags

Tag Description
<ol> Defines an ordered list
<ul> Defines an unordered list
<li> Defines a list item
<dl> Defines a definition list
<dt> Defines an item in a definition list
<dd> Defines a description of an item in a definition

13
19) HTML Forms and Input
HTML Forms are used to select different kinds of user input.

HTML Forms

HTML forms are used to pass data to a server.

A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more.
A form can also contain select lists, textarea, fieldset, legend, and label elements.

The <form> tag is used to create an HTML form:

<form>
.
input elements
.
</form>

HTML Forms - The Input Element

The most important form element is the input element.

The input element is used to select user information.

An input element can vary in many ways, depending on the type attribute. An input element can be of
type text field, checkbox, password, radio button, submit button, and more.

The most used input types are described below.

Text Fields

<input type="text" /> defines a one-line input field that a user can enter text into:

<form>
First name: <input type="text" name="firstname" /><br />
Last name: <input type="text" name="lastname" />
</form>

How the HTML code above looks in a browser:

First name:
Last name:

Note: The form itself is not visible. Also note that the default width of a text field is 20 characters.

14
Password Field

<input type="password" /> defines a password field:

<form>
Password: <input type="password" name="pwd" />
</form>

How the HTML code above looks in a browser:

Password:

Note: The characters in a password field are masked (shown as asterisks or circles).

Radio Buttons

<input type="radio" /> defines a radio button. Radio buttons let a user select ONLY ONE one of a
limited number of choices:

<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>

How the HTML code above looks in a browser:

Male
Female

Checkboxes

<input type="checkbox" /> defines a checkbox. Checkboxes let a user select ONE or MORE options of
a limited number of choices.

<form>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car
</form>

How the HTML code above looks in a browser:

I have a bike
I have a car

15
Submit Button

<input type="submit" /> defines a submit button.

A submit button is used to send form data to a server. The data is sent to the page specified in the form's
action attribute. The file defined in the action attribute usually does something with the received input:

<form name="input" action="html_form_action.asp" method="get">


Username: <input type="text" name="user" />
<input type="submit" value="Submit" />
</form>

How the HTML code above looks in a browser:

Submit
Username:

If you type some characters in the text field above, and click the "Submit" button, the browser will send
your input to a page called "html_form_action.asp". The page will show you the received input.

HTML Form Tags

Tag Description
<form> Defines an HTML form for user input
<input> Defines an input control
<textarea> Defines a multi-line text input control
<label> Defines a label for an input element
<fieldset> Defines a border around elements in a form
<legend> Defines a caption for a fieldset element
<select> Defines a select list (drop-down list)
<optgroup> Defines a group of related options in a select list
<option> Defines an option in a select list
<button> Defines a push button

20) HTML Frames


Frames

With frames, you can display more than one HTML document in the same browser window. Each
HTML document is called a frame, and each frame is independent of the others.

The disadvantages of using frames are:

• The web developer must keep track of more HTML documents


• It is difficult to print the entire page

16
The Frameset Tag

• The <frameset> tag defines how to divide the window into frames
• Each frameset defines a set of rows or columns
• The values of the rows/columns indicate the amount of screen area each row/column will
occupy

The Frame Tag

• The <frame> tag defines what HTML document to put into each frame

In the example below we have a frameset with two columns. The first column is set to 25% of the width
of the browser window. The second column is set to 75% of the width of the browser window. The
HTML document "frame_a.htm" is put into the first column, and the HTML document "frame_b.htm"
is put into the second column:

<frameset cols="25%,75%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>

Frame Tags

Tag Description
<frameset> Defines a set of frames
<frame> Defines a sub window (a frame)
<noframes> Defines a noframe section for browsers that do not handle frames
<iframe> Defines an inline sub window (frame

21) HTML Fonts


The <font> tag in HTML is deprecated. It is supposed to be removed in a future version of HTML.

Even if a lot of people are using it, you should try to avoid it, and use styles instead.

The HTML <font> Tag

With HTML code like this, you can specify both the size and the type of the browser output :

Example

<p>
<font size="2" face="Verdana">
This is a paragraph.
</font>
</p>

17
<p>
<font size="3" face="Times">
This is another paragraph.
</font>
</p>

Font Attributes

Attribute Example Purpose


size="number" size="2" Defines the font size
size="+number" size="+1" Increases the font size
size="-number" size="-1" Decreases the font size
face="face-name" face="Times" Defines the font-name
color="color-value" color="#eeff00" Defines the font color
color="color-name" color="red" Defines the font color

22) HTML Styles (CSS)


With HTML 4.0 all formatting can be moved out of the HTML document and into a separate style
sheet.

How to Use Styles

When a browser reads a style sheet, it will format the document according to it. There are three ways of
inserting a style sheet:

External Style Sheet

An external style sheet is ideal when the style is applied to many pages. With an external style sheet,
you can change the look of an entire Web site by changing one file. Each page must link to the style
sheet using the <link> tag. The <link> tag goes inside the head section.

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

Internal Style Sheet

An internal style sheet should be used when a single document has a unique style. You define internal
styles in the head section with the <style> tag.

<head>
<style type="text/css">

18
body {background-color: red}
p {margin-left: 20px}
</style>
</head>

Inline Styles

An inline style should be used when a unique style is to be applied to a single occurrence of an element.

To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any
CSS property. The example shows how to change the color and the left margin of a paragraph:

<p style="color: red; margin-left: 20px">


This is a paragraph
</p>

Style Tags

Tag Description
<style> Defines a style definition
<link> Defines a resource reference
<div> Defines a section in a document
<span> Defines a section in a document
<font> Deprecated. Use styles instead
<basefont> Deprecated. Use styles instead
<center> Deprecated. Use styles instead

23) HTML 4.0 Event Attributes


Window Events

Only valid in body and frameset elements.

Attribute Value Description


onload script Script to be run when a document loads
onunload script Script to be run when a document unloads

Form Element Events

Only valid in form elements.

19
Attribute Value Description
onchange script Script to be run when the element changes
onsubmit script Script to be run when the form is submitted
onreset script Script to be run when the form is reset
onselect script Script to be run when the element is selected
onblur script Script to be run when the element loses focus
onfocus script Script to be run when the element gets focus

Keyboard Events

Not valid in base, bdo, br, frame, frameset, head, html, iframe, meta, param, script, style, and title
elements.

Attribute Value Description


onkeydown script What to do when key is pressed
onkeypress script What to do when key is pressed and released
onkeyup script What to do when key is released

Mouse Events

Not valid in base, bdo, br, frame, frameset, head, html, iframe, meta, param, script, style, title elements.

Attribute Value Description


onclick script What to do on a mouse click
ondblclick script What to do on a mouse double-click
onmousedown script What to do when mouse button is pressed
onmousemove script What to do when mouse pointer moves
onmouseout script What to do when mouse pointer moves out of an element
onmouseover script What to do when mouse pointer moves over an element
onmouseup script What to do when mouse button is released

Result
Thus the HTML concepts have studied.

20
Ex.No.02 WEB PROGRAMMING USING VBSCRIPT

Aim
To program using VB Script

Description about VB Script

• VBScript is a Microsoft scripting language.


• VBScript is the default scripting language in ASP.
• Client-side VBScript only works in Internet Explorer!
• A scripting language is a lightweight programming language
• VBScript is a light version of Microsoft's programming language Visual Basic

How Does it Work?

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

The HTML <script> tag is used to insert a VBScript into an HTML page.

Put a VBScript into an HTML Page

The example below shows how to use VBSript to write text on a web page:

Example (IE Only)

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

The document.write command is a standard VBScript command for writing output to a page.

By entering the document.write command between the <script> and </script> tags, the browser will
recognize it as a VBScript command and execute the code line. In this case the browser will write Hello
World! to the page:

How to Handle Simple Browsers

Browsers that do not support scripting, will display VBScript as page content.

To prevent them from doing this, the HTML comment tag should be used to "hide" the VBScript.

21
Just add an HTML comment tag <!-- before the first VBScript statement, and a --> (end of comment)
after the last VBScript statement, like this:

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

Where to Put the VBScript

VBScripts 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, or at a later event,
such as when a user clicks a button. When this is the case we put the script inside a function or a sub
procedure, you will learn about procedures in a later chapter.

Scripts in <head>

Put your functions and sub procedures in the head section, this way they are all in one place, and they
do not interfere with page content.

Example (IE Only)

<html>
<head>
<script type="text/vbscript">
function myFunction()
alert("Hello World!")
end function
</script>
</head>

<body onload="myFunction()">
</body>
</html>

Scripts in <body>

If you don't want your script to be placed inside a function, and especially if your script should write
page content, it should be placed in the body section.

Example (IE Only)

22
<html>
<head>
</head>

<body>
<script type="text/vbscript">
document.write("This message is written by VBScript")
</script>
</body>

</html>

Scripts in <head> and <body>

You can place an unlimited number of scripts in your document, and you can have scripts in both the
body and the head section.

Example (IE Only)

<html>
<head>
<script type="text/vbscript">
function myFunction()
alert("Hello World!")
end function
</script>
</head>

<body>
<button onclick="myFunction()">Click me</button>
<script type="text/vbscript">
document.write("This message is written by VBScript")
</script>
</body>
</html>

Using an External VBScript

If you want to run the same VBScript on several pages, without having to write the same script on every
page, you can write a VBScript in an external file.

Save the external VBScript file with a .vbs file extension.

Note: The external script cannot contain the <script> tag!

To use the external script, point to the .vbs file in the "src" attribute of the <script> tag:

Example

23
<html>
<head>
<script type="text/vbscript" src="ex.vbs"></script>
</head>
<body>
</body>
</html>

Variables are "containers" for storing information.

VBScript Variables

As with algebra, VBScript variables are used to hold values or expressions.

A variable can have a short name, like x, or a more descriptive name, like carname.

Rules for VBScript variable names:

• Must begin with a letter


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

In VBScript, all variables are of type variant, that can store different types of data.

Declaring (Creating) VBScript Variables

Creating variables in VBScript is most often referred to as "declaring" variables.

You can declare VBScript variables with the Dim, Public or the Private statement. Like this:

Dim x
Dim carname
Assigning Values to Variables

You assign a value to a variable like this:

carname="Volvo"
x=10
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.

24
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
VBScript Array Variables

An array variable is used to store multiple values in a single variable.

In the following example, an array containing 3 elements is declared:

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"

Similarly, the data can be retrieved from any element using the index of the particular array element
you want. Like this:

mother=names(0)

You can have up to 60 dimensions in an array. Multiple dimensions are declared by separating the
numbers in the parentheses with commas. Here we have a two-dimensional array consisting of 5 rows
and 7 columns:

Dim table(4,6)

Asign data to a two-dimensional array:

Example (IE Only)

<html>
<body>

<script type="text/vbscript">
Dim x(2,2)
x(0,0)="Volvo"
x(0,1)="BMW"
x(0,2)="Ford"
x(1,0)="Apple"
x(1,1)="Orange"
x(1,2)="Banana"
x(2,0)="Coke"
x(2,1)="Pepsi"
x(2,2)="Sprite"
for i=0 to 2
document.write("<p>")
for j=0 to 2
document.write(x(i,j) & "<br />")

25
next
document.write("</p>")
next
</script>

</body>
</html>

VBScript has two kinds procedures:

• Sub procedure
• Function procedure

VBScript Sub Procedures

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
• without arguments, it must include an empty set of parentheses ()

Sub mysub()
some statements
End Sub

or

Sub mysub(argument1,argument2)
some statements
End Sub

Example (IE Only)

Sub mysub()
alert("Hello World")
End Sub

VBScript Function Procedures

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

26
• 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

Example (IE Only)

function myfunction()
myfunction=Date()
end function

How to Call a Procedure

There are different ways to call a procedure. You can call it from within another procedure, on an event,
or call it within a script.

Example (IE Only)

Call a procedure when the user clicks on a button:

<body>
<button onclick="myfunction()">Click me</button>
</body>

Procedures can be used to get a variable value:

carname=findname()

Here you call a Function called "findname", the Function returns a value that will be stored in the
variable "carname".

Function procedures can calculate the sum of two arguments:

27
Example (IE Only)

Function myfunction(a,b)
myfunction=a+b
End Function

document.write(myfunction(5,9))

The function "myfunction" will return the sum of argument "a" and argument "b". In this case 14.

When you call a 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

Conditional statements are used to perform different actions for different decisions.

In VBScript we have four conditional statements:

• If statement - executes a set of code when a condition is true


• If...Then...Else statement - select one of two sets of lines to execute
• If...Then...ElseIf statement - select one of many sets of lines to execute
• Select Case statement - select one of many sets of lines to execute

If...Then...Else

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 alert("Hello")

There is no ..Else.. in this syntax. You just tell the code to perform one action if a 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":

28
If i=10 Then
alert("Hello")
i = i+1
End If

There is no ..Else.. in the example above 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:

Example (IE Only)

<html>
<body>
<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>

In the example above, the first block of code will be executed if the condition is true, and the other
block will be executed otherwise (if i is greater than 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:

Example (IE Only)

<html>
<body>
<script type="text/vbscript">
Function greeting()
i=hour(time)

29
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>

Select Case

You can also use the "Select Case" statement if you want to select one of many blocks of code to
execute:

Example (IE Only)

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

30
End Select
</script>

</body>
</html>

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

Looping statements are used to run the same block of code a specified number of times.

In VBScript we have four looping statements:

• For...Next statement - runs code a specified number of times


• For Each...Next statement - runs code 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

For...Next Loop

Use the For...Next statement to run a block of code a specified number of times.

The For statement specifies the counter variable (i), and its start and end values. The Next statement
increases the counter variable (i) by one.

Example

<html>
<body>

<script type="text/vbscript">
For i = 0 To 5
document.write("The number is " & i & "<br />")
Next
</script>

</body>
</html>

31
The Step Keyword

With 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 i=1 To 10
If i=5 Then Exit For
some code
Next

For Each...Next Loop

A For Each...Next loop repeats a block of code for each item in a collection, or for each element of an
array.

Example

<html>
<body>

<script type="text/vbscript">
Dim cars(2)
cars(0)="Volvo"
cars(1)="Saab"
cars(2)="BMW"

For Each x In cars


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

32
</script>

</body>
</html>

Do...Loop

If you don't know how many repetitions you want, use a Do...Loop statement.

The Do...Loop statement repeats a block of code while a condition is true, or until a condition becomes
true.

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

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

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

Result
Thus the VB Scripts concepts have been studied

34
Ex.No.03 WEB PROGRAMMING USING JAVASCRIPT

AIM

To program using Java Script

DESCRIPTION ABOUT JAVASCRIPT

WHAT IS JAVASCRIPT?

• JavaScript was designed to add interactivity to HTML pages


• JavaScript is a scripting language
• A scripting language is a lightweight programming language
• JavaScript is usually embedded directly into HTML pages
• JavaScript is an interpreted language (means that scripts execute without preliminary
compilation)
• Everyone can use JavaScript without purchasing a license

WHAT CAN A JAVASCRIPT DO?

• JavaScript gives HTML designers a programming tool - HTML authors are normally not
programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone
can put small "snippets" of code into their HTML pages
• JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
• JavaScript can react to events - A JavaScript can be set to execute when something happens,
like when a page has finished loading or when a user clicks on an HTML element
• JavaScript can read and write HTML elements - A JavaScript can read and change the
content of an HTML element
• JavaScript can be used to validate data - A JavaScript can be used to validate form data
before it is submitted to a server. This saves the server from extra processing
• JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect
the visitor's browser, and - depending on the browser - load another page specifically designed
for that browser
• JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve
information on the visitor's computer

The Real Name is ECMAScript

• JavaScript's official name is ECMAScript.


• ECMAScript is developed and maintained by the ECMA organization.
• ECMA-262 is the official JavaScript standard.
• The language was invented by Brendan Eich at Netscape (with Navigator 2.0), and has
appeared in all Netscape and Microsoft browsers since 1996.
• The development of ECMA-262 started in 1996, and the first edition of was adopted by the
ECMA General Assembly in June 1997.
• The standard was approved as an international ISO (ISO/IEC 16262) standard in 1998.
• The development of the standard is still in progress.

35
Put a JavaScript into an HTML page

The example below shows how to use JavaScript to write text on a web page:

Example

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

The example below shows how to add HTML tags to the JavaScript:

Example

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

The document.write command is a standard JavaScript command for writing output to a page.
By entering the document.write command between the <script> and </script> tags, the browser will
recognize it as a JavaScript command and execute the code line. In this case the browser will write
Hello World! to the page:

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

Where to Put the JavaScript

JavaScripts 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, or at a later event,
such as when a user clicks a button. When this is the case we put the script inside a function, you will
learn about functions in a later chapter.

Scripts in <head>

36
Scripts to be executed when they are called, or when an event is triggered, are placed in functions.

Put your functions in the head section, this way they are all in one place, and they do not interfere with
page content.

Example

<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>

<body onload="message()">
</body>
</html>

Try it yourself »

Scripts in <body>

If you don't want your script to be placed inside a function, or if your script should write page content, it
should be placed in the body section.

Example

<html>
<head>
</head>

<body>
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>

</html>

Try it yourself »

Scripts in <head> and <body>

You can place an unlimited number of scripts in your document, so you can have scripts in both the
body and the head section.

37
Example

<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>

<body onload="message()">
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>

</html>

Try it yourself »

JavaScript is Case Sensitive

Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely when you write
JavaScript statements, create or call variables, objects and functions.

JavaScript Statements

A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser
what to do.

This JavaScript statement tells the browser to write "Hello Dolly" to the web page:

document.write("Hello Dolly");

It is normal to add a semicolon at the end of each executable statement. Most people think this is a good
programming practice, and most often you will see this in JavaScript examples on the web.

The semicolon is optional (according to the JavaScript standard), and the browser is supposed to
interpret the end of the line as the end of the statement. Because of this you will often see examples
without the semicolon at the end.

Note: Using semicolons makes it possible to write multiple statements on one line.

JavaScript Blocks

JavaScript statements can be grouped together in blocks.

38
Blocks start with a left curly bracket {, and ends with a right curly bracket }.

The purpose of a block is to make the sequence of statements execute together.

This example will write a heading and two paragraphs to a web page:

Example

<script type="text/javascript">
{
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
}
</script>

The example above is not very useful. It just demonstrates the use of a block. Normally a block is used
to group statements together in a function or in a condition (where a group of statements should be
executed if a condition is met).

You will learn more about functions and conditions in later chapters.

JavaScript Comments

Comments can be added to explain the JavaScript, or to make the code more readable.

Single line comments start with //.

The following example uses single line comments to explain the code:

Example

<script type="text/javascript">
// Write a heading
document.write("<h1>This is a heading</h1>");
// Write two paragraphs:
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script>

Try it yourself »

JavaScript Multi-Line Comments

Multi line comments start with /* and end with */.

39
JavaScript Variables

As with algebra, JavaScript variables are used to hold values or expressions.

A variable can have a short name, like x, or a more descriptive name, like carname.

Rules for JavaScript variable names:

• Variable names are case sensitive (y and Y are two different variables)
• Variable names must begin with a letter or the underscore character

Note: Because JavaScript is case-sensitive, variable names are case-sensitive.

Declaring (Creating) JavaScript Variables

Creating variables in JavaScript is most often referred to as "declaring" variables.

You can declare JavaScript variables with the var statement:

var x;
var carname;

After the declaration shown above, the variables are empty (they have no values yet).

However, you can also assign values to the variables when you declare them:

var x=5;
var carname="Volvo";

After the execution of the statements above, the variable x will hold the value 5, and carname will hold
the value Volvo.

Note: When you assign a text value to a variable, use quotes around the value.

Assigning Values to Undeclared JavaScript Variables

If you assign values to variables that have not yet been declared, the variables will automatically be
declared.

These statements:

x=5;
carname="Volvo";

have the same effect as:

var x=5;

40
var carname="Volvo";

Redeclaring JavaScript Variables

If you redeclare a JavaScript variable, it will not lose its original value.

var x=5;
var x;

After the execution of the statements above, the variable x will still have the value of 5. The value of x
is not reset (or cleared) when you redeclare it.

JavaScript Arithmetic

As with algebra, you can do arithmetic operations with JavaScript variables:

y=x-5;
z=y+5;

You will learn more about the operators that can be used in the next chapter of this tutorial.

= is used to assign values.

+ is used to add values.

The assignment operator = is used to assign values to JavaScript variables.

The arithmetic operator + is used to add values together.

y=5;
z=2;
x=y+z;

The value of x, after the execution of the statements above is 7.

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 JavaScript we have the following conditional statements:

• if statement - use this statement to execute some code only if a specified condition is true
• if...else statement - use this statement to execute some code if the condition is true and another
code if the condition is false

41
• if...else if....else statement - use this statement to select one of many blocks of code to be
executed
• switch statement - use this statement to select one of many blocks of code to be executed

If Statement

Use the if statement to execute some code only if a specified condition is true.

Syntax
if (condition)
{
code to be executed if condition is true
}

Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript error!

Example

<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10

var d=new Date();


var time=d.getHours();

if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>

Notice that there is no ..else.. in this syntax. You tell the browser to execute some code only if the
specified condition is true.

If...else Statement

Use the if....else statement to execute some code if a condition is true and another code if the condition
is not true.

Syntax
if (condition)
{
code to be executed if condition is true
}
else
{

42
code to be executed if condition is not true
}

Example

<script type="text/javascript">
//If the time is less than 10, you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.

var d = new Date();


var time = d.getHours();

if (time < 10)


{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
</script>

If...else if...else Statement

Use the if....else if...else statement to select one of several blocks of code to be executed.

Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and condition2 are not true
}

Example

<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)

43
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{
document.write("<b>Hello World!</b>");
}
</script>

The JavaScript Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}

This is how it works: First we have a single expression n (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. Use break to prevent the code from
running into the next case automatically.

Example

<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.

var d=new Date();


theDay=d.getDay();
switch (theDay)
{

44
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>

Alert Box

An alert box is often used if you want to make sure information comes through to the user.

When an alert box pops up, the user will have to click "OK" to proceed.

Syntax
alert("sometext");

Example

<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body>

<input type="button" onclick="show_alert()" value="Show alert box" />

</body>
</html>

Confirm Box

A confirm box is often used if you want the user to verify or accept something.

45
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.

If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

Syntax
confirm("sometext");

Example

<html>
<head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
{
alert("You pressed OK!");
}
else
{
alert("You pressed Cancel!");
}
}
</script>
</head>
<body>

<input type="button" onclick="show_confirm()" value="Show confirm box" />

</body>
</html>

Prompt Box

A prompt box is often used if you want the user to input a value before entering a page.

When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after
entering an input value.

If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.

Syntax
prompt("sometext","defaultvalue");

46
Example

<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
{
document.write("Hello " + name + "! How are you today?");
}
}
</script>
</head>
<body>

<input type="button" onclick="show_prompt()" value="Show prompt box" />

</body>
</html>

A function will be executed by an event or by a call to the function.

JavaScript Functions

To keep the browser from executing a script when the page loads, you can put your script into a
function.

A function contains code that will be executed by an event or by a call to the function.

You may call a function from anywhere within a page (or even from other pages if the function is
embedded in an external .js file).

Functions can be defined both in the <head> and in the <body> section of a document. However, to
assure that a function is read/loaded by the browser before it is called, it could be wise to put functions
in the <head> section.

How to Define a Function

Syntax
function functionname(var1,var2,...,varX)
{
some code
}

The parameters var1, var2, etc. are variables or values passed into the function. The { and the } defines
the start and end of the function.

47
Note: A function with no parameters must include the parentheses () after the function name.

Note: Do not forget about the importance of capitals in JavaScript! The word function must be written
in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with
the exact same capitals as in the function name.

JavaScript Function Example

Example

<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>

<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>

If the line: alert("Hello world!!") in the example above had not been put within a function, it would
have been executed as soon as the line was loaded. Now, the script is not executed before a user hits the
input button. The function displaymessage() will be executed if the input button is clicked.

The return Statement

The return statement is used to specify the value that is returned from the function.

So, functions that are going to return a value must use the return statement.

The example below returns the product of two numbers (a and b):

48
Example

<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>

<body>
<script type="text/javascript">
document.write(product(4,3));
</script>

</body>
</html>

The Lifetime of JavaScript Variables

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

If you declare a variable outside a function, all the functions on your page can access it. The lifetime of
these variables starts when they are declared, and ends when the page is closed.

JavaScript Loops

Often when you write code, you want the same block of code to run over and over again in a row.
Instead of adding several almost equal lines in a script we can use loops to perform a task like this.

In JavaScript, there are two different kind of loops:

• for - loops through a block of code a specified number of times


• while - loops through a block of code while a specified condition is true

The for Loop

The for loop is used when you know in advance how many times the script should run.

49
Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}

Example

The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less
than, or equal to 5. i will increase by 1 each time the loop runs.

Note: The increment parameter could also be negative, and the <= could be any comparing statement.

Example

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

The while Loop

The while loop loops through a block of code while a specified condition is true.

Syntax
while (var<=endvalue)
{
code to be executed
}

Note: The <= could be any comparing statement.

Example

The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less
than, or equal to 5. i will increase by 1 each time the loop runs:

Example

50
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
</script>
</body>
</html>

The do...while Loop

The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and
then it will repeat the loop as long as the specified condition is true.

Syntax
do
{
code to be executed
}
while (var<=endvalue);

Example

The example below uses a do...while loop. The do...while loop will always be executed at least once,
even if the condition is false, because the statements are executed before the condition is tested:

Example

<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);
</script>

51
</body>
</html>

The break Statement

The break statement will break the loop and continue executing the code that follows after the loop (if
any).

Example

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

The continue Statement

The continue statement will break the current loop and continue with the next value.

Example

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");

52
}
</script>
</body>
</html>

JavaScript For...In Statement

The for...in statement loops through the elements of an array or through the properties of an object.

Syntax
for (variable in object)
{
code to be executed
}

Note: The code in the body of the for...in loop is executed once for each element/property.

Note: The variable argument can be a named variable, an array element, or a property of an object.

Example

Use the for...in statement to loop through an array:

Example

<html>
<body>

<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>

</body>
</html>

Events

By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be
detected by JavaScript.

53
Every element on a web page has certain events which can trigger a JavaScript. For example, we can
use the onClick event of a button element to indicate that a function will run when a user clicks on the
button. We define the events in the HTML tags.

Examples of events:

• A mouse click
• A web page or an image loading
• Mousing over a hot spot on the web page
• Selecting an input field in an HTML form
• Submitting an HTML form
• A keystroke

Note: Events are normally used in combination with functions, and the function will not be executed
before the event occurs!

For a complete reference of the events recognized by JavaScript, go to our complete JavaScript
reference.

onLoad and onUnload

The onLoad and onUnload events are triggered when the user enters or leaves the page.

The onLoad event is often used to check the visitor's browser type and browser version, and load the
proper version of the web page based on the information.

Both the onLoad and onUnload events are also often used to deal with cookies that should be set when
a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his
first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page,
you could have another popup saying something like: "Welcome John Doe!".

onFocus, onBlur and onChange

The onFocus, onBlur and onChange events are often used in combination with validation of form fields.

Below is an example of how to use the onChange event. The checkEmail() function will be called
whenever the user changes the content of the field:

<input type="text" size="30" id="email" onchange="checkEmail()">

onSubmit

The onSubmit event is used to validate ALL form fields before submitting it.

Below is an example of how to use the onSubmit event. The checkForm() function will be called when
the user clicks the submit button in the form. If the field values are not accepted, the submit should be
cancelled. The function checkForm() returns either true or false. If it returns true the form will be
submitted, otherwise the submit will be cancelled:

54
<form method="post" action="xxx.htm" onsubmit="return checkForm()">

onMouseOver and onMouseOut

onMouseOver and onMouseOut are often used to create "animated" buttons.

Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is
detected:

<a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return


false"><img src="w3s.gif" alt="W3Schools" /></a>

The try...catch Statement

The try...catch statement allows you to test a block of code for errors. The try block contains the code to
be run, and the catch block contains the code to be executed if an error occurs.

Syntax
try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}

Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript
error!

Examples

The example below is supposed to alert "Welcome guest!" when the button is clicked. However, there's
a typo in the message() function. alert() is misspelled as adddlert(). A JavaScript error occurs. The catch
block catches the error and executes a custom code to handle it. The code displays a custom error
message informing the user what happened:

Example

<html>
<head>
<script type="text/javascript">
var txt="";
function message()
{
try

55
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.description + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>

</html>

The next example uses a confirm box to display a custom message telling users they can click OK to
continue viewing the page or click Cancel to go to the homepage. If the confirm method returns false,
the user clicked Cancel, and the code redirects the user. If the confirm method returns true, the code
does nothing:

Example

<html>
<head>
<script type="text/javascript">
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Click OK to continue viewing this page,\n";
txt+="or Cancel to return to the home page.\n\n";
if(!confirm(txt))
{
document.location.href="http://www.w3schools.com/";
}
}
}
</script>

56
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>

</html>

The Throw Statement

The throw statement allows you to create an exception. If you use this statement together with the
try...catch statement, you can control program flow and generate accurate error messages.

Syntax
throw(exception)

The exception can be a string, integer, Boolean or an object.

Note that throw is written in lowercase letters. Using uppercase letters will generate a JavaScript error!

Example

The example below determines the value of a variable called x. If the value of x is higher than 10, lower
than 0, or not a number, we are going to throw an error. The error is then caught by the catch argument
and the proper error message is displayed:

Example

<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","");
try
{
if(x>10)
{
throw "Err1";
}
else if(x<0)
{
throw "Err2";
}
else if(isNaN(x))
{
throw "Err3";
}
}
catch(er)

57
{
if(er=="Err1")
{
alert("Error! The value is too high");
}
if(er=="Err2")
{
alert("Error! The value is too low");
}
if(er=="Err3")
{
alert("Error! The value is not a number");
}
}
</script>
</body>
</html>

Result

Thus the JavaScript have been studied.

58
Ex.No.04a XML with HTML
Aim
To Create a XML program for book store and use DTD
Procedure
i) Create a xml document to contain the data about the book catalogue in the following way
i<books>
<book>
<author>
<title>
<price>
<ISBN_No>
<Publisher>
<Country>
ii) Create a html document
iii) Open a html tag
iv) In html document Use the src attribute to refer the xml document
v) Create the table with the following fields
a) Book Title
b) Author
c) Price
d) ISBN_No
e) Publishers
f) Country
vi) Use the div and datafld field to fetch the data from the Xml document
vii) Close the table
viii) Close the html tag
Program

Html Program

<html>
<head>
<title> XML Data</title>
</head>
<body bgcolor="#ffccff">
<h1> <center> Book Catalogue table </h1>

<xml id="Books Catalogue" src="book.xml"> </xml>


<Table border="1" datasrc="#Books Catalogue">
<THead>
<tr>
<th> Book Title </th>
<th> Author </th>
<th> Price </th>
<th> ISBN_No </th>
<th> Publishers </th>
<th> Country </th>
</tr>
<THead>
<Tfoot>
<tr>

59
<th colspan="5"> Book Catlalogue of Knowledge Garden </th>
</tr>
</Tfoot>
<tr>
<td> <div datafld="title"> </div> </td>
<td> <div datafld="author"> </div> </td>
<td> <div datafld="price"> </div> </td>
<td> <div datafld="ISBN_No"> </div> </td>
<td> <div datafld="Publishers"> </div> </td>
<td> <div datafld="Country"> </div> </td>
</tr>

</Table>
</body>
</html>

XML Program

<?xml version="1.0"?>

<books>

<book>
<title> Asp.net </title>
<author> Wilson </author>
<price> Rs.300 </price>
<ISBN_No> 12345 </ISBN_No>
<Publishers> TMH </Publishers>
<Country> USA </Country>
</book>
<book>
<title> Web Technology </title>
<author> R.Premananth </author>
<price> Rs.500 </price>
<ISBN_No> 12321 </ISBN_No>
<Publishers> RBP</Publishers>
<Country> India </Country>
</book>
<book>
<title> Data Structures </title>
<author> M.S.weiss </author>
<price> Rs.400 </price>
<ISBN_No> 12321 </ISBN_No>
<Publishers> RBP </Publishers>
<Country> USA </Country>
</book>
<book>
<title> C# Programming </title>
<author> E.Balagurusamy </author>
<price> Rs.400 </price>
<ISBN_No> 12320 </ISBN_No>

60
<Publishers> PHI </Publishers>
<Country> India </Country>
</book>
</books>
Output

Result

Thus the program for Book Catalogue Table has been created with HTML &XML

61
Ex.No.04b XML with XSLT & DTD

Aim
To Create a XML program for book catalogue using XSLT & DTD
Procedure

i) Create a XML file with book catalogue details


ii) Include the following Statement in XML file to use DTD
<!DOCTYPE books SYSTEM "book.dtd">
Here book.dtd is the external DTD file, books is the name of the root element
iii) Include the following statement in the XML file to transform it into html
<?xml-stylesheet type="text/xsl" href="bo.xsl"?>
iii) Create an External DTD file with appropriate entities and elements
iv) Create a XSLT file to transform XML into HTML file
v) Inside the XSLT file give the statements for selecting the records in sorted order.
vi) Close the XML , XSLT & DTD files

Program

XML file
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="bo.xsl"?>
<!DOCTYPE books SYSTEM "book.dtd">
<books>

<book>
<title> Asp.net </title>
<author> Wilson </author>
<price> Rs.300 </price>
<ISBN_No> 12345 </ISBN_No>
<Publishers> &TMH; </Publishers>
<Country> USA </Country>
</book>
<book>
<title> Web Technology </title>
<author> R.Premananth </author>
<price> Rs.500 </price>
<ISBN_No> 12321 </ISBN_No>
<Publishers> &RBP;</Publishers>
<Country> India </Country>
</book>
<book>
<title> Data Structures </title>
<author> M.S.weiss </author>
<price> Rs.400 </price>
<ISBN_No> 12321 </ISBN_No>
<Publishers> &RBP; </Publishers>

62
<Country> USA </Country>
</book>
<book>
<title> C# Programming </title>
<author> E.Balagurusamy </author>
<price> Rs.400 </price>
<ISBN_No> 12320 </ISBN_No>
<Publishers> &PHI; </Publishers>
<Country> India </Country>
</book>
</books>

XSLT File

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
<title> XML Data</title>
</head>
<body bgcolor="#ffccff">
<h1> <center> Book Catalogue table </center> </h1>

<center>
<Table border="1" bgcolor="#cccccc">
<THead>
<tr>
<th> Book Title </th>
<th> Author </th>
<th> Price </th>
<th> ISBN_No </th>
<th> Publishers </th>
<th> Country </th>
</tr>
</THead>
<Tfoot>
<tr>
<th colspan="5"> Book Catlalogue of Knowledge Garden </th>
</tr>
</Tfoot>
<xsl:for-each select="books/book">
<xsl:sort select="title" />
<tr>
<td> <xsl:value-of select="title" /> </td>
<td> <xsl:value-of select="author" /> </td>
<td> <xsl:value-of select="price" /> </td>

63
<td> <xsl:value-of select="ISBN_No" /></td>
<td> <xsl:value-of select="Publishers" /> </td>
<td> <xsl:value-of select="Country" /> </td>
</tr>

</xsl:for-each>

</Table>
</center>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

External DTD

<!--Elements-->
<!ELEMENT books (book+)>

<!--Element-->
<!ELEMENT book (title,author,price,ISBN_No,Publishers,Country)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT ISBN_No (#PCDATA)>
<!ELEMENT Publishers (#PCDATA)>
<!ELEMENT country (#PCDATA)>

<!--Entities-->
<!ENTITY PHI "Prentice-Hall of India">
<!ENTITY RBP "RB Publications">
<!ENTITY TMH "TATA MC-GraW Hill">

64
Output

Result

Thus the book catalogue is displayed using XML , XSLT & DTD

65
Ex.No.04c XML with CSS

Aim
To Create a simple XML program with CSS

Procedure
i) Create a file with .css extension
ii) The css file should include the procedure to display the data in a formatted
manner
iii) Create a XML file with simple mail transfer details
iv) Include the css file into the XML file by using the following way
<?xml-stylesheet type=”text/css” href=”mystyle.css”?>
v) Close the program
Program

XML file (style.xml)

<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="mystyle.css"?>
<EMAIL><Inbox>
<Mail>
<To> WebMaster@xyz.com</To>
<From>Customer@xyz.com</From>
<Subject> Service Required </Subject>
<Body> Please give service for the supply of Instrument </Body>
</Mail>
<Mail>
<To> WebMaster@xyz.com</To>
<From>Customer@xyz.com</From>
<Subject> Thanks </Subject>
<Body> Thanks for the supply of Instrument </Body>
</Mail>
</Inbox>
</EMAIL>

CSS file(mystyle.css)
To
{
background-color:#ffccff;
width:100%;
}
From
{
background-color:#EEaaff;
width:100%;
}
Subject

66
{
background-color:#ffccff;
width:100%;
}
Body
{
background-color:#aaaaaa;
font-size:20pt;
color:#ccffcc;
margin-left:50pt;
}

Output

Result
Thus the XML program with css has been executed successfully

67
EX NO:5 ASP PROGRAM USING COMPONENTS

AIM

To write a ASP program using the components.

PROCEDURE

1. ASP AdRotator Component

1. The ASP AdRotator component creates an AdRotator object that displays a different
image each time a user enters or refreshes a page.
2. A text file includes information about the images.

PROGRAM
adrotator.asp

<html>
<body>
<%
set adrotator=Server.CreateObject("MSWC.AdRotator")
response.write(adrotator.GetAdvertisement("sample.txt"))
%>
</body>
</html>
sample.txt

REDIRECT banners.asp
*
web.gif
Free Tutorials from W3Schools
50
mmc.gif
XML Editor from Altova
50

2. ASP Browser Capabilities Component

1. The ASP Browser Capabilities component creates a BrowserType object that


determines the type, capabilities and version number of each browser that visits your
site.
2. When a browser connects to a server, an HTTP User Agent Header is also sent to the
server. This header contains information about the browser (like browser type and
version number).

68
3. The BrowserType object then compares the information in the header with information
in a file on the server called "Browscap.ini".
4. If there is a match between the browser type and version number sent in the header and
the information in the "Browsercap.ini" file, you can use the BrowserType object to list
the properties of the matching browser.
5. If there is no match for the browser type and version number in the Browscap.ini file, it
will set every property to "UNKNOWN".

PROGRAM

sample.asp

<html>
<body>
<%
Set MyBrow=Server.CreateObject("MSWC.BrowserType")
%>
<table border="1" width="100%">
<tr>
<th>Client OS</th>
<th><%=MyBrow.platform%></th>
</tr><tr>
<td >Web Browser</td>
<td ><%=MyBrow.browser%></td>
</tr><tr>
<td>Browser version</td>
<td><%=MyBrow.version%></td>
</tr><tr>
<td>Frame support?</td>
<td><%=MyBrow.frames%></td>
</tr><tr>
<td>Table support?</td>
<td><%=MyBrow.tables%></td>
</tr><tr>
<td>Sound support?</td>
<td><%=MyBrow.backgroundsounds%></td>
</tr><tr>
<td>Cookies support?</td>
<td><%=MyBrow.cookies%></td>
</tr><tr>
<td>VBScript support?</td>
<td><%=MyBrow.vbscript%></td>
</tr><tr>
<td>JavaScript support?</td>
<td><%=MyBrow.javascript%></td>
</tr>

69
</table>
</body>
</html>

3. ASP Content Linking Component

1. The ASP Content Linking component is used to create a quick and easy navigation
system
2. The Content Linking component returns a Nextlink object that is used to hold a list of
Web pages to be navigated.
Syntax
<%
Set nl=Server.CreateObject( "MSWC.NextLink" )
%>
PROGRAM
page1.asp

<html>
<body>
<h1>
This is page 1!
</h1>
<%
Set nl=Server.CreateObject("MSWC.NextLink")
If (nl.GetListIndex("links2.txt")>1) Then
%>
<a href="<%Response.Write(nl.GetPreviousURL("links2.txt"))%>">Previous Page</a>
<%End If%>
<a href="<%Response.Write(nl.GetNextURL("links2.txt"))%>">Next Page</a>
<p>The example uses the Content Linking Component
to navigate between the pages in a text file.</p>
<p>
<a href="links2.txt"><img border="0" src="warning.gif"></a>
</p>
</body>
</html>
page2.asp

<html>
<body>
<h1>This is page 2!</h1>

<%
Set nl=Server.CreateObject("MSWC.NextLink")
If (nl.GetListIndex("links2.txt")>1) Then
%>

70
<a href="<%Response.Write(nl.GetPreviousURL("links2.txt"))%>">Previous Page</a>
<%End If%>
<a href="<%Response.Write(nl.GetNextURL("links2.txt"))%>">Next Page</a>
<p>The example uses the Content Linking Component
to navigate between the pages in a text file.</p>
<p>
<a href="links2.txt"><img border="0" src="web.gif"></a>
</p>
</body>
</html>

page3.asp
<html>
<body>
<h1>This is page 3!</h1>
<%
Set nl=Server.CreateObject("MSWC.NextLink")
If (nl.GetListIndex("links2.txt")>1) Then
%>
<a href="<%Response.Write(nl.GetPreviousURL("links2.txt"))%>">Previous Page</a>
<%End If%>
<a href="<%Response.Write(nl.GetNextURL("links2.txt"))%>">Next Page</a>
<p>The example uses the Content Linking Component
to navigate between the pages in a text file.</p>
<p>
<a href="links2.txt"><img border="0" src="print.gif"></a>
</p>
</body>
</html>

links2.txt
page1.asp Page 1
page2.asp Page 2
page3.asp Page 3

4. ASP Content Rotator Component

1. The ASP Content Rotator component creates a ContentRotator object that displays a
different HTML content string each time a user enters or refreshes a page.
2. A text file, called the Content Schedule File, includes the information about the content
strings.
3. The content strings can contain HTML tags so you can display any type of content that
HTML can represent: text, images, colors, or hyperlinks.
Syntax
<% Set cr=Server.CreateObject( "MSWC.ContentRotator" ) %>

71
conrotator.asp
<html>
<body>
<%
set cr=server.createobject("MSWC.ContentRotator")
response.write(cr.ChooseContent("textads.txt"))
%>
</body>
</html>

textads.txt

%% #3
<h2>This is a great day!!</h2>

%% #3
<img src="winxp.gif">

%% #4
<a href="http://www.w3schools.com">Visit W3Schools.com</a>

OUTPUT

1. ASP AdRotator Component

72
2. ASP Browser Capabilities Component

3. ASP Content Linking Component

4. ASP Content Rotator Component

73
RESULT
Thus the ASP components are studied and a program is written and verified using the
components

74
EX NO:6 STUDENTS MARKLIST USING SERVLETS

Write a program in java to create servlets for displaying students mark list. Assume that
student information is available in a database which has been stored in a server.

AIM

To develop an Servlet program to display the students mark list.

PROCEDURE

1. Create an Access database, add a table to it with the following fields

Field name data type


Rollno text
Name text
Mark1 integer
Mark2 integer
Mark3 integer
Mark4 integer
Mark5 integer
Mark6 integer

2. Add some records to the table


3. Create a system DSN
start – settings – control panel – administrative tools – odbc
4 DSN name ex7, select the database you have created
5 compile the servlet and place the class file in the webapp folder of the tomcat
6 open the browser and invoke the servlet.

PROGRAM

/*
* Exam.java
*
* Created on September 27, 2003, 4:39 PM
*/

package com;

75
import java.io.*;
import java.net.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Exam extends HttpServlet {

Connection ConnRecordset;
PreparedStatement StatementRecordset;
ResultSet Recordset;

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int total=0;
out.print("<H3>MARK List</h3>");
out.print("<Table border=1><tr>");
out.print("<TD>Roll
No</TD><TD>NAME</TD><TD>MARK1</TD><TD>MARK2</TD><TD>MARK
3</TD><TD>MARK4</TD><TD>MARK5</TD><TD>MARK6</TD><TD>TOTAL
</TD></tr>");
try{
while (Recordset.next())
{ total=0;
out.println("<tr><td>");
out.print(Recordset.getString(1));
out.println("</td>");

out.println("<td>");
out.print(Recordset.getString(2));
out.println("</td>");

int t;
for (int i=3;i<9;i++)
{ out.println("<td>");
t=Recordset.getInt(i);
total=total+t;
out.print(t);
out.println("</td>");
}
out.println("<td>");
out.print(total);
out.println("</td></tr>");
}

76
out.close();
Recordset.close();
StatementRecordset.close();
ConnRecordset.close();
}
catch(SQLException sqe)
{
out.print("Error"+sqe);
}
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
ConnRecordset=DriverManager.getConnection("jdbc:odbc:ex7");
StatementRecordset = ConnRecordset.prepareStatement("SELECT * FROM
Student");
Recordset = StatementRecordset.executeQuery();
}
catch(Exception e){}
processRequest(request, response);
}}

OUTPUT

77
RESULT:

Thus the Servlet program has been developed to display the students mark list.

78
EX NO:7 JSP PROGRAM FOR ORDER PROCESSING

AIM

To create a JSP program to perform Order Processing.

PROCEDURE

STEP 1: Design a HTML form which includes product name,customer name, date of
purchase.
STEP 2:Get the required details from the user .
STEP 3: Using the details given, process the data using JSP.Retrieve the data from the database
using the given product number.
STEP 4: If the product is available, save the customer details and display the product details.
STEP 5: If there is no stock, display that the product is not available.
STEP 6: Execute and save the process.

PROGRAM

main.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<form name="form1" action="serverside.jsp" method="post">

<h1><center> BOOK STORE</center></h1>


<h2><p> ENTER THE BOOK DETAILS </p></h2>
<center>
<table>
<tr>
<td><h4>Enter the name</h4></td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td><h4>Address</h4></td>
<td><input type="text" name="address"></td>
</tr>
<tr>
<td><h4>Email</h4></td>

79
<td><input type="text" name="email"></td>
</tr>
<tr>
<td><h4>Mobile</h4></td>
<td><input type="text" name="mobile"></td>
</tr>
<tr>
<td><h4>Book Title</h4></td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td><h4>Author</h4></td>
<td><input type="text" name="author"></td>
</tr>
<tr>
<td><h4>Publisher</h4></td>
<td><input type="text" name="publisher"></td>
</tr>
<tr>
<td><h4>Edition</h4></td>
<td><input type="text" name="edition"></td>
</tr>
<tr>
<td><h4>No.of Books</h4></td>
<td><input type="text" name="quantity"></td>
</tr>
<tr>
<td><input type="submit" name="submit"></td>
</tr>
</table>
</center>
</form>
<body>

</body>
</html>

serverside.jsp

<%@ page import="java.io.*,java.sql.*,java.lang.*" %>


<%!
String name = "test";
String pass = "test";
String url = "jdbc:odbc:order";
Connection con=null;
Statement st=null;

80
String t1=" ";
String t2=" ";
String t3=" ";
String t4=" ";
String t5=" ";
String t6=" ";
String t7=" ";
String t8=" ";
String t9=" ";

int no;
%>
<%
try
{

t1=request.getParameter("name");
t2=request.getParameter("address");
t3=request.getParameter("email");
t4=request.getParameter("mobile");
t5=request.getParameter("title");
t6=request.getParameter("author");
t7=request.getParameter("publisher");
t8=request.getParameter("edition");
t9=request.getParameter("quantity");

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(url, name, pass);

st=con.createStatement();
no=st.executeUpdate("insert into jsp_book
values('"+t1+"','"+t2+"','"+t3+"','"+t4+"','"+t5+"','"+t6+"','"+t7+"','"+t8+"','"+t9+"')");
con.close();

out.println("<h1> <br><br><br><br><center>THANKS FOR YOUR ORDER</center>");


out.println("<h1>Mr/Ms. "+t1+"<h3> your request for the following book(s) Will dispatch
as soon as poosible ");
out.println("<center><table> <tr> <td><h4> Book Title :</h4></td><td> "+t5+"
</td></tr>");
out.println("<tr> <td><h4> Author :</h4></td><td>" +t6+ "</td></tr>" );
out.println("<tr> <td><h4> Publisher :</h4></td><td>" +t7+
"</td></tr></table></center>");

catch(SQLException e){
out.println("Error"+e);

81
}
%>

OUTPUT

RESULT
Thus the program to perform Order Processing using JSP has been created and executed

successfully.

82
Ex.No.8 C# Programming in .Net platform

Aim
To Create a namespace using C# in .net platform

Procedure
1. Start Microsoft Visual C# 2005 and create a new Console Application named
RealEstate1
2. To create a new class, in the Class View, right-click the name of the project,
position the mouse on Add and click Class...
3. Change the name to House and press Enter
4. Change the class as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RealEstate1
{
public class House
{
public string PropertyNumber;
public char PropertyType;
public uint Stories;
public uint Bedrooms;
public float Bathrooms;
public double Value;
}
}
5. Save the file

Accessing Members of a Namespace


After creating the necessary members of a namespace, you can use the period operator to
access an item that is part of the namespace. To do this, in the desired location, type the
name of the namespace, followed by a period, followed by the desired member of the
namespace. Here is an example:

using System;

namespace Business
{
public class House
{
public string PropertyNumber;
public decimal Price;
}
}

public class Exercise

83
{
static void Main()
{
Business.House property = new Business.House();

property.PropertyNumber = "D294FF";
property.Price = 425880;

Console.WriteLine("=//= Altair Realty =//=");


Console.WriteLine("Properties Inventory");
Console.Write("Property #: ");
Console.WriteLine(property.PropertyNumber);
Console.Write("Market Value: ");
Console.WriteLine(property.Price);
Console.WriteLine();
}
}

Output
=//= Altair Realty =//=
Properties Inventory
Property #: D294FF
Market Value: 425880

Press any key to continue . . .

Namespace Nesting
You can create one namespace inside of another namespace. Creating a namespace inside
of another is referred to as nesting the namespace. The namespace inside of another
namespace is nested. To create a namespace inside of another, simply type it as you
would create another namespace. Here is an example:

namespace Business
{
public class House
{
public string PropertyNumber;
public decimal Price;
}

namespace Dealer
{
}
}

In the example above, the Dealer namespace is nested inside of the Business namespace.
After creating the desired namespaces, nested or not, you can create the necessary
class(es) inside of the desired namespace. To access anything that is included in a nested
namespace, you use the period operator before calling a member of a namespace or
before calling the next nested namespace. Here is an example:

using System;

namespace Business
{
public class House

84
{
public string PropertyNumber;
public decimal Price;
}

namespace Dealer
{
public class Car
{
public decimal Price;
}
}
}

public class Exercise


{
static void Main()
{
Business.House property = new Business.House();

property.PropertyNumber = "D294FF";
property.Price = 425880;

Console.WriteLine("=//= Altair Realty =//=");


Console.WriteLine("Properties Inventory");
Console.Write("Property #: ");
Console.WriteLine(property.PropertyNumber);
Console.Write("Market Value: ");
Console.WriteLine(property.Price);
Console.WriteLine();

Business.Dealer.Car vehicle = new Business.Dealer.Car();


vehicle.Price = 38425.50M;

Console.Write("Car Value: ");


Console.WriteLine(vehicle.Price);
}
}

Output

=//= Altair Realty =//=


Properties Inventory
Property #: D294FF
Market Value: 425880

Car Value: 38425.50


Press any key to continue . .

Result
Thus the program for creating a namespace using c# in .net platform has been executed
successfully.

85
References

Websites
1) http://www.functionx.com/csharp/Lesson05.htm
2) http://www.w3schools.com
3) http://www.w3c.org

Books
1) R.Bremananth-C.S. Senthil Raja, V.Sivakumar – Web Technology – Pradeepa
Publishers
2) Rashim Mogha, Preetham.V.V., “ Java Web Services Programming”, Wiley
Dreamtech, New Delhi, 2002.
3) Achyut S Godbole and Atul Kahate, “Web Technologies – TCP/IP
Architectures and Java Programming”, Second Edition, Tata Mc-Graw Hill
Education Pvt., Ltd., New Delhi, 2009
4). E Balagurusamy, “Programming in C#”, Second Edition, Tata Mc-Graw hill
Publishing Co. Ltd., New Delhi, 2008
5) Deitel ,“ XML How to Program”, first edition, Pearson Education, USA, 2002.
6) Jason Hunter, William Crawford, “Java Servlet Programming”, O’ Reilly
Publications, USA, 1998.

86

You might also like