Sei sulla pagina 1di 45

Web Technologies 1

Overview of Internet and web

Contents of a website

URL: In computing, a uniform resource locator (URL) is a specific character string that constitutes a reference to an
Internet resource. A URL is technically a type of uniform resource identifier (URI) but in many technical documents
and verbal discussions URL is often used as a synonym for URI. Example: www.facebook.com

Web Browser: A web browser is a software application for retrieving, presenting, and traversing information
resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier (URI) and
may be a web page, image, video, or other piece of content. Hyperlinks present in resources enable users easily to
navigate their browsers to related resources. A web browser can also be defined as an application software or
program designed to enable users to access, retrieve and view documents and other resources on the Internet.
Although browsers are primarily intended to access the World Wide Web, they can also be used to access
information provided by web servers in private networks or files in file systems. The major web browsers are Firefox,
Google Chrome, Internet Explorer, Opera, and Safari.

How a webpage is fetch: A web page or webpage is a document or information resource that is suitable for the
World Wide Web and can be accessed through a web browser and displayed on a monitor or mobile device. This
information is usually in HTML or XHTML format, and may provide navigation to other web pages via hypertext links.
Web pages frequently subsume other resources such as style sheets, scripts and images into their final presentation.
Web pages may be retrieved from a local computer or from a remote web server. The web server may restrict access
only to a private network, e.g. a corporate intranet, or it may publish pages on the World Wide Web. Web pages are
requested and served from web servers using Hypertext Transfer Protocol (HTTP).
Web pages may consist of files of static text and other content stored within the web server's file system (static web
pages), or may be constructed by server-side software when they are requested (dynamic web pages). Client-side
scripting can make web pages more responsive to user input once on the client browser.
Web Technologies 2

Introduction to 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 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. When you save an HTML file, you can use either
the .htm or the .html file extension.

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. Most
HTML elements can be nested (can contain other HTML elements). HTML documents consist of nested 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".
Class: Specifies a class name for an element.
Id: Specifies a unique id for an element.
Style: Specifies an inline style for an element.
Title: Specifies extra information about an element (displayed as a tool tip).

HTML Document Example


<html>
<head>
<title></title>
</head>
<body></body>
</html>
Web Technologies 3

HTML <body>: The <body> element defines the body of the HTML document. The element has a start tag
<body> and an end tag </body>.
HTML <html>: The <html> element defines the whole HTML document. The element has a start tag <html> and
an end tag </html>.
HTML Headings: Headings are defined with the <h1> to <h6> tags. <h1> defines the most important heading.
<h6> defines the least important heading. Use HTML headings for headings only. Don't use headings to make
text BIG or bold. Search engines use your headings to index the structure and content of your web pages. Since
users may skim your pages by its headings, it is important to use headings to show the document structure. H1
headings should be used as main headings, followed by H2 headings, then the less important H3 headings, and
so on.
HTML Paragraphs: The <p> element defines a paragraph in the HTML document. The element has a start tag <p>
and an end tag </p>.
HTML Lines: The <hr /> tag creates a horizontal line in an HTML page.
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. (<!-- This is a comment -->)
HTML Line Break: HTML elements with no content are called empty elements. <br> is an empty element without
a closing tag (the <br> tag defines a line break). In XHTML, XML, elements with no end tag (closing tag) are not
allowed. Even if <br> works in all browsers, writing <br /> instead works better in XHTML and XML applications.
HTML Formatting Tags:
HTML Text Formatting Tags:
<b>: Defines bold text
<big>: Defines big text
<em>: Defines emphasized text
<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
HTML Computer Output Tags:
<code>: Defines computer code text
<kbd>: Defines keyboard text
<samp>: Defines sample computer code
<tt>: Defines teletype text
<var>: Defines a variable
<pre>: Defines preformatted text
HTML Citations, Quotations, and Definition Tags:
<abbr>: Defines an abbreviation
<acronym>: Defines an acronym
<address>: Defines contact information for the author/owner of a document
<bdo>: Defines the text direction
<blockquote>: Defines a long quotation
<q>: Defines a short quotation
<cite>: Defines a citation
<dfn>: Defines a definition term
Web Technologies 4

HTML Font Tag: The <font> tag is deprecated in HTML 4, and removed from HTML5. The World Wide Web
Consortium (W3C) has removed the <font> tag from its recommendations. In HTML 4, style sheets (CSS) should
be used to define the layout and display properties for many HTML elements.
HTML 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 (<a href="url">Link text</a>).
The <a> tag can be used in two ways:
To create a link to another document, by using the href attribute
To create a bookmark inside a document, by using the name attribute
HTML Images: 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 (<img src="url"
alt="some_text"/>). The URL points to the location where the image is stored. 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.
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>: 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

HTML Table Example


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

HTML Lists: The most common HTML lists are ordered and unordered lists.
Web Technologies 5

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

HTML Ordered List Example


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

HTML Unordered List Example


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

HTML Definition List


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

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 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.
<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 field set 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

HTML Form Examples


<form name="input" action="html_form_action.asp" method="get">
<input type="text" name="firstname" />
Web Technologies 6

<input type="password" name="pwd" />


<input type="radio" name="sex" value="male" />
<input type="checkbox" name="vehicle" value="Bike" />
<input type="submit" value="Submit" />
</form>

HTML 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 HTML frameset Element: The frameset element holds one or more frame elements. Each frame
element can hold a separate document. The frameset element states HOW MANY columns or rows there
will be in the frameset, and HOW MUCH percentage/pixels of space will occupy each of them.
The HTML frame Element: The <frame> tag defines one particular window (frame) within a frameset. 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
document "frame_a.htm" is put into the first column, and the document "frame_b.htm" is put into the
second column:
The HTML noframes Element: The <noframes> tag is a fallback tag for browsers that do not support
frames. It can contain all the HTML elements that you can find inside the <body> element of a normal
HTML page. The <noframes> element can be used to link to a non-frameset version of the web site or to
display a message to users that frames are required. The <noframes> element goes inside the
<frameset> element.

The disadvantages of using frames are:


Frames are not expected to be supported in future versions of HTML.
Frames are difficult to use. (Printing the entire page is difficult).
The web developer must keep track of more HTML documents.

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

HTML IFrames: The <iframe> tag specifies an inline frame. An inline frame is used to embed another document
within the current HTML document. An iframe is used to display a web page within a web page (<iframe
src="demo_iframe.htm" width="200" height="200"></iframe>). The URL points to the location of the separate
page. The height and width attributes are used to specify the height and width of the iframe. The attribute
values are specified in pixels by default, but they can also be in percent (like "80 %").

HTML DOM

The DOM is a W3C (World Wide Web Consortium) standard. The W3C Document Object Model (DOM) is a platform
and language-neutral interface that allows programs and scripts to dynamically access and update the content,
structure, and style of a document. The DOM defines the objects and properties of all document elements, and the
methods (interface) to access them. The DOM is separated into 3 different parts / levels:
Core DOM - standard model for any structured document
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
Web Tecchnologiess 7

The HTML DOM defines the objects


o and properties
p off all HTML elements, and the method
ds (interface) to access
them
m. The HTML DOM
D is
A standarrd object mod
del for HTML
A standarrd programmiing interface for HTML
Platform- and language-independen nt
A W3C staandard

According to the DOM,


D everythhing in an HTML document is a node. The DOM sayss:
The entiree document iss a documentt node
Every HTM ML element iss an element node
The text in the HTML elements
e is te
ext nodes
Every HTM ML attribute is
i an attributee node
Commentts are comme ent nodes

HTM
ML DOM Exam
mple
<htm
ml>
<head>
<tiitle>DOM Tuttorial</title>
</heead>
<bo
ody>
<h1>DOM Lesso on one</h1>
<p>Hello world!!</p>
</boody>
</htm
ml>

The root node in the HTML above


a is <htm
ml>. All otherr nodes in th
he documentt are containeed within <html>. The
<htm
ml> node has two child noodes; <head>> and <body>>. The <head> node holdss a <title> noode. The <boody> node
holdss a <h1> and <p> node.

The HTML DOM Node Tree: The T HTML DOM views an n HTML docu ument as a trree-structuree. The tree sttructure is
d a node-tree
called c be accesssed through the tree. Their contents caan be modifieed or deleted, and new
e. All nodes can
Web Tecchnologiess 8

elem
ments can be created.
c The node tree below shows th he set of nodees, and the coonnections beetween them
m. The tree
starts at the root node and braanches out to
o the text nodes at the low
west level of th
he tree. (Above diagram)

Nodee Parents, Chhildren, and Siblings:


S The nodes
n in the node tree haave a hierarch
hical relationsship to each o
other. The
terms parent, child, and sibling are used to o describe the relationship ps. Parent no
odes have children. Childrren on the
samee level are callled siblings (b
brothers or siisters).
In a node tree, the top p node is calleed the root
Every nod de, except the e root, has exxactly one parrent node
A node caan have any numbern of children
A leaf is a node with no o children
Siblings arre nodes with h the same paarent

m the HTML above (HTML DOM examp


From ple):
The <html> node has non parent nodde; it is the ro
oot node
The parennt node of the
e <head> andd <body> nodes is the <htm ml> node
The parennt node of the
e "Hello world
d!" text nodee is the <p> no
ode

The <html> node has two


t child nodes; <head> and <body>
The <head d> node has one
o child nod de; the <title>> node
The <title> node also has
h one child node; the texxt node "DOM M Tutorial"
The <h1> and <p> nodes are siblinggs, and both cchild nodes off <body>

First Child - Last Child


C (HTML DOM
D example)
The <head d> element iss the first child of the <html> element,, and the <bo
ody> elementt is the last ch
hild of the
<html> element
The <h1> > element is the first child of the <bo ody> elementt, and the <pp> element is the last ch hild of the
<body> ellement

Programming Inte erface: In thee DOM, HTML documents consist of a set of node o objects. The nodes
n can bee accessed
with JavaScript or other programming languages. The programming interface o of the DOM isi defined byy standard
properties and meethods.
Properties are often reeferred to as something
s th
hat is (i.e. the name of a no
ode).
Methods are often refe omething that is done (i.e.. remove a no
erred to as so ode).
Web Technologies 9

HTML DOM Properties


x.innerHTML - the text value of x
x.nodeName - the name of x
x.nodeValue - the value of x
x.parentNode - the parent node of x
x.childNodes - the child nodes of x
x.attributes - the attributes nodes of x

HTML DOM Methods


x.getElementById(id) - get the element with a specified id
x.getElementsByTagName(name) - get all elements with a specified tag name
x.appendChild(node) - insert a child node to x
x.removeChild(node) - remove a child node from x

HTML innerHTML property example


<html>
<body>
<p id="intro">Hello World!</p>
<script type="text/javascript">
txt=document.getElementById("intro").innerHTML;
document.write("<p>The text from the intro paragraph: " + txt + "</p>");
</script>
</body>
</html>

Output in the browser

Hello World!
The text from the intro paragraph: Hello World!

HTML childNodes and nodeValue example


<html>
<body>
<p id="intro">Hello World!</p>
<script type="text/javascript">
txt=document.getElementById("intro").childNodes[0].nodeValue;
document.write("<p>The text from the intro paragraph: " + txt + "</p>");
</script>
</body>
</html>

Output in the browser

Hello World!
The text from the intro paragraph: Hello World!

HTML DOM getElementByid() example


<html>
Web Technologies 10

<body>
<p id="intro">Hello World!</p>
<p>This example demonstrates the <b>getElementById</b> method!</p>
<script type="text/javascript">
x=document.getElementById("intro");
document.write("<p>The text from the intro paragraph: " + x.innerHTML + "</p>");
</script>
</body>
</html>

Output in the browser

Hello World!
This example demonstrates the getElementById method!
The text from the intro paragraph: Hello World!

HTML DOM getElementByTagName() example


<html>
<body>
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>
<script type="text/javascript">
x=document.getElementsByTagName("p");
document.write("Text of first paragraph: " + x[0].innerHTML);
</script>
</body>
</html>

Output in the browser

Hello World!
The DOM is very useful!
This example demonstrates the getElementsByTagName method.
Text of first paragraph: Hello World!

HTML DOM Events: Every element on a web page has certain events which can trigger JavaScript functions. 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 elements.
A mouse click
A web page or an image loading
Mousing over a hot spot on the web page
Selecting an input box in an HTML form
Submitting an HTML form
A keystroke

Mouse Events
click (onclick):The event occurs when the user clicks on an element.
Web Technologies 11

dblclick (ondblclick):The event occurs when the user double-clicks on an element.


mousedown (onmousedown):The event occurs when a user presses a mouse button over an element.
mousemove (onmousemove):The event occurs when a user moves the mouse pointer over an element.
mouseover (onmouseover):The event occurs when a user mouse over an element.
mouseout (onmouseout):The event occurs when a user moves the mouse pointer out of an element.
mouseup (onmouseup):The event occurs when a user releases a mouse button over an element.

Keyboard Events
keydown (onkeydown):The event occurs when the user is pressing a key or holding down a key.
keypress (onkeypress):The event occurs when the user is pressing a key or holding down a key.
keyup (onkeyup):The event occurs when a keyboard key is released.

Frame/Object Events
abort (onabort):The event occurs when an image is stopped from loading before completely loaded (for
<object>).
error (onerror):The event occurs when an image does not load properly (for <object>, <body> and
<frameset>).
load (onload):The event occurs when a document, frameset, or <object> has been loaded.
resize (onresize):The event occurs when a document view is resized.
scroll (onscroll):The event occurs when a document view is scrolled.
unload (onunload):The event occurs when a document is removed from a window or frame (for <body> and
<frameset>).

Form Events
blur (onblur):The event occurs when a form element loses focus.
change (onchange):The event occurs when the content of a form element, the selection, or the checked
state have changed (for <input>, <select>, and <textarea>).
focus (onfocus):The event occurs when an element gets focus (for <label>, <input>, <select>, textarea>, and
<button>).
reset (onreset):The event occurs when a form is reset.
select (onselect):The event occurs when a user selects some text (for <input> and <textarea>).
submit (onsubmit):The event occurs when a form is submitted.

Introduction to Java Script

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 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 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.
Web Technologies 12

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.

JavaScript Functions and Events: Java Scripts in an HTML page will be executed when the page loads. This is not
always what we want. Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks
a button. When this is the case we can put the script inside a function. Events are normally used in combination with
functions (like calling a function when an event occurs).

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 at the same time. It is a common practice to put all functions in the
head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.

Using an External JavaScript: Java Script can also be placed in external files. External JavaScript files often contain
code to be used on several different web pages. External JavaScript files have the file extension .js. (<script
type="text/javascript" src="xxx.js"></script>)

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 Code: JavaScript code (or just JavaScript) is a sequence of JavaScript statements. Each statement is
executed by the browser in the sequence they are written.

JavaScript Blocks: JavaScript statements can be grouped together in blocks. Blocks start with a left curly bracket {,
and end with a right curly bracket}. The purpose of a block is to make the sequence of statements execute together.

JavaScript Comments: Comments can be added to explain the JavaScript, or to make the code more readable. Single
line comments start with //. JavaScript Multi-Line Comments Multi line comments start with /* and end with */.

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, the $ character, or the underscore character

Creating variables in JavaScript is most often referred to as "declaring" variables. You declare JavaScript variables
with the var keyword:
var x;
var carname;

Local JavaScript Variables: A variable declared within a JavaScript function becomes LOCAL and can only be accessed
within that function. (The variable has local scope). You can have local variables with the same name in different
functions, because local variables are only recognized by the function in which they are declared. Local variables are
destroyed when you exit the function.
Web Technologies 13

Global JavaScript Variables: Variables declared outside a function become GLOBAL, and all scripts and functions on
the web page can access it. Global variables are destroyed when you close the page. If you declare a variable,
without using "var", the variable always becomes GLOBAL.

Conditional Statements

If Statement
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
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
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 neither condition1 nor condition2 is true
}

Switch Statement
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
}

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. (alert ("sometext"); )

Confirm Box: A confirms box is often used if you want the user to verify or accept something. 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. (confirm("sometext"); )
Web Technologies 14

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.
(prompt("sometext","defaultvalue"); )

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.

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

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.

Example of function and return statement


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

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

For Statement
for (variable=startvalue;variable<=endvalue;variable=variable+increment)
{
code to be executed
}
Web Technologies 15

While: loops through a block of code while a specified condition is true

While Statement
while (variable<=endvalue)
{
code to be executed
}

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.

Do while loop Statement


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

The break Statement: The break statement will break the loop and continue executing the code that follows after
the loop.

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

For...In Statement: The for...in statement loops through the properties of an object.

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

Example of For in Statement


var person={fname:"John",lname:"Doe",age:25};
var x;

for (x in person)
{
document.write(person[x] + " ");
}

Events: By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be
detected by JavaScript. 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:
Web Technologies 16

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

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: (<form
method="post" action="xxx.htm" onsubmit="return checkForm()">)

onMouseOver: The onmouseover event can be used to trigger a function when the user mouses over an HTML
element

Catching Errors: When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is
a runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers but not for
users. When users see errors, they often leave the Web page.

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.

Try Catch Statement


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

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. (throw
exception)
Web Technologies 17

Error Handling Example


<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 5 and 10:","");
try
{
if(x>10)
{
throw "Err1";
}
else if(x<5)
{
throw "Err2";
}
else if(isNaN(x))
{
throw "Err3";
}
}
catch(err)
{
if(err=="Err1")
{
document.write("Error! The value is too high.");
}
if(err=="Err2")
{
document.write("Error! The value is too low.");
}
if(err=="Err3")
{
document.write("Error! The value is not a number.");
}
}
</script>
</body>
</html>

Insert Special Characters: The backslash (\) is used to insert apostrophes, new lines, quotes, and other special
characters into a text string.
\': single quote
\": double quote
\\: backslash
\n: new line
\r: carriage return
\t: tab
\b: backspace
Web Tecchnologiess 18

\f: form fe
eed

Intro
oduction to Caascading Stylle Sheets

CSS stands
s for Caascading Style
e Sheets. Stylles define how
w to display HTML elemen nts. Styles weere added to HTML 4.0
to soolve a problem. External Style
S Sheets can
c save a lo ot of work. Exxternal Style Sheets are stored
s in CSS files. CSS
Saves a Lot of Wo ork! CSS defin
nes HOW HTM ML elements aare to be disp played. Styless are normallyy saved in extternal .css
files. External style sheets enaable you to change
c the ap
ppearance an nd layout of aall the pages in a Web sitte, just by
editinng one single file!

CSS Syntax:
S A CSSS rule has two nd one or more declarations:
o main parts: a selector, an
The selecttor is normallly the HTML element
e you want
w to style.
Each declaration consists of a prope erty and a vallue.
The propeerty is the styyle attribute you
y want to change. Each property
p has a value.

CSS Comments:
C Comments
C arre used to exxplain your co
ode, and mayy help you w
when you editt the source code at a
later date. Comments are ignored by browssers. A CSS coomment beginns with "/*", aand ends with "*/"

The idi and class Selectors: In addition to setting a style for a HTM ML element, C CSS allows yoou to specify your own
selecctors called "id" and "class".
The id Selector: The id selector is ussed to specifyy a style for a single, uniqu
ue element. The
T id selecto or uses the
id attributte of the HTM
ML element, and
a is defined d with#".
The class Selector: Thee class selectoor is used to specify
s a style
e for a group of elements.. Unlike the id d selector,
the class selector is most often useed on severall elements. This allows yo ou to set a paarticular style for many
HTML elements with the t same classs. The class sselector usess the HTML cllass attributee, and is defin ned with a
"."

Three Ways to Inssert CSS: There are three ways


w of insertting a style sh
heet:
External style
s sheet: AnA external style sheet is ideal when n the style iss applied to many pages. With an
external style
s sheet, yoou can changge the look off an entire Weeb site by chaanging one file. Each pagee must link
to the styyle sheet usinng the <link> tag. The <lin nk> tag goes inside the head section: (<link rel="sttylesheet"
type="texxt/css" href="mystyle.css" />)
Internal style sheet: An internal styyle sheet should be used when w h a unique style. You
a singlee document has
define intternal styles in the head d section of an HTML paage, by using the <style> tag, like this:(<style
type="texxt/css"></style>)
Inline style: An inline style
s loses maany of the advvantages of sttyle sheets byy mixing conttent with pressentation.
Use this method
m sparringly! To usee inline styles you use th he style attribbute in the relevant
r tag. The style
attribute can contain any
a CSS propeerty. The example shows how h to changge the color and a the left margin
m of a
paragraph h:(<p style="ccolor:sienna;mmargin-left:200px">This is a paragraph.<</p>)
Web Technologies 19

All CSS Background Properties


background: Sets all the background properties in one declaration
background-attachment: Sets whether a background image is fixed or scrolls with the rest of the page
background-color: Sets the background color of an element
background-image: Sets the background image for an element
background-position: Sets the starting position of a background image
background-repeat: Sets how a background image will be repeated

All CSS Text Properties


color: Sets the color of text
direction: Specifies the text direction/writing direction
letter-spacing: Increases or decreases the space between characters in a text
line-height: Sets the line height
text-align: Specifies the horizontal alignment of text
text-decoration: Specifies the decoration added to text
text-indent: Specifies the indentation of the first line in a text-block
text-shadow: Specifies the shadow effect added to text
text-transform: Controls the capitalization of text
unicode-bidi:
vertical-align: Sets the vertical alignment of an element
white-space: Specifies how white-space inside an element is handled
word-spacing: Increases or decreases the space between words in a text

All CSS Font Properties


font: Sets all the font properties in one declaration
font-family: Specifies the font family for text
font-size: Specifies the font size of text
font-style: Specifies the font style for text
font-variant: Specifies whether or not a text should be displayed in a small-caps font
font-weight: Specifies the weight of a font

All CSS List Properties


list-style: Sets all the properties for a list in one declaration
list-style-image: Specifies an image as the list-item marker
list-style-position: Specifies if the list-item markers should appear inside or outside the content flow
list-style-type: Specifies the type of list-item marker

All CSS Border Properties


border: Sets all the border properties in one declaration
border-bottom: Sets all the bottom border properties in one declaration
border-bottom-color: Sets the color of the bottom border
border-bottom-style: Sets the style of the bottom border
border-bottom-width: Sets the width of the bottom border
border-color: Sets the color of the four borders
border-left: Sets all the left border properties in one declaration
border-left-color: Sets the color of the left border
border-left-style: Sets the style of the left border
border-left-width: Sets the width of the left border
Web Technologies 20

border-right: Sets all the right border properties in one declaration


border-right-color: Sets the color of the right border
border-right-style: Sets the style of the right border
border-right-width: Sets the width of the right border
border-style: Sets the style of the four borders
border-top: Sets all the top border properties in one declaration
border-top-color: Sets the color of the top border
border-top-style: Sets the style of the top border
border-top-width: Sets the width of the top border
border-width: Sets the width of the four borders

All CSS Margin Properties


margin: A shorthand property for setting the margin properties in one declaration
margin-bottom: Sets the bottom margin of an element
margin-left: Sets the left margin of an element
margin-right: Sets the right margin of an element
margin-top: Sets the top margin of an element

All CSS Padding Properties


padding: A shorthand property for setting all the padding properties in one declaration
padding-bottom: Sets the bottom padding of an element
padding-left: Sets the left padding of an element
padding-right: Sets the right padding of an element
padding-top: Sets the top padding of an element

Styling Links: Links can be styled with any CSS property. Special for links are that they can be styled differently
depending on what state they are in. The four links states are:
a:link - a normal, unvisited link
a:visited - a link the user has visited
a:hover - a link when the user mouses over it
a:active - a link the moment it is clicked

DHTML

DHTML stands for Dynamic HTML. DHTML is NOT a language or a web standard. To most people DHTML means the
combination of HTML, JavaScript, DOM and CSS.
JavaScript and the HTML DOM: A JavaScript can also be used to change the content or attributes of HTML elements.
To change the content of an HTML element: document.getElementById(id).innerHTML=new HTML;
To change the attribute of an HTML element: document.getElementById(id).attribute=new value;

JavaScript and HTML Events: A JavaScript can also be executed when an event occurs, like when a user clicks on an
HTML element.
To execute code when a user clicks on an element, use the following event attribute: onclick=JavaScript

JavaScript and CSS: A JavaScript can also change the style of HTML elements.
To change the style of an HTML element: document.getElementById(id).style.property=new style
Web Technologies 21

Dream Weaver

Adobe Dreamweaver (formerly Macromedia Dreamweaver) is a proprietary web development application originally
created by Macromedia. It is now developed by Adobe Systems, which acquired Macromedia in 2005.

Dreamweaver is available for both Mac and Windows operating systems. Recent versions have incorporated support
for web technologies such as CSS, JavaScript, and various server-side scripting languages and frameworks including
ASP (ASP JavaScript, ASP VBScript, ASP.NET C#, and ASP.NET VB), ColdFusion, Script let, and PHP.

The common misconception with Dreamweaver is that Dreamweaver is designed to or is even capable of completely
removing the agency of HTML and CSS coding from web design. This is like saying that a nail-gun can completely
replace a hammer. A nail-gun will nail the boards together, but it is an imprecise tool, and there is a certain amount
of danger while using it. If you cant occasionally fall back on the hammer for more detail-oriented work, then theres
a definite limit to what you can build. A skilled carpenter knows how to use the hammer and occasionally does so
when the nail-gun just isnt doing what is intended.

Dreamweaver, like the nail-gun, is designed to make your life easier. You may never learn HTML or CSS, but without
knowing them, you are limited to Dreamweavers way of doing things. This is not altogether a bad thing: it is simply a
slightly narrow perspective on a large field.
Writing Content: HTML can be cumbersome. Dreamweaver writes (for the most part) good, valid HTML
using an easy point-and-click interface.
Managing Files: Unless you are using a scripting language like PHP, managing a large site with many pages
and files can quickly become a mess. Dreamweaver has built-in dependency tracking that will automatically
manage your files and will update your pages accordingly. Many people use Dreamweaver just for its built-in
synchronization tool.
Preliminary Page Layout: Dreamweaver has good tools to assist you in laying out your site. There are also a
lot of pre-fab layouts and templates available as starting points in Dreamweaver CS3.
Dreamweavers layout features are, however, somewhat limiting. Some designs are simply impossible to
achieve using the buit-in layout tools. In these cases, you can go in and manually edit the HTML and CSS that
Dreamweaver produces to tweak to exactly what you need.

Gif Animator

GIF Animator can be used to create an animation by linking images together, similar to creating a "flip book." Just
insert each separate image into the animator, and then set the frame rate to determine the speed. Once you have
inserted all the images, you can save the file as either a gif image, an .avi movie, or even a flash movie. Then the
animator will generate the html code necessary to display your creation on your web page. Microsoft GIF Animator
is a historical computer software program for Microsoft Windows to create simple animated GIF files based on the
GIF89a file format. It was freely downloadable from the Microsoft Download Center but is now only available
through MSDN and on third party download sites. It was also bundled with Microsoft Image Composer and Microsoft
FrontPage. Animations can be looped, spun, and faded in and out; users can set the size and transparency of images.
Automatic and custom palette creations are supported.
Web Technologies 22

Classic ASP: Active Server Pages (ASP), also known as Classic ASP, was introduced in 1998 as Microsoft's first server
side scripting engine. ASP is a technology that enables scripts in web pages to be executed by an Internet server. ASP
pages have the file extension .asp, and are normally written in VBScript.

ASP.NET: ASP.NET is a new ASP generation. It is not compatible with Classic ASP, but ASP.NET may include Classic
ASP. ASP.NET pages are compiled, which makes them faster than Classic ASP. ASP.NET has better language support,
a large set of user controls, XML-based components, and integrated user authentication. ASP.NET pages have the
extension .aspx, and are normally written in VB (Visual Basic) or C# (C sharp). User controls in ASP.NET can be
written in different languages, including C++ and Java. When a browser requests an ASP.NET file, the ASP.NET engine
reads the file, compiles and executes the scripts in the file, and returns the result to the browser as plain HTML.

ASP.NET Razor: Razor is new and simple markup syntax for embedding server code into ASP.NET web pages, much
like Classic ASP. Razor has the power of traditional ASP.NET, but is easier to use and easier to learn.

ASP.NET Programming Languages


Visual Basic (VB.NET)
C# (Pronounced C sharp)

ASP.NET Server Technologies


Web Pages (with Razor syntax)
MVC (Model View Controller)
Web Forms (traditional ASP.NET)

ASP.NET Development Tools


WebMatrix
Visual Web Developer
Visual Studio

ASP.NET File Extensions


Classic ASP files have the file extension .asp
ASP.NET files have the file extension .aspx
ASP.NET files with Razor C# syntax have the file extension .cshtml
ASP.NET files with Razor VB syntax have the file extension .vbhtml

Web Pages: It is the simplest programming model for developing ASP.NET web pages. Web Pages are easy
extendable with programmable Web Helpers, including database, video, graphics, social networking and much more.
Web Pages provide an easy way to combine HTML, CSS, and JavaScript and server code:
Easy to learn, understand, and use
Built around single web pages
Similar to PHP and Classic ASP
Top-to-bottom server execution
Server scripting with Visual Basic or C#
Full HTML, CSS, and JavaScript control

Working of an asp.net page: Fundamentally an ASP.NET page is just the same as an HTML page. An HTML page has
the extension .htm. If a browser requests an HTML page from the server, the server sends the page to the browser
without any modifications. An ASP.NET page has the extension .aspx. If a browser requests an ASP.NET page, the
server processes any executable code in the page, before the result is sent back to the browser. The ASP.NET page
Web Tecchnologiess 23

abovve does not contain any executable code,


c so nothing is execu
uted. In the next examples we will add
a some
executable code to
t the page to nce between static HTML pages and dyynamic ASP paages.
o demonstratte the differen

ding an asp.net application


Build
Open Visu ual Studios frrom your Starrt menu by cllicking on its "Microsoft V Visual Studios 2010". It will take few
seconds to open.
Go to File Menu and Click on New Web W Site
A Dialogue box will appear asking for f Template, Location, Language. Selecct/write the location
l in the location
TextBox, Select ASP.NET Web Site as Tempate and Select Visual C# as laanguage as displayed in th he picture
below. Cliick OK.
This will create a deffault.aspx, deefault.aspx.cs (it is called as codebehiind file) file, web.cofig file and an
App_Dataa (It is used too place your database
d like MS Access orr SQL Expresss or xml files ) folder by default
Start writing few codes as displayed in the pictu ure below. Yo
ou can notice that as soon as you starteed writing
code, Visuual Web Deve elope will givee intellisense (dropdown) to complete the t code of the control
Now presss F7 key fro om the Keyboard and you will jump to the Codebehind file named n defau ult.aspx.cs.
Alternativvely you can click + symbo ol beside the default.aspxx file and dou uble click defaault.aspx.cs. Write
W few
lines of co
ode into it. In this file Page
e_Load metho od will be auttomatically wwritten. Now Save
S all files by
b clicking
on the Savve All toolbarr or by going through
t File->>Save All.
Now hit F5 F key from your
y keyboard d and your ap pplication will start in the debug mode e. Alternativelly you can
click on the
t Play buttton from the toolbar. This will ask you to modify the web.cofig file to start the
applicatioon in the debu ug mode.
After few seconds a brrowser will op pen with yourr default.aspxx page
Web Technologies 24

Limitations in Classic ASP: With Classic ASP it is impossible to separate executable code from the HTML itself. This
makes the page difficult to read, and difficult to maintain.

ASP.Net Page Life Cycle: When a page is requested, it is loaded into the server memory, processed and sent to the
browser. Then it is unloaded from the memory. At each of this steps, methods and events are available, which could
be overridden according to the need of the application. In other words, you can write your own code to override the
default code. The Page class creates a hierarchical tree of all the controls on the page. All the components on the
page, except the directives are part of this control tree. You can see the control tree by adding trace= "true" to the
Page directive. We will cover page directives and tracing under 'directives' and 'error handling'. The page life cycle
phases are:
Initialization
Instantiation of the controls on the page
Restoration and maintenance of the state
Execution of the event handler codes
Page rendering

Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the page
life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with
view-state data and run control behavior code. Following are the different stages of an ASP.Net page:
Page request: when ASP.Net gets a page request, it decides whether to parse and compile the page or there
would be a cached version of the page; accordingly the response is sent
Starting of page life cycle: at this stage, the Request and Response objects are set. If the request is an old
request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is
also set.
Page initialization: at this stage, the controls on the page are assigned unique ID by setting the UniqueID
property and themes are applied. For a new request postback data is loaded and the control properties are
restored to the view-state values.
Page load: at this stage, control properties are set using the view state and control state values.
Validation: Validate method of the validation control is called and if it runs successfully, the IsValid property
of the page is set to true.
Postback event handling: if the request is a postback (old request), the related event handler is called.
Page rendering: at this stage, view state for the page and all controls are saved. The page calls the Render
method for each control and the output of rendering is written to the OutputStream class of the Page's
Response property.
Unload: the rendered page is sent to the client and page properties, such as Response and Request are
unloaded and all cleanup done.

ASP.Net Page Life Cycle Events: At each stage of the page life cycle, the page raises some events, which could be
coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes like
Onclick or handle. Following are the page life cycle events:
PreInit: PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether
the page is a postback. It sets the themes and master pages, creates dynamic controls and gets and sets
profile property values. This event can be handled by overloading the OnPreInit method or creating a
Page_PreInit handler.
Init: Init event initializes the control property and the control tree is built. This event can be handled by
overloading the OnInit method or creating a Page_Init handler.
InitComplete: InitComplete event allows tracking of view state. All the controls turn on view-state tracking.
LoadViewState: LoadViewState event allows loading view state information into the controls.
Web Technologies 25

LoadPostData: during this phase, the contents of all the input fields defined with the <form> tag are
processed.
PreLoad: PreLoad occurs before the post back data is loaded in the controls. This event can be handled by
overloading the OnPreLoad method or creating a Page_PreLoad handler.
Load: the Load event is raised for the page first and then recursively for all child controls. The controls in the
control tree are created. This event can be handled by overloading the OnLoad method or creating a
Page_Load handler.
LoadComplete: the loading process is completed, control event handlers are run and page validation takes
place. This event can be handled by overloading the OnLoadComplete method or creating a
Page_LoadComplete handler.
PreRender: the PreRender event occurs just before the output is rendered. By handling this event, pages and
controls can perform any updates before the output is rendered.
PreRenderComplete: as the PreRender event is recursively fired for all child controls, this event ensures the
completion of the pre-rendering phase.
SaveStateComplete: state of control on the page is saved. Personalization, control state and view state
information is saved. The HTML markup is generated. This stage can be handled by overriding the Render
method or creating a Page_Render handler.
UnLoad: the UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls
recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as
database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating
a Page_UnLoad handler.

Page: An ASP.Net page is also a server side file saved with the .aspx extension. It is modular in nature and can be
divided into the following core sections:
Page directives
Code Section
Page Layout

Page directives: The page directives set up the environments for the page to run. The @Page directive defines page-
specific attributes used by the ASP.Net page parser and compiler. Page directives specify how the page should be
processed, and which assumptions are to be taken about the page. It allows importing namespaces, loading
assemblies and registering new controls with custom tag names and namespace prefixes. We will discuss all of these
concepts in due time.
The Application Directive: The Application directive defines application-specific attributes. It is provided at
the top of the global.aspx file. ( %@ Application Language="C#" %> )
The Assembly Directive: The Assembly directive links an assembly to the page or the application at parse
time. This could appear either in the global.asax file for application-wide linking or in the page file or a user
control file for linking to a page or user control. ( <%@ Assembly Name ="myassembly" %> )
The Control Directive: The Control directive is used with the user controls and appears in the user control
(.ascx) files. ( <%@ Control Language="C#" EnableViewState="false" %> )
The Implements Directive: The Implement directive indicates that the web page, master page or user
control page must implement the specified .Net framework interface. ( <%@ Implements
Interface="interface_name" %> )
The Import Directive: The Import directive imports a namespace into a web page, user control pate of
application. If the Import directive is specified in the global.asax, then it will apply to the entire application. If
it is in a page of user control page, then it would apply to that page or control. ( <%@
namespace="System.Drawing" %> )
Web Technologies 26

The Master Directive: The Master directive specifies a page file as being the mater page. ( <%@ MasterPage
Language="C#" AutoEventWireup="true" CodeFile="SiteMater.master.cs" Inherits="SiteMaster" %> )
The MasterType Directive: The MasterType directive assigns a class name to the Master property of a page,
to make it strongly typed. ( <%@ MasterType attribute="value"[attribute="value" ...] %> )
The OutputCache Directive: The OutputCache directive controls the output caching policies of a web page or
a user control. We will discuss this directive in details, in data caching. ( <%@ OutputCache Duration="15"
VaryByParam="None" %> )
The Page Directive: The Page directive defines the attributes specific to the page file for the page parser and
the compiler. ( <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" Trace="true" %> )
The PreviousPageType Directive: The PreviousPageType directive assigns a class to a page, so that the page
is strongly typed. ( <%@ PreviousPageType attribute="value"[attribute="value" ...] %> )
The Reference Directive: The Reference directive indicates that another page or user control should be
compiled and linked to the current page. ( <%@ Reference Page ="somepage.aspx" %> )
The Register Directive: The Register derivative is used for registering the custom server controls and user
controls. ( <%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %> )

Code Section: The code section provides the handlers for the page and control events along with other functions
required. We mentioned that, ASP.Net follows an object model. Now, these objects raises events when something
happens on the user interface, like a user clicks a button or moves the cursor. How these events should be handled?
That code is provided in the event handlers of the controls, which are nothing but functions bound to the controls.
The code section or the code behind file provides all these event handler routines, and other functions used by the
developer. The page code could be precompiled and deployed in the form of a binary assembly.

Page Layout: The page layout provides the interface of the page. It contains the server controls, text, inline
JavaScript and HTML tags.

Server Controls: Server controls are tags that are understood by the server. There are three kinds of server controls:
HTML Server Controls - Traditional HTML tags
Web Server Controls - New ASP.NET tags
Validation Server Controls - For input validation

HTML Server Controls: HTML server controls are HTML tags understood by the server. HTML elements in ASP.NET
files are, by default, treated as text. To make these elements programmable, add a runat="server" attribute to the
HTML element. This attribute indicates that the element should be treated as a server control. The id attribute is
added to identify the server control. The id reference can be used to manipulate the server control at run time.

Example of HTML server control


<script runat="server">
Sub Page_Load
link1.HRef="http://www.w3schools.com"
End Sub
</script>
<html>
<body>
<form runat="server">
<a id="link1" runat="server">Visit W3Schools!</a>
</form>
Web Technologies 27

</body>
</html>

HtmlAnchor: Controls an <a> HTML element


HtmlButton: Controls a <button> HTML element
HtmlForm: Controls a <form> HTML element
HtmlGeneric: Controls other HTML element not specified by a specific HTML server control, like <body>,
<div>, <span>, etc.
HtmlImage: Controls an <image> HTML element
HtmlInputButton: Controls <input type="button">, <input type="submit">, and <input type="reset"> HTML
elements
HtmlInputCheckBox: Controls an <input type="checkbox"> HTML element
HtmlInputFile: Controls an <input type="file"> HTML element
HtmlInputHidden: Controls an <input type="hidden"> HTML element
HtmlInputImage: Controls an <input type="image"> HTML element
HtmlInputRadioButton: Controls an <input type="radio"> HTML element
HtmlInputText: Controls <input type="text"> and <input type="password"> HTML elements
HtmlSelect: Controls a <select> HTML element
HtmlTable: Controls a <table> HTML element
HtmlTableCell: Controls <td>and <th> HTML elements
HtmlTableRow: Controls a <tr> HTML element
HtmlTextArea: Controls a <textarea> HTML element

Web Server Controls: Web server controls are special ASP.NET tags understood by the server. Like HTML server
controls, Web server controls are also created on the server and they require a runat="server" attribute to work.
However, Web server controls do not necessarily map to any existing HTML elements and they may represent more
complex elements. The syntax for creating a Web server control is:

<asp:control_name id="some_id" runat="server" />

Example of Web Server Control


<script runat="server">
Sub submit(Source As Object, e As EventArgs)
button1.Text="You clicked me!"
End Sub
</script>
<html>
<body>
<form runat="server">
<asp:Button id="button1" Text="Click me!"
runat="server" OnClick="submit"/>
</form>
</body>
</html>

AdRotator: Displays a sequence of images


Button: Displays a push button
Calendar: Displays a calendar
Web Technologies 28

CalendarDay: A day in a calendar control


CheckBox: Displays a check box
CheckBoxList: Creates a multi-selection check box group
DataGrid: Displays fields of a data source in a grid
DataList: Displays items from a data source by using templates
DropDownList: Creates a drop-down list
HyperLink: Creates a hyperlink
Image: Displays an image
ImageButton: Displays a clickable image
Label: Displays static content which is programmable (lets you apply styles to its content)
LinkButton: Creates a hyperlink button
ListBox: Creates a single- or multi-selection drop-down list
ListItem: Creates an item in a list
Literal: Displays static content which is programmable(does not let you apply styles to its content)
Panel: Provides a container for other controls
PlaceHolder: Reserves space for controls added by code
RadioButton: Creates a radio button
RadioButtonList: Creates a group of radio buttons
BulletedList: Creates a list in bullet format
Repeater: Displays a repeated list of items bound to the control
Style: Sets the style of controls
Table: Creates a table
TableCell: Creates a table cell
TableRow: Creates a table row
TextBox: Creates a text box
Xml: Displays an XML file or the results of an XSL transform

Validation Server Controls: Validation server controls are used to validate user-input. If the user-input does not pass
validation, it will display an error message to the user. Each validation control performs a specific type of validation
(like validating against a specific value or a range of values). By default, page validation is performed when a Button,
ImageButton, or LinkButton control is clicked. You can prevent validation when a button control is clicked by setting
the CausesValidation property to false. The syntax for creating a Validation server control is:

<asp:control_name id="some_id" runat="server" />

Why we use validation controls: Validation is important part of any web application. User's input must always be
validated before sending across different layers of the application. Validation controls are used to:
Implement presentation logic.
To validate user input data.
Data format, data type and data range is used for validation.

Validation is of two types:


Client Side
Serve Side

Client side validation is good but we have to be dependent on browser and scripting language support. Client side
validation is considered convenient for users as they get instant feedback. The main advantage is that it prevents a
page from being postback to the server until the client validation is executed successfully. For developer point of
Web Technologies 29

view serve side is preferable because it will not fail, it is not dependent on browser and scripting language. You can
use ASP.NET validation, which will ensure client, and server validation. It work on both end; first it will work on client
validation and then on server validation. At any cost server validation will work always whether client validation is
executed or not. So you have a safety of validation check. For client script .NET used JavaScript. WebUIValidation.js
file is used for client validation by .NET

Validation Properties: Usually, Validation is invoked in response to user actions like clicking submit button or
entering data. Suppose, you wish to perform validation on page when user clicks submit button. Server validation
will only performed when CauseValidation is set to true. When the value of the CausesValidation property is set to
true, you can also use the ValidationGroup property to specify the name of the validation group for which the Button
control causes validation. Page has a Validate() method. If it is true this methods is executed. Validate() executes
each validation control. To make this happen, simply set the CauseValidation property to true for submit button as
shown below:

<asp:Button ID="Button2" runat="server" Text="Submit" CausesValidation=true />

Example of Validation server control


<html>
<body>
<form runat="server">
<p>Enter a number from 1 to 100:
<asp:TextBox id="tbox1" runat="server" />
<br /><br />
<asp:Button Text="Submit" runat="server" />
</p>
<p>
<asp:RangeValidator
ControlToValidate="tbox1"
MinimumValue="1"
MaximumValue="100"
Type="Integer"
Text="The value must be from 1 to 100!"
runat="server" />
</p>
</form>
</body>
</html>

CompareValidator: Compares the value of one input control to the value of another input control or to a
fixed value
CustomValidator: Allows you to write a method to handle the validation of the value entered
RangeValidator: Checks that the user enters a value that falls between two values
RegularExpressionValidator: Ensures that the value of an input control matches a specified pattern
RequiredFieldValidator: Makes an input control a required field
ValidationSummary: Displays a report of all validation errors occurred in a Web page

RequiredFieldValidator (<asp:RequiredFieldValidator>): Checks that the validated control contains a value. It


cannot be empty. Can be used in conjunction with other validators on a control to trap empty values. Simply, we can
Web Technologies 30

use it to check if the input control has any value. The most important property in the RequiredFieldValidator is
InitialValue.

<asp:RequiredFieldValidator id="validTxtName runat="server" controlToValidate="txtName" errorMessage="Name


must be entered" display="static"></asp:RequiredFieldValidator>

RegularExpressionValidator (<asp:RegularExpressionValidator>): Checks the value against a regular expression


(pattern). Checks that the value in the control matches a specified regular expression. If the validated control is
empty, no validation takes place. The most important property in the RegularExpressionValidator is
ValidationExpression.

<asp:RegularExpressionValidator id="regvH" runat="server" display="static" controlToValidate="txtH"


errorMessage="Hours must be 1-3 digits only" validationExpression="\d{1,3}"></asp:RegularExpressionValidator>

CompareValidator (<asp:CompareValidator>): Checks if the value is acceptable compared to a given value or


compared to the content of another control. In other words, it checks that the value in the validated control matches
the value in another control or a specific value. The data type and comparison operation can be specified. If the
validated control is empty, no validation takes place. The most important properties in the CompareValidator are
ValueToCompare, ControlToCompare, Operator, and type.

<asp:CompareValidator id="comvR" runat="server" display="static" controlToValidate="txtR" errorMessage="Rate


must be numeric" type="Double" operator="DataTypeCheck"></asp:CompareValidator>

RangeValidator (<asp:RangeValidator>): Checks if the input controls value is within a specified range. In other
words, it checks that the value in the validated control is within the specified text or numeric range. If the validated
control is empty, no validation takes place. The most important properties in the RangeValidator are
MaximumValue, MinimumValue, and type.

<asp:RangeValidator id="ranvDependents" runat="server" display="static" controlToValidate="txtDependents"


errorMessage="Must be from 0 to 10" type="Integer" minimumValue=0 maximumValue=10></asp:RangeValidator>

CustomValidator (<asp:CustomValidator>): Allows you to develop custom validation. Performs user-defined


validation on an input control using a specified function (client-side, server-side, or both). If the validated control is
empty, no validation takes place. The most important property in the CustomValidator is ClientValidationFunction.

<asp:CustomValidator id="cusvDeptNum" runat="server" display="static" controlToValidate="txtDeptNum"


onServerValidate="validateDeptNum" errorMessage="Must be in multiples of 10" ></asp:CustomValidator>

ValidationSummary (<asp:ValidationSummary>): Displays a summary of all current validation errors. In other


words, reports a summary of all errors. The most important properties in the ValidationSummary are DisplayMode,
ShowHeaderText, ShowMessageBox, and ShowSummary.

<asp:ValidationSummary id="valSummary" runat="server" headerText="Please correct the following errors"


display="static" showSummary= "True" />

The Page_Load Event: The Page_Load event is one of many events that ASP.NET understands. The Page_Load event
is triggered when a page loads, and ASP.NET will automatically call the subroutine Page_Load, and execute the code
inside it:
Web Technologies 31

Example of Page_Load Event


<script runat="server">
Sub Page_Load
lbl1.Text="The date and time is " & now()
End Sub
</script>
<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
</form>
</body>
</html>

The Page.IsPostBack Property: The Page_Load subroutine runs EVERY time the page is loaded. If you want to
execute the code in the Page_Load subroutine only the FIRST time the page is loaded, you can use the
Page.IsPostBack property. If the Page.IsPostBack property is false, the page is loaded for the first time, if it is true,
the page is posted back to the server (i.e. from a button click on a form):

Example of Page.IsPostBack Property


<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
lbl1.Text="The date and time is " & now()
end if
End Sub
Sub submit(s As Object, e As EventArgs)
lbl2.Text="Hello World!"
End Sub
</script>
<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
<h3><asp:label id="lbl2" runat="server" /></h3>
<asp:button text="Submit" onclick="submit" runat="server" />
</form>
</body>
</html>

Session: When a user connects to an ASP.Net website, a new session object is created. When session state is turned
on, a new session state object is created for each new request. This session state object becomes part of the context
and it is available through the page. Session state is generally used for storing application data like inventory or
supplier list, or a customer record or shopping cart. It can also keep information about the user and his preference
and keep track of pending operations. Sessions are identified and tracked with a 120-bit SessionID, which is passed
from client to server and back as cookie or a modified URL. The SessionID is globally unique and random. The session
Web Technologies 32

state object is created from the HttpSessionState class, which defines a collection of session state items. The
HttpSessionState class has the following properties:
SessionID: The unique session identifier
Item(name): The value of the session state item with the specified name. This is the default property of the
HttpSessionState class
Count: The number of items in the session state collection
TimeOut: Gets and sets the amount of time, in minutes, allowed between requests before the session-state
provider terminates the session.

The HttpSessionState class has the following methods:


Add(name, value): Adds an item to the session state collection
Clear: Removes all the items from session state collection
Remove(name): Removes the specified item from the session state collection
RemoveAll: Removes all keys and values from the session-state collection.
RemoveAt: Deletes an item at a specified index from the session-state collection.

Introduction to ADO.net: ADO.NET (ActiveX Data Objects for .NET) is a set of computer software components that
programmers can use to access data and data services. It is a part of the base class library that is included with the
Microsoft .NET Framework. It is commonly used by programmers to access and modify data stored in relational
database systems, though it can also access data in non-relational sources. ADO.NET is sometimes considered an
evolution of ActiveX Data Objects (ADO) technology, but was changed so extensively that it can be considered an
entirely new product.

Architecture of ADO.NET: ADO.NET is conceptually divided into consumers and data providers. The consumers are
the applications that need access to the data, and the providers are the software components that implement the
interface and thereby provide the data to the consumer.

ADO.NET Components: The ADO.NET components have been designed to factor data access from data
manipulation. There are two central components of ADO.NET that accomplish this: the DataSet, and the .NET
Framework data provider, which is a set of components including the Connection, Command, DataReader, and
DataAdapter objects.

The ADO.NET DataSet is the core component of the disconnected architecture of ADO.NET. The DataSet is explicitly
designed for data access independent of any data source. As a result it can be used with multiple and differing data
sources, used with XML data, or used to manage data local to the application. The DataSet contains a collection of
one or more DataTable objects made up of rows and columns of data, as well as primary key, foreign key, constraint,
and relation information about the data in the DataTable objects.

The other core element of the ADO.NET architecture is the .NET Framework data provider, whose components are
explicitly designed for data manipulation and fast, forward-only, read-only access to data. The Connection object
provides connectivity to a data source. The Command object enables access to database commands to return data,
modify data, run stored procedures, and send or retrieve parameter information. The DataReader provides a high-
performance stream of data from the data source. Finally, the DataAdapter provides the bridge between the DataSet
object and the data source. The DataAdapter uses Command objects to execute SQL commands at the data source
to both load the DataSet with data, and reconcile changes made to the data in the DataSet back to the data source.
Web Technologies 33

A .NET Framework data provider is used for connecting to a database, executing commands, and retrieving results.
Those results are either processed directly, or placed in an ADO.NET DataSet in order to be exposed to the user in an
ad-hoc manner, combined with data from multiple sources, or remoted between tiers. The .NET Framework data
provider is designed to be lightweight, creating a minimal layer between the data source and your code, increasing
performance without sacrificing functionality. The following are the four core objects that make up a .NET
Framework data provider.
Connection: Establishes a connection to a specific data source.
Command: Executes a command against a data source. Exposes Parameters and can execute within the
scope of a Transaction from a Connection.
DataReader: Reads a forward-only, read-only stream of data from a data source.
DataAdapter: Populates a DataSet and resolves updates with the data source.

The DataSet object is central to supporting disconnected, distributed data scenarios with ADO.NET. The DataSet is a
memory-resident representation of data that provides a consistent relational programming model regardless of the
data source. It can be used with multiple and differing data sources, used with XML data, or used to manage data
local to the application. The DataSet represents a complete set of data including related tables, constraints, and
relationships among the tables. The following illustration shows the DataSet object model.

Data object model: The methods and objects in a DataSet are consistent with those in the relational database
model. The DataSet can also persist and reload its contents as XML and its schema as XML Schema definition
language (XSD) schema.

The DataTableCollection: An ADO.NET DataSet contains a collection of zero or more tables represented by
DataTable objects. The DataTableCollection contains all the DataTable objects in a DataSet. A DataTable is defined in
the System.Data namespace and represents a single table of memory-resident data. It contains a collection of
columns represented by a DataColumnCollection, and constraints represented by a ConstraintCollection, which
together define the schema of the table. A DataTable also contains a collection of rows represented by the
DataRowCollection, which contains the data in the table. Along with its current state, a DataRow retains both its
current and original versions to identify changes to the values stored in the row.

The DataRelationCollection: A DataSet contains relationships in its DataRelationCollection object. A relationship,


represented by the DataRelation object, associates rows in one DataTable with rows in another DataTable. It is
Web Technologies 34

analogous to a join path that might exist between primary and foreign key columns in a relational database. A
DataRelation identifies matching columns in two tables of a DataSet.

Relationships enable navigation from one table to another within a DataSet. The essential elements of a
DataRelation are the name of the relationship, the name of the tables being related, and the related columns in each
table. Relationships can be built with more than one column per table by specifying an array of DataColumn objects
as the key columns. When a relationship is added to the DataRelationCollection, it may optionally add a
UniqueKeyConstraint and a ForeignKeyConstraint to enforce integrity constraints when changes are made to related
column values.

ExtendedProperties: The DataSet (as well as the DataTable and DataColumn) has an ExtendedProperties property.
ExtendedProperties is a PropertyCollection where you can place customized information, such as the SELECT
statement that was used to generate the resultset, or a date/time stamp of when the data was generated. The
ExtendedProperties collection is persisted with the schema information for the DataSet (as well as the DataTable and
DataColumn).

Database connectivity: The database connectivity in C# is done through ADO.net. ADO.NET (ActiveX Data Object for
.NET) is a set of computer software components that programmers can use to access data and data services.

Basic Components of ADO.net are


SqlConnection
SqlDataReader
SqlCommand

SqlConnection: The SqlConnection class provides all the properties and methods needed to make a connection to a
Microsoft SQL database.

Properties
ConnectionString: Contains the database connection string
DataSource: Contains the name of the connected server
Methods
Close(): Closes the connection to the current database
Open(): Opens the connection to the database

SqlCommand: The SqlCommand class is at the heart of the System.SqlClient namespace. It is used to execute
operations on a database and retrieve data.

Properties
CommandText: Contains the text of a SQL query
Connection: Specifies the connection to the database.

Methods
ExecuteNonQuery(): Executes the CommandText property against the database and does not return a result
set.
ExecuteReader(): Executes the CommandText property and returns data in a DataReader object.
Cancel(): Cancels the running query.
Web Technologies 35

SqlDataReader: The SqlDataReader class defines a lightweight yet powerful object that is used to read information
from a SQL database. A SqlDataReader object has a small footprint, because it doesn't contain more than a single
record in memory at any time. This makes it ideal for reading large amounts of data from a database.

Methods
Read(): Reads the next result in the result set into memory
Close(): Closes the SqlDataReader object

Simple Data Binding: Simple data binding involves the read-only selection lists. These controls can bind to an array
list or fields from a database. Selection lists takes two values from the database or the data source; one value is
displayed by the list and the other is considered as the value corresponding to the display. Let us take up a small
example to understand the concept. Create a web site with a bulleted list and a SqlDataSource control on it.
Configure the data source control to retrieve two values from your database. Choosing a data source for the bulleted
list control involves:
Selecting the data source control
Selecting a field to display, which is called the data field
Selecting a field for the value
When the application is run, check that the entire title column is bound to the bulleted list and displayed.

Declarative Data Binding: We have already used declarative data binding in the previous tutorial using GridView
control. The other composite data bound controls capable of displaying and manipulating data in a tabular manner
are the DetailsView, FormView and RecordList control. However, the data binding involves the following objects:
A dataset that stores the data retrieved from the database
The data provider, which retrieves data from the database, using a command over a connection
The data adapter that issues the select statement stored in the command object; it is also capable of update
the data in a database by issuing Insert, Delete, and Update statements.
Relation between the data binding objects:

Error handling in ASP.Net has three aspects:


Tracing: tracing the program execution at page level or application level.
Error handling: handling standard errors or custom errors at page level or application level
Debugging: stepping through the program, setting break points to analyze the code

Although ASP.Net can detect all runtime errors, still some subtle errors may still be there. Observing the errors by
tracing is meant for the developers, not for the users. Hence, to intercept such occurrence, you can add error
Web Technologies 36

handing settings in the web.config file of the application. It is application wide error handling. For example, you can
add the following lines in the web.config file:
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
</system.web>
<configuration>

The <customErrors> section has the possible attributes:


Mode: It enables or disables custom error pages. It has the three possible values:
On: displays the custom pages.
Off: displays ASP.Net error pages (yellow pages)
remoteOnly: displays custom errors to client, display ASP.Net errors locally
defaultRedirect: It contains the URL of the page to be displayed in case of unhandled errors.

To put different custom error pages for different type of errors, the <error> sub tags are used, where different error
pages are specified, based on the status code of the errors. To implement page level error handling, the Page
directive could be modified:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"


Inherits="errorhandling._Default" Trace ="true" ErrorPage="PageError.htm" %>

Datalist Control: DataList is a data bound list control that displays items using certain templates defined at the
design time. The content of the DataList control is manipulated by using templates sections such as
AlternatingItemTemplate, EditItemTemplate, FooterTemplate, HeaderTemplate, ItemTemplate,
SelectedItemTemplate and SeparatorTemplate. Each of these sections has its own characteristics to be defined but
at a very minimum, the ItemTemplate needs to be defined to display the items in the DataList control. Other sections
can be used to provide additional look and feel to the DataList control.The contents of the DataList control can be
manipulated by using templates. The following table lists the supported templates.
AlternatingItemTemplate: If defined, provides the content and layout for alternating items in the DataList. If
not defined, ItemTemplate is used.
EditItemTemplate: If defined, provides the content and layout for the item currently being edited in the
DataList. If not defined, ItemTemplate is used.
FooterTemplate: If defined, provides the content and layout for the footer section of the DataList. If not
defined, a footer section will not be displayed.
HeaderTemplate: If defined, provides the content and layout for the header section of the DataList. If not
defined, a header section will not be displayed.
ItemTemplate: Required template that provides the content and layout for items in the DataList.
SelectedItemTemplate: If defined, provides the content and layout for the currently selected item in the
DataList. If not defined, ItemTemplate is used.
SeparatorTemplate: If defined, provides the content and layout for the separator between items in the
DataList. If not defined, a separator will not be displayed.

At the very minimum, the ItemTemplate needs to be defined to display the items in the DataList control. Additional
templates can be used to provide a custom look to the DataList control. The appearance of the DataList control may
Web Technologies 37

be customized by setting the style properties for the different parts of the control. The following table lists the
different style properties.
AlternatingItemStyle: Specifies the style for alternating items in the DataList control.
EditItemStyle: Specifies the style for the item being edited in the DataList control.
FooterStyle: Specifies the style for the footer in the DataList control.
HeaderStyle: Specifies the style for the header in the DataList control.
ItemStyle: Specifies the style for the items in the DataList control.
SelectedItemStyle: Specifies the style for the selected item in the DataList control.
SeparatorStyle: Specifies the style for the separator between the items in the DataList control.

You can also show or hide different parts of the control. The following table lists the properties that control which
parts are shown or hidden.
ShowFooter: Shows or hides the footer section of the DataList control.
ShowHeader: Shows or hides the header section of the DataList control.

The display direction of a DataList control can be vertical or horizontal. Set the RepeatDirection property to specify
the display direction. The layout of the DataList control is controlled with the RepeatLayout property. Setting this
property to RepeatLayout.Table will display the DataList in a table format, while RepeatLayout.Flow displays the
DataList without a table structure.

<asp:DataList ID=" dlMyCountry" runat="server">


<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Country_Code") %>'></asp:Label>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Country_Name") %>'></asp:Label>
</ItemTemplate>
</asp:DataList>

Data Caching: Caching is a technique of storing frequently used data/information in memory, so that, when the
same data/information is needed next time, it could be directly retrieved from the memory instead of being
generated by the application. Caching is extremely important for performance boosting in ASP.Net, as the pages and
controls are dynamically generated here. It is especially important for data related transactions, as these are
expensive in terms of response time. Caching places frequently used data in quickly accessed media like the random
access memory of the computer. The ASP.Net runtime includes a key-value map of CLR objects called cache. This
lives with the application and is available via the HttpContext and System.Web.UI.Page. In some respect, caching is
similar to storing the state objects. However, the storing information in state objects is deterministic, i.e., you can
count on the data being stored there, and caching of data is nondeterministic. The data will not be available if its
lifetime expires, or the application releases its memory, or caching does not take place for some reason. You can
access items in the cache using an indexer and may control the lifetime of objects in the cache and set up links
between the cached objects and their physical sources.

Caching in ASP.Net: ASP.Net provides the following different types of caching:


Output Caching: Output cache stores a copy of the finally rendered HTML pages or part of pages sent to the
client. When the next client requests for this page, instead of regenerating the page, a cached copy of the
page is sent, thus saving time.
Data Caching: Data caching means caching data from a data source. As long as the cache is not expired, a
request for the data will be fulfilled from the cache. When the cache is expired, fresh data is obtained by the
data source and the cache is refilled.
Web Technologies 38

Object Caching: Object caching is caching the objects on a page, such as data-bound controls. The cached
data is stored in server memory.
Class Caching: Web pages or web services are compiled into a page class in the assembly, when run for the
first time. Then the assembly is cached in the server. Next time when a request is made for the page or
service, the cached assembly is referred to. When the source code is changed, the CLR recompiles the
assembly.
Configuration Caching: Application wide configuration information is stored in a configuration file.
Configuration caching stores the configuration information in the server memory.

Authentication is the process of obtaining identification credentials such as name and password from a user and
validating those credentials against some authority. If the credentials are valid, the entity that submitted the
credentials is considered an authenticated identity. Once an identity has been authenticated, the authorization
process determines whether that identity has access to a given resource.

Windows Authentication treats the user identity supplied by Microsoft Internet Information Services (IIS) as the
authenticated user in an ASP.NET application. IIS provides a number of authentication mechanisms to verify user
identity, including anonymous authentication, Windows integrated (NTLM) authentication, Windows integrated
(Kerberos) authentication, Basic (base64 encoded) authentication, Digest authentication, and authentication based
on client certificates. Windows Authentication is implemented in ASP.NET using the WindowsAuthenticationModule
module. The module constructs a WindowsIdentity based on the credentials supplied by IIS and sets the identity as
the current User property value for the application. Windows Authentication is the default authentication
mechanism for ASP.NET applications and is identified as the authentication mode for an application using the
authentication configuration element, as shown in the following code example.
<system.web>
<authentication mode="Windows"/>
</system.web>

Forms authentication lets you authenticate users by using your own code and then maintain an authentication
token in a cookie or in the page URL. Forms authentication participates in the ASP.NET page life cycle through the
FormsAuthenticationModule class. You can access forms authentication information and capabilities through the
FormsAuthentication class. To use forms authentication, you create a login page that collects credentials from the
user and that includes code to authenticate the credentials. Typically you configure the application to redirect
requests to the login page when users try to access a protected resource, such as a page that requires
authentication. If the user's credentials are valid, you can call methods of the FormsAuthentication class to redirect
the request back to the originally requested resource with an appropriate authentication ticket (cookie). If you do
not want the redirection, you can just get the forms authentication cookie or set it. On subsequent requests, the
user's browser passes the authentication cookie with the request, which then bypasses the login page. You configure
forms authentication by using the authentication configuration element. In the simplest case, you have a login page.
In the configuration file, you specify a URL to redirect unauthenticated requests to the login page. You then define
valid credentials, either in the Web.config file or in a separate file. The following example shows a section from a
configuration file that specifies a login page and authentication credentials for the Authenticate method. The
passwords have been encrypted by using the HashPasswordForStoringInConfigFile method.
<authentication mode="Forms">
<forms name="SavingsPlan" loginUrl="/Login.aspx">
<credentials passwordFormat="SHA1">
<user name="Kim"
password="07B7F3EE06F278DB966BE960E7CBBD103DF30CA6"/>
<user name="John"
Web Technologies 39

password="BA56E5E0366D003E98EA1C7F04ABF8FCB3753889"/>
</credentials>
</forms>
</authentication>

Encrypting Data over the Network: If you need to send or receive sensitive information at your Web sitesuch as
credit card numbers, business plans, or legal documentsyou need to encrypt the information. In this chapter, you
examine methods for encrypting data before it is sent across an unsecure network such as the Internet.
Using the Secure Sockets Layer: The Secure Sockets Layer (SSL) is a protocol, originally developed by
Netscape, for transmitting information securely across an unsecure network. SSL is the only existing method
for sending private information across the Internet that works with the majority of current browsers. SSL
provides a technical solution to three distinct security problems: encryption, authentication, and data
integrity.
Encryption: When you enter information into an HTML form and submit it at a Web site, the information is
transmitted from your browser to the Web site's server. As the information travels across the Internet, it
typically passes through several intermediate connections. In theory, the data entered into the form can be
intercepted and read.
Using SSL in ASP.NET Pages: After you configure your server to use SSL, you can request any page from your
Web site using a secure connection. To retrieve a Web page using SSL, use an address of the form
https://www.yourdomain.com/page.aspx rather than the normal http://www.yourdomain.com/page.aspx.
This form works for any page at your Web site. You can force users to use SSL when requesting pages from
your Web site. To do so, open the property sheet for a directory or a single page within the Internet Services
Manager and choose the Directory Security or File Security tab. Next, click the Edit button under Secure
Communications and choose Require Secure Channel When Accessing This Resource. If you want to require
128-bit SSL, click the Encryption Settings button and choose Require 128-Bit Encryption.
Using .NET Encryption Classes: The .NET framework includes a rich set of classes for performing
cryptographic operations. You can access any of these classes within an ASP.NET page. In several situations,
you need to use these classes in an ASP.NET application. For example you can use these classes to encrypt
sensitive information, such as credit card numbers and legal documents, before you store the information in
a database table or the file system. You also can use these classes to automatically add digital signatures to
documents.
Web Technologies 40

Introduction to XML: XML stands for Extensible Markup Language. XML is a markup language much like HTML. XML
was designed to carry data, not to display data. XML tags are not predefined. You must define your own tags. XML is
designed to be self-descriptive. Some of the important features of a XML document are
XML can be used to exchange, share, and store data.
XML documents form a tree structure that starts at "the root" and branches to "the leaves".
XML has very simple syntax rules. XML with correct syntax is "Well Formed". Valid XML also validates against
a DTD.
XSLT is used to transform XML into other formats like HTML.
All modern browsers have a built-in XML parser that can read and manipulate XML.
The DOM (Document Object Model) defines a standard way for accessing XML.
The XMLHttpRequest object provides a way to communicate with a server after a web page has loaded.
XML Namespaces provide a method to avoid element name conflicts.
Text inside a CDATA section is ignored by the parser.

The Difference between XML and HTML: All XML Elements Must Have a Closing Tag. XML Tags are Case Sensitive.
XML Elements must be Properly Nested. XML Documents Must Have a Root Element. XML Attribute Values must be
quoted. All modern browsers have a built-in XML parser. An XML parser converts an XML document into an XML
DOM object - which can then be manipulated with JavaScript. XML is not a replacement for HTML. XML and HTML
were designed with different goals. XML was designed to transport and store data, with focus on what data is. HTML
was designed to display data, with focus on how data looks. HTML is about displaying information, while XML is
about carrying information.

Usage of XML
XML Separates Data from HTML
XML Simplifies Data Sharing
XML Simplifies Data Transport
XML Simplifies Platform Changes
XML Makes Your Data More Available
XML is Used to Create New Internet Languages

Example of XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Valid XML Documents


XML Document
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
Web Technologies 41

</note>

XML DTD
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>

XML Schema
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

SOAP is a simple XML-based protocol to let applications exchange information over HTTP. Or more simply: SOAP is a
protocol for accessing a Web Service.
SOAP stands for Simple Object Access Protocol
SOAP is a communication protocol
SOAP is for communication between applications
SOAP is a format for sending messages
SOAP communicates via Internet
SOAP is platform independent
SOAP is language independent
SOAP is based on XML
SOAP is simple and extensible
SOAP allows you to get around firewalls
SOAP is a W3C recommendation

Why SOAP?
It is important for application development to allow Internet communication between programs.
Today's applications communicate using Remote Procedure Calls (RPC) between objects like DCOM and
CORBA, but HTTP was not designed for this. RPC represents a compatibility and security problem; firewalls
and proxy servers will normally block this kind of traffic.
A better way to communicate between applications is over HTTP, because HTTP is supported by all Internet
browsers and servers. SOAP was created to accomplish this.
SOAP provides a way to communicate between applications running on different operating systems, with
different technologies and programming languages.
SOAP Building Blocks: A SOAP message is an ordinary XML document containing the following elements:
Web Tecchnologiess 42

The requiired SOAP En nvelope elem ment is the ro oot element of a SOAP m message. An Envelope
E elemment that
identifies the XML document as a SOAP messagee
A Header element that t containss header infformation. The T optional SOAP Head der element contains
applicatio
on-specific infformation (likke authenticaation, paymen nt, etc) about the SOAP message.
m If th
he Header
element is present, it must
m be the first f child elemment of the Envelope elem ment.
A Body element that contains
c a responsee information. The requireed SOAP Bodyy element contains the
call and
actual SOAP message intended for the ultimatee endpoint off the messagee. Immediatee child elements of the
SOAP Bod dy element may be namespace-qualified.
A Fault element
e conttaining errorss and status information. The optional SOAP Fau ult element is used to
indicate error
e message es. If a Fault element
e is preesent, it mustt appear as a child elemen
nt of the Bodyy element.
A Fault ele
ement can on nly appear on nce in a SOAP message.

ple SOAP message


Samp
<?xmml version="1.0"?>
<soapp:Envelope
xmlns:soap=http:///www.w3.orrg/2001/12/ssoap-envelopee soap:encoding Style=""http://www.w3.org/2001//12/soap-
encoding">
<soa
ap:Header><//soap:Headerr>
<soa
ap:Body>
<soaap:Fault></so
oap:Fault>
</so
oap:Body>
</soaap:Envelope>>

DL
WSD
WSDL stands for Web Services Desccription Langu
uage
WSDL is written
w in XML
WSDL is an
a XML docum ment
WSDL is used
u to descriibe Web services
WSDL is also
a used to lo ocate Web seervices
WSDL is a W3C recomm mendation

The WSDL
W Documment Structure
<types>: The <types> element deefines the data types that are used b by the web service.
s For maximum
platform neutrality,
n W
WSDL uses XML Schema syn ntax to definee data types.
<message e>: The <messsage> elemen nt defines thee data elemen nts of an operation. Each message can consist of
one or more
m parts. The
T parts caan be compaared to the parameters of a function call in a ttraditional
programmming languagee.
Web Technologies 43

<portType> : The <portType> element is the most important WSDL element. It describes a web service,
the operations that can be performed, and the messages that are involved. The <portType> element can be
compared to a function library (or a module, or a class) in a traditional programming language.
<binding>: The <binding> element defines the message format and protocol details for each port.

WSDL Example 1
<definitions>
<types>definition of types</types>
<message>definition of a message</message>
<portType>definition of a port</portType>
<binding>definition of a binding</binding>
</definitions>

WSDL Example 2
<message name="getTermRequest">
<part name="term" type="xs:string"/>
</message>
<message name="getTermResponse">
<part name="value" type="xs:string"/>
</message>
<portType name="glossaryTerms">
<operation name="getTerm">
<input message="getTermRequest"/>
<output message="getTermResponse"/>
</operation>
</portType>

UDDI is a platform-independent framework for describing services, discovering businesses, and integrating business
services by using the Internet.
UDDI stands for Universal Description, Discovery and Integration
UDDI is a directory for storing information about web services
UDDI is a directory of web service interfaces described by WSDL
UDDI communicates via SOAP
UDDI is built into the Microsoft .NET platform

What is UDDI Based On: UDDI uses World Wide Web Consortium (W3C) and Internet Engineering Task Force (IETF)
Internet standards such as XML, HTTP, and DNS protocols. UDDI uses WSDL to describe interfaces to web services.
Additionally, cross platform programming features are addressed by adopting SOAP, known as XML Protocol
messaging specifications found at the W3C Web site.

Benefits: Any industry or businesses of all sizes can benefit from UDDI. Before UDDI, there was no Internet standard
for businesses to reach their customers and partners with information about their products and services. Nor was
there a method of how to integrate into each other's systems and processes. Problems the UDDI specification can
help to solve:
Making it possible to discover the right business from the millions currently online
Defining how to enable commerce once the preferred business is discovered
Reaching new customers and increasing access to current customers
Expanding offerings and extending market reach
Web Technologies 44

Solving customer-driven need to remove barriers to allow for rapid participation in the global Internet
economy
Describing services and business processes programmatically in a single, open, and secure environment

How can UDDI be Used: If the industry published an UDDI standard for flight rate checking and reservation, airlines
could register their services into an UDDI directory. Travel agencies could then search the UDDI directory to find the
airline's reservation interface. When the interface is found, the travel agency can communicate with the service
immediately because it uses a well-defined reservation interface.

Grid and Cloud Computing Study: You might have heard many times about these buzz words Cloud Computing and
Grid Computing by now and you might be really thinking about what is the real difference about these two
technologies. Everyone talks about Cloud nowadays, what actually is cloud and grid? here l discuss about the
similarities and differences between Grid and cloud computing. Both Cloud and Grid computing are Scalable. Cloud
computing evolved from Grid computing. you might have heard about SaaS, IaaS and PaaS. All these buzz words
have a link with cloud and Grid computing. All of them are inter linked. Grid is mostly used for High intensive
computational requirements where as cloud can be used for High CPU usage, High storage and bandwidth etc.

Cloud Computing: Using Cloud Computing, companies can scale upto High capacities immediately without investing
in new infrastructure, training the people or new software licensing. It is more useful for small and medium scale
businesses who wants to outsource their Data Center infrastructure, or some larger companies also prefer if they
want to cut down the costs of building data-centers internally in order to get peak load capacity. In short, consumers
use what they need and pay accordingly. Additional advantages for the consumer are, they no longer has to be at a
computer to use the application. they can access it by using smartphones, PDA or which the medium Cloud supports.
By adopting cloud, consumer does not need to own the infrastructure, software and also consumer doesnt need to
worry about the network maintenance. By choosing this he can reduce the capital expenses, Upfront costs and
operating expenses.

Grid Computing: Grid Computing is the parent of Cloud computing, cloud actually evolves from Grid Computing. Grid
is more useful in provisioning resources on-demand. Some people say Grid computing can also be called Cloud
computing but it depends on what type of users using the Grid, if they are system administrators and integrators,
they bother about how things are maintained in the Cloud and their work is to upgrade, install and virtualise the
servers and applications. Consumers dont care about how things are running at the system end, they simply try to
check whether their application is working or not.
Web Tecchnologiess 45

Grid Computing needs


n a softw
ware to divid
de and farm out into piecces of a proggram as one large system image to
severral thousandss of computers. Major disaadvantage with Grid Comp puting is, if on
ne piece of so
oftware on a node
n fails,
other pieces of th
he software ono the other nodes may fail.
f It can bee rectified by installing a failover
f comp
ponent on
other nodes, but when some components
c depend on o
other compon nents the sam m arise. To Build and
me problem may
Manaage a Grid yo
ou may incur huge
h capital and
a operation nal expenses..

Some e of the con ncerns i still have with Clloud and Griid computingg are: Securitty, Privacy, Network
N latency when
integgrating with in
n-house sytem ms or during peak loads and hidden co osts etc. Thou
ugh scalabilityy is the commmon factor
betwween the Grid d and Cloud Computing and a scalabilitty can be ach hieved by using load balaancing techniques and
connecting appliccation througgh web serviice but Scalaability in Grid d is, for a co
ompany who o wants to scale
s their
comp putational ressources and scalability
s in cloud
c is, for a consumer who
w wants to scale
s their ap
pplication reso ources.

A Seervice-Oriente ed Architecture (SOA) iss a set of prrinciples and d methodologgies for desiigning and developing
d
softw
ware in the foorm of interoperable services. These seervices are weell-defined bu usiness functionalities that are built
as so
oftware comp ponents (discrrete pieces of code and/o or data structures) that can be reused forf different purposes.
SOA design principles are used d during the phases
p of systtems develop pment and integration. SO OA generally provides
p a
way for consumeers of services, such as we eb-based app plications, to be aware off available SOOA-based serrvices. For
exammple, several disparate departments within a com mpany may develop and d deploy SOA A services in different
impleementation laanguages; their respectivee clients will benefit from a well-defineed interface to t access them. XML is
often
n used for in nterfacing with SOA servvices, though h this is not required. JSSON is also becoming increasingly
comm mon. SOA deefines how to t integrate widely dispaarate applicattions for a W Web-based environment
e and uses
multiple impleme entation platfo orms. Ratherr than defining an API, SOA A defines the interface in terms
t of prottocols and
functtionality. An endpoint is the entry po oint for suchh a SOA impllementation. Service-orientation requires loose
couppling of services with opeerating systeems, and oth her technologgies that und derlie applications. SOA separates
functtions into disttinct units, orr services, wh
hich developeers make acceessible over a network in order
o to allow
w users to
comb bine and reu use them in the productiion of appliccations. These services an nd their corrresponding cconsumers
comm municate witth each othe er by passingg data in a w well-defined, shared form mat, or by co oordinating ana activity
betwween two or more
m servicess. SOA can be e seen in a co
ontinuum, fro om older concepts of distrributed comp puting and
modu ular programmming, througgh SOA, and on to curren nt practices ofo mashups, SaaS, and clo oud computing (which
somee see as the offspring
o of SOOA).