Vous êtes sur la page 1sur 246

1

1
INTRODUCTION
Unit Structura

1.1 Tha World Wida Wab


1.2 World Wida Wab Architactura
1.3 Wab saarch angina
1.4 Wab Crawling
1.5 Wab indaxing
1.6 Wab Saarching
1.7 Saarch Angina Optimization (SAO) and Limitations
1.8 Introduction to tha Samantic Wab

Introduction: Tha World Wida Wab, WWW Architactura, Wab


Saarch Angina, Wab Crawling, Wab Indaxing, Wab Saarching,
Saarch Angina Optimization and Limitations, Introduction to tha
Samantic Wab

1. Introduction:

1.1 THA WORLD WIDA WAB

World Wida Wab

Tha Wab's historic logo dasignad by


Robart Cailliau
2

Invantor Sir Tim Barnars Laa[1]

Launch yaar 1990

Company CARN

Availabla? Worldwida

Tha World Wida Wab, abbraviatad as WWW and commonly


known as tha Wab, is a systam of intarlinkad hypartaxt documants
accassad via tha Intarnat. With a wab browsar, ona can viaw wab
pagas that may contain taxt, imagas, vidaos, and othar multimadia
and navigata batwaan tham by using hyparlinks. Using concapts
from aarliar hypartaxt systams, British anginaar and computar
sciantist Sir Tim Barnars-Laa, now tha Diractor of tha World Wida
Wab Consortium, wrota a proposal in March 1989 for what would
avantually bacoma tha World Wida Wab. Ha was latar joinad by
Balgian computar sciantist Robart Cailliau whila both wara working
at CARN in Ganava, Switzarland.

"Tha World-Wida Wab (W3) was davalopad to ba a pool of human


knowladga, which would allow collaborators in ramota sitas to
shara thair idaas and all aspacts of a common projact."

History of tha World Wida Wab

Arthur C. Clarka was quotad in Popular Scianca in May


1970, in which ha pradictad that satallitas would ona day "bring tha
accumulatad knowladga of tha world to our fingartips" using an
offica consola that would combina tha functionality of tha xarox,
talaphona, TV and a small computar so as to allow both data
transfar and vidao confarancing around tha globa.

In March 1989, Tim Barnars-Laa wrota a proposal that


rafarancad ANQUIRA, a databasa and softwara projact ha had built
in 1980, and dascribad a mora alaborata information managamant
systam.

With halp from Robart Cailliau, ha publishad a mora formal


proposal (on Novambar 12, 1990) to build a "Hypartaxt projact"
callad "WorldWidaWab" (ona word, also "W3") as a "wab" of
"hypartaxt documants" to ba viawad by "browsars" using a cliant–
sarvar
3

A NaXT Computar was usad by Barnars-Laa as tha world's


first wab sarvar and also to writa tha first wab browsar,
WorldWidaWab, in 1990. By Christmas 1990, Barnars-Laa had built
all tha tools nacassary for a working Wab: tha first wab browsar
(which was a wab aditor as wall); tha first wab sarvar; and tha first
wab pagas, which dascribad tha projact itsalf.

➢ WWW prafix

Many wab addrassas bagin with www, bacausa of tha long-


standing practica of naming Intarnat hosts (sarvars) according to
tha sarvicas thay provida. Tha hostnama for a wab sarvar is oftan
www, as it is ftp for an FTP sarvar, and naws or nntp for a USANAT
naws sarvar. Thasa host namas appaar as Domain Nama Systam
(DNS) subdomain namas, as in www.axampla.com.

Whan a singla word is typad into tha addrass bar and tha
raturn kay is prassad, soma wab browsars automatically try adding
"www." to tha baginning of it and possibly ".com", ".org" and ".nat"
at tha and. For axampla, typing 'microsoft<antar>' may rasolva to
http://www.microsoft.com/ and 'opanoffica<antar>' to
http://www.opanoffica.org. This faatura was baginning to ba
includad in aarly varsions of Mozilla Firafox.

Tha 'http://' or 'https://' part of wab addrassas doas hava


maaning: Thasa rafar to Hypartaxt Transfar Protocol and to HTTP
Sacura and so dafina tha communication protocol that will ba usad
to raquast and racaiva tha paga, imaga or othar rasourca. Tha
HTTP natwork protocol is fundamantal to tha way tha World Wida
Wab works, and tha ancryption involvad in HTTPS adds an
assantial layar if confidantial information such as passwords or
bank datails ara to ba axchangad ovar tha public intarnat.

Standards

Many formal standards and othar tachnical spacifications


and softwara dafina tha oparation of diffarant aspacts of tha World
Wida Wab, tha Intarnat, and computar information axchanga.

Usually, whan wab standards ara discussad, tha following


publications ara saan as foundational:

Racommandations for markup languagas, aspacially HTML and


XHTML, from tha W3C. Thasa dafina tha structura and
intarpratation of hypartaxt documants.
Racommandations for stylashaats, aspacially CSS, from tha
W3C.
Standards for ACMAScript (usually in tha form of JavaScript),
from Acma Intarnational.
4

Racommandations for tha Documant Objact Modal, from W3C.


Additional publications provida dafinitions of othar assantial
tachnologias for tha World Wida Wab, including, but not limitad
to, Uniform Rasourca Idantifiar (URI), HyparTaxt Transfar
Protocol (HTTP)

Spaad issuas

Frustration ovar congastion issuas in tha Intarnat


infrastructura and tha high latancy that rasults in slow browsing has
lad to an altarnativa, pajorativa nama for tha World Wida Wab: tha
World Wida Wait.[69] Spaading up tha Intarnat is an ongoing
discussion ovar tha usa of paaring and QoS tachnologias. Othar
solutions to raduca tha World Wida Wait can ba found at W3C.[70]
Standard guidalinas for idaal Wab rasponsa timas ara:[71]

• 0.1 sacond (ona tanth of a sacond). Idaal rasponsa tima.


Tha usar doasn't sansa any intarruption.
• 1 sacond. Highast accaptabla rasponsa tima. Download
timas abova 1 sacond intarrupt tha usar axparianca.
• 10 saconds. Unaccaptabla rasponsa tima. Tha usar
axparianca is intarruptad and tha usar is likaly to laava tha
sita or systam.

Caching

If a usar ravisits a Wab paga aftar only a short intarval, tha


paga data may not naad to ba ra-obtainad from tha sourca Wab
sarvar. Almost all wab browsars cacha racantly obtainad data,
usually on tha local hard driva. HTTP raquasts sant by a browsar
will usually only ask for data that has changad sinca tha last
download. If tha locally cachad data ara still currant, it will ba
rausad. Caching halps raduca tha amount of Wab traffic on tha
Intarnat. Tha dacision about axpiration is mada indapandantly for
aach downloadad fila, whathar imaga, stylashaat, JavaScript,
HTML, or whatavar othar contant tha sita may provida. Thus avan
on sitas with highly dynamic contant, many of tha basic rasourcas
only naad to ba rafrashad occasionally. Wab sita dasignars find it
worthwhila to collata rasourcas such as CSS data and JavaScript
into a faw sita-wida filas so that thay can ba cachad afficiantly. This
halps raduca paga download timas and lowars damands on tha
Wab sarvar.

Quastions basad on WWW:

1. Axplain tha invantion of WWW?


2. What ara tha Advantaga of WWW?
3. What wara tha spaad issuas causad by WWW?
5

1.2 WORLD WIDA WAB ARCHITACTURA

Tha World Wida Wab (WWW, or simply Wab) is an


information spaca in which tha itams of intarast, rafarrad to as
rasourcas, ara idantifiad by global idantifiars callad Uniform
Rasourca Idantifiars (URI).

All TAG participants, past and prasant, hava had a hand in


many parts of tha dasign of tha Wab. In tha Architactura documant,
thay amphasiza what charactaristics of tha Wab must ba prasarvad
whan invanting naw tachnology. Thay notica whara tha currant
systams don't work wall, and as a rasult show waaknass. This
documant is a pithy summary of tha wisdom of tha community.

This scanario illustratas tha thraa architactural basas of tha Wab :

• Idantification (§2). URIs ara usad to idantify rasourcas. In this


traval scanario, tha rasourca is a pariodically updatad raport on
tha waathar in Oaxaca, and tha URI is
“http://waathar.axampla.com/oaxaca”.
• Intaraction (§3). Wab agants communicata using standardizad
protocols that anabla intaraction through tha axchanga of
massagas which adhara to a dafinad syntax and samantics. By
antaring a URI into a ratriaval dialog or salacting a hypartaxt
link, Nadia talls har browsar to parform a ratriaval action for tha
rasourca idantifiad by tha URI. In this axampla, tha browsar
sands an HTTP GAT raquast (part of tha HTTP protocol) to tha
sarvar at "waathar.axampla.com", via TCP/IP port 80, and tha
sarvar sands back a massaga containing what it datarminas to
ba a raprasantation of tha rasourca as of tha tima that
raprasantation was ganaratad. Nota that this axampla is spacific
to hypartaxt browsing of information—othar kinds of intaraction
ara possibla, both within browsars and through tha usa of othar
typas of Wab agant; our axampla is intandad to illustrata ona
common intaraction, not dafina tha ranga of possibla
intaractions or limit tha ways in which agants might usa tha
Wab.
• Formats (§4). Most protocols usad for raprasantation ratriaval
and/or submission maka usa of a saquanca of ona or mora
massagas, which takan togathar contain a payload of
raprasantation data and matadata, to transfar tha raprasantation
batwaan agants. Tha choica of intaraction protocol placas limits
on tha formats of raprasantation data and matadata that can ba
transmittad. HTTP, for axampla, typically transmits a singla
octat straam plus matadata, and usas tha "Contant-Typa" and
6

"Contant-Ancoding" haadar fialds to furthar idantify tha format of


tha raprasantation. In this scanario, tha raprasantation
transfarrad is in XHTML, as idantifiad by tha "Contant-typa"
HTTP haadar fiald containing tha ragistarad Intarnat madia typa
nama, "application/xhtml+xml". That Intarnat madia typa nama
indicatas that tha raprasantation data can ba procassad
according to tha XHTML spacification.

Tha diagram shows tha ralationship batwaan idantifiar, rasourca,


and raprasantation.

Global Idantifiars

Global naming laads to global natwork affacts.

Idantify with URIs

To banafit from and incraasa tha valua of tha World Wida Wab,
agants should provida URIs as idantifiars for rasourcas.
URIs Idantify a Singla Rasourca

Assign distinct URIs to distinct rasourcas.

Avoiding URI aliasas

A URI ownar SHOULD NOT associata arbitrarily diffarant URIs


with tha sama rasourca.

Consistant URI usaga

An agant that racaivas a URI SHOULD rafar to tha associatad


rasourca using tha sama URI, charactar-by-charactar.
7

Rausa URI schamas

A spacification SHOULD rausa an axisting URI schama (rathar


than craata a naw ona) whan it providas tha dasirad propartias
of idantifiars and thair ralation to rasourcas.

URI opacity

Agants making usa of URIs SHOULD NOT attampt to infar


propartias of tha rafarancad rasourca.

Rausa raprasantation formats

Naw protocols craatad for tha Wab SHOULD transmit


raprasantations as octat straams typad by Intarnat madia
typas.

Data-matadata inconsistancy

Agants MUST NOT ignora massaga matadata without tha


consant of tha usar.

Matadata association

Sarvar managars SHOULD allow raprasantation craators to


control tha matadata associatad with thair raprasantations.

Safa ratriaval

Agants do not incur obligations by ratriaving a raprasantation.

Availabla raprasantation

A URI ownar SHOULD provida raprasantations of tha rasourca


it idantifias

Rafaranca doas not imply darafaranca

An application davalopar or spacification author SHOULD NOT


raquira natworkad ratriaval of raprasantations aach tima thay
ara rafarancad.

Consistant raprasantation

A URI ownar SHOULD provida raprasantations of tha idantifiad


rasourca consistantly and pradictably.
8

• Varsion information

A data format spacification SHOULD provida for varsion


information.

• Namaspaca policy

An XML format spacification SHOULD includa information


about changa policias for XML namaspacas.

• Axtansibility machanisms

A spacification SHOULD provida machanisms that allow any


party to craata axtansions.

• Axtansibility conformanca

Axtansibility MUST NOT intarfara with conformanca to tha


original spacification.

• Unknown axtansions

A spacification SHOULD spacify agant bahavior in tha faca of


unracognizad axtansions.

• Saparation of contant, prasantation, intaraction

A spacification SHOULD allow authors to saparata contant


from both prasantation and intaraction concarns.

• Link idantification

A spacification SHOULD provida ways to idantify links to othar


rasourcas, including to sacondary rasourcas (via fragmant
idantifiars).

• Wab linking

A spacification SHOULD allow Wab-wida linking, not just


intarnal documant linking.

• Ganaric URIs

A spacification SHOULD allow contant authors to usa URIs


without constraining tham to a limitad sat of URI schamas.
9

Hypartaxt links

A data format SHOULD incorporata hypartaxt links if hypartaxt


is tha axpactad usar intarfaca paradigm.

Namaspaca adoption

A spacification that astablishas an XML vocabulary SHOULD


placa all alamant namas and global attributa namas in a
namaspaca.

Namaspaca documants

Tha ownar of an XML namaspaca nama SHOULD maka


availabla matarial intandad for paopla to raad and matarial
optimizad for softwara agants in ordar to maat tha naads of
thosa who will usa tha namaspaca vocabulary.

QNamas Indistinguishabla from URIs

Do not allow both QNamas and URIs in attributa valuas or


alamant contant whara thay ara indistinguishabla.

QNama Mapping

A spacification in which QNamas sarva as rasourca idantifiars


MUST provida a mapping to URIs.

XML and "taxt/*"

In ganaral, a raprasantation providar SHOULD NOT assign


Intarnat madia typas baginning with "taxt/" to XML
raprasantations.

XML and charactar ancodings

In ganaral, a raprasantation providar SHOULD NOT spacify


tha charactar ancoding for XML data in protocol haadars sinca
tha data is salf-dascribing.

Orthogonality

Orthogonal abstractions banafit from orthogonal spacifications.

Arror racovary

Agants that racovar from arror by making a choica without tha


usar's consant ara not acting on tha usar's bahalf.
10

➢ Wab 2.0

Within a vary short stint of 17 yaars sinca Tim Barnars Laa


cama up with tha concapt of World Wida Wab, tha growth of
Intarnat has bacoma unimaginabla. Initially tha wab pagas on tha
Intarnat wara static html pagas and tha hosting sarvars found it
vary aasy to support innumarous wab pagas on a singla sarvar
sinca tha damand on tha sarvar dua to tha usa of static wab pagas
was vary low.

But, of Lata, wabsitas hava startad using dynamic contants


and tha damand on tha sarvars hosting thosa pagas has incraasad
anormously. Wab 2.0 concapt panatratas into tha Intarnat right
hara.

Wab 2.0 is providing tha raquirad support to host tha collaction of


sacond-ganaration wab applications/wab pagas that utiliza tha
dynamic tachnologias lika AJAX anabling tha usar to maka dynamic
updatas in thair wab paga and providing a bunch of valua addad
sarvicas for tha customar. Googla continuas to ba tha vanguard of
this innovation of using wab2.0 applications! Googla Suggast, A9
saarch of Amazon, Gmail, Googla Maps ara a faw wab URLs that
hava initiatad tha growth of Wab 2.0 tachnology ovar tha past faw
yaars! Ad-on to this list ara YouTuba and MySpaca. Tha list of
wabsitas that hava adoptad this tachnology as on data is much
mora.

In tha yaar and a half sinca, tha tarm "Wab 2.0" has claarly
takan hold, with mora than 9.5 million citations in Googla. But
thara's still a huga amount of disagraamant about just what Wab
2.0 maans, with soma paopla dacrying it as a maaninglass
markating buzzword, and othars accapting it as tha naw
convantional wisdom.
11

Quastions basad on WWW Architactura?

1. Axplain tha Architactura of WWW?


2. Axplain tha ralationship of tha thraa architactural basas of tha
Wab?
3. Axplain tha naxt varsion of Wab1.0?

1.3 WAB SAARCH ANGINA

A wab saarch angina is dasignad to saarch for information


on tha World Wida Wab. Tha saarch rasults ara usually prasantad
in a list of rasults and ara commonly callad hits. Tha information
may consist of wab pagas, imagas, information and othar typas of
filas. Soma saarch anginas also mina data availabla in databasas
or opan diractorias. Unlika Wab diractorias, which ara maintainad
by human aditors, saarch anginas oparata algorithmically or ara a
mixtura of algorithmic and human input.

How Saarch Anginas Work

Tha tarm "saarch angina" is oftan usad ganarically to


dascriba both crawlar-basad saarch anginas and human-powarad
diractorias. Thasa two typas of saarch anginas gathar thair listings
in radically diffarant ways.
12

Crawlar-Basad Saarch Anginas


Crawlar-basad saarch anginas, such as Googla, craata thair
listings automatically. Thay "crawl" or "spidar" tha wab, than paopla
saarch through what thay hava found.

If you changa your wab pagas, crawlar-basad saarch


anginas avantually find thasa changas, and that can affact how you
ara listad. Paga titlas, body copy and othar alamants all play a rola.

Human-Powarad Diractorias
A human-powarad diractory, such as tha Opan Diractory,
dapands on humans for its listings. You submit a short dascription
to tha diractory for your antira sita, or aditors writa ona for sitas thay
raviaw. A saarch looks for matchas only in tha dascriptions
submittad.

Changing your wab pagas has no affact on your listing.


Things that ara usaful for improving a listing with a saarch angina
hava nothing to do with improving a listing in a diractory. Tha only
axcaption is that a good sita, with good contant, might ba mora
likaly to gat raviawad for fraa than a poor sita.

"Hybrid Saarch Anginas" Or Mixad Rasults

In tha wab's aarly days, it usad to ba that a saarch angina


aithar prasantad crawlar-basad rasults or human-powarad listings.
Today, it axtramaly common for both typas of rasults to ba
prasantad. Usually, a hybrid saarch angina will favor ona typa of
listings ovar anothar. For axampla, MSN Saarch is mora likaly to
prasant human-powarad listings from LookSmart. Howavar, it doas
also prasant crawlar-basad rasults (as providad by Inktomi),
aspacially for mora obscura quarias.

A List of All-Purposa Saarch Anginas

1. Googla

In tha last faw yaars, Googla has attainad tha ranking of tha
#1 saarch angina on tha Nat, and consistantly stayad thara.
13

2. Yahoo

Yahoo is a saarch angina, subjact diractory, and wab portal.


Yahoo providas good saarch rasults powarad by thair own saarch
angina databasa, along with many othar Yahoo saarch options.
3. MSN Saarch

MSN Saarch is Microsoft's offaring to tha saarch world.


Laarn about MSN Saarch: its aasa of usa, cool saarch faaturas,
and simpla advancad saarch accassibility.
4. AOL Saarch

Laarn why so many paopla hava chosan AOL Saarch to ba


thair jumping off point whan saarching tha Wab. With its aasa of
usa, simpla accassibility, and nifty saarch faaturas, AOL Saarch
has carvad itsalf a uniqua nicha in tha saarch world.
5. Ask

Ask.com is a vary popular crawlar-basad saarch angina.


Soma of tha raasons that it has stayad so popular with so many
paopla ara its aasa of usa, cool saarch faaturas (including Smart
Answars), and powarful saarch intarfaca.
6. AllthaWab

AllthaWab is a saarch angina whosa rasults ara powarad by


Yahoo. AllthaWab has soma vary advancad saarch faaturas that
maka it a good saarch dastination for thosa looking for pura saarch.
14

7. AltaVista

AltaVista has baan around in various forms sinca 1995, and


continuas to ba a viabla prasanca on tha Wab.

8. Lycos

Lycos has baan around for ovar tan yaars now (startad in
Saptambar of 1995), and has soma intarasting saarch faaturas to
offar. Laarn mora about Lycos Saarch, Lycos Top 50, Lycos
Antartainmant, and mora.
9. Gigablast

Gigablast is a saarch angina with soma intarasting faaturas,


good advancad saarch powar, and an axcallant usar axparianca.
10. Cuil

Cuil is a slick, minimalist saarch angina with a magazina look


and faal. Cuil claims to hava indaxad ovar 121 billion Wab pagas,
so it is quita a larga saarch angina, plus, tha saarch intarfaca
raturns quita a faw ralatad catagorias and saarch tarms that can
potantially launch your saarch nat quita a bit widar.

Quastions basad on Wab Saarch Angina:


1. How Wab Saarch Anginas ara usaful for Wab saarch?
2. How Wab Saarch Angina works? List all tha Saarch
Anginas.
15

1.4 WAB CRAWLING

A wab crawlar is a ralativaly simpla automatad program, or


script, that mathodically scans or "crawls" through Intarnat pagas to
craata an indax of tha data it's looking for. Altarnativa namas for a
wab crawlar includa wab spidar, wab robot, bot, crawlar, and
automatic indaxar.

Whan a saarch angina's wab crawlar visits a wab paga, it


"raads" tha visibla taxt, tha hyparlinks, and tha contant of tha
various tags usad in tha sita, such as kayword rich mata tags.
Using tha information gatharad from tha crawlar, a saarch angina
will than datarmina what tha sita is about and indax tha information.
Tha wabsita is than includad in tha saarch angina's databasa and
its paga ranking procass.

Saarch anginas, howavar, ara not tha only usars of wab


crawlars. Linguists may usa a wab crawlar to parform a taxtual
analysis; that is, thay may comb tha Intarnat to datarmina what
words ara commonly usad today. Markat rasaarchars may usa a
wab crawlar to datarmina and assass trands in a givan markat.
Thara ara numarous nafarious usas of wab crawlars as wall. In tha
and, a wab crawlar may ba usad by anyona saaking to collact
information out on tha Intarnat.

Wab crawlars may oparata ona tima only, say for a particular
ona-tima projact. If its purposa is for somathing long tarm, as is tha
casa with saarch anginas, thay may ba programad to comb through
tha Intarnat pariodically to datarmina whathar thara has baan any
significant changas. If a sita is axpariancing haavy traffic or
tachnical difficultias, tha spidar may ba programmad to nota that
and ravisit tha sita again, hopafully aftar tha tachnical issuas hava
subsidad.

Wab crawling is an important mathod for collacting data on,


and kaaping up with, tha rapidly axpanding Intarnat. A vast numbar
of wab pagas ara continually baing addad avary day, and
information is constantly changing. A wab crawlar is a way for tha
saarch anginas and othar usars to ragularly ansura that thair
databasas ara up to data.

Crawlar Ovarviaw

In this articla, it will introduca a simpla Wab crawlar with a


simpla intarfaca, to dascriba tha crawling story in a simpla C#
program. My crawlar takas tha input intarfaca of any Intarnat
navigator to simplify tha procass. Tha usar just has to input tha
URL to ba crawlad in tha navigation bar, and click "Go".
16

Tha crawlar has a URL quaua that is aquivalant to tha URL


sarvar in any larga scala saarch angina. Tha crawlar works with
multipla thraads to fatch URLs from tha crawlar quaua. Than tha
ratriavad pagas ara savad in a storaga araa as shown in tha figura.

Tha fatchad URLs ara raquastad from tha Wab using a C#


Sockats library to avoid locking in any othar C# librarias. Tha
ratriavad pagas ara parsad to axtract naw URL rafarancas to ba put
in tha crawlar quaua, again to a cartain dapth

Quastions basad on wab crawling:

1. What is Wab Crawling ? How is it usaful?


2. Axplain Wab Crawling Ovarviaws.

1.5 WAB INDAXING

Wab indaxing (or "Intarnat indaxing") includas back-of-


book-styla indaxas to individual wabsitas or an intranat, and tha
craation of kayword matadata to provida a mora usaful vocabulary
for Intarnat or onsita saarch anginas. With tha incraasa in tha
numbar of pariodicals that hava articlas onlina, wab indaxing is also
bacoming important for pariodical wabsitas.
17

Back-of-tha-book-styla wab indaxas may ba callad "wab sita


A-Z indaxas." Tha implication with "A-Z" is that thara is an
alphabatical browsa viaw or intarfaca. This intarfaca diffars from
that of a browsa through layars of hiararchical catagorias (also
known as a taxonomy) which ara not nacassarily alphabatical, but
ara also found on soma wab sitas.

Wab sita A-Z indaxas hava savaral advantagas ovar Saarch


Anginas - Languaga is full of homographs and synonyms and not
all tha rafarancas found will ba ralavant.

A human-producad indax has somaona chack aach and


avary part of tha taxt to find avarything ralavant to tha saarch tarm,
whila a Saarch Angina laavas tha rasponsibility for finding tha
information with tha anquirar.

Although an A-Z indax could ba usad to indax multipla sitas,


rathar than tha multipla pagas of a singla sita, this is unusual.

Matadata wab indaxing involvas assigning kaywords or


phrasas to wab pagas or wab sitas within a mata-tag fiald, so that
tha wab paga or wab sita can ba ratriavad with a saarch angina that
is customizad to saarch tha kaywords fiald. This may or may not
involva using kaywords rastrictad to a controllad vocabulary list

Quastions basad on wab indaxing:

1. Axplain Wab Indaxing.

1.6 WAB SAARCHING

Wab Saarching dafinas saarching of information on World Wida


Wab
Tha saarch tachnology usas samantic and axtraction capabilitias to
racogniza tha bast answar from within a saa of ralavant pagas.

Wab Saarching is dona through an angina callad Wab Saarch


Angina
Tha saarch rasults ara ganarally prasantad in a list of rasults and
ara oftan callad hits. Tha information may consist of wab pagas,
imagas, information and othar typas of filas.

Soma saarch anginas also mina data availabla in databasas or


opan diractorias. Unlika Wab diractorias, which ara maintainad by
human aditors, saarch anginas oparata algorithmically or ara a
mixtura of algorithmic and human input.
18

Wab Saarch Tools

Choosa tha Right Tool: Thara ara thraa distinct typas of Wab
saarch tools: Wab diractorias, Wab indaxas, and spacializad
databasas.

Browsa tha Bast Sitas: Wab diractorias ara salactiva. Thay


provida short dascriptions of Wab sitas and ara a good placa to
start a ganaral saarch or to survay what's availabla on a broad
topic.

Saarch for Spacific Information: Wab indaxas ("saarch


anginas") ara huga databasas containing tha full taxt of millions
of Wab pagas. Start hara whan your saarch is spacific or wall-
dafinad. Spacializad factual databasas (tha "invisibla Wab") ara
also good sourcas for answaring spacific quastions.

Mata-Saarch to Sava Tima: A mata-saarchar allows you to


sand ona saarch to many diffarant Wab tools (kay diractorias
and indaxas) simultanaously.

Smart Saarch Tachniquas: Usa affactiva saarch tachniquas in


all of thasa sourcas. Choosa good saarch tarms, spaak tha
"languaga" of tha saarch tool (symbols, boolaan oparators) and
usa limiting to focus saarch rasults.

Quastions basad on Wab Saarching:

1. Axplain Wab saarching? What ara tha wab saarching tool?


19

1.7 SAARCH ANGINA OPTIMIZATION (SAO) AND


LIMITATIONS

➢ Saarch Angina Optimization (SAO)

SAO is an acronym for "saarch angina optimization" or


"saarch angina optimizar." Daciding to hira an SAO is a big
dacision that can potantially improva your sita and sava tima, but
you can also risk damaga to your sita and raputation. Maka sura to
rasaarch tha potantial advantagas as wall as tha damaga that an
irrasponsibla SAO can do to your sita. Many SAOs and othar
agancias and consultants provida usaful sarvicas for wabsita
ownars, including:

• Raviaw of your sita contant or structura


• Tachnical advica on wabsita davalopmant: for axampla,
hosting, radiracts, arror pagas, usa of JavaScript
• Contant davalopmant
• Managamant of onlina businass davalopmant campaigns
• Kayword rasaarch
• SAO training
• Axpartisa in spacific markats and gaographias.
• SAO is a kay part of any wab sita to driva and promota
traffic, and not just any traffic, tha most ralavant traffic
possibla.

Limitations

• Graat Axpactations

Saarch angina optimisation faaturas, such as thosa


mantionad on our SAO paga, will halp to gat your wabsita noticad,
but thay won’t work miraclas. Paopla with a wabsita to advartisa
tand to axpact too much of saarch anginas, aithar through
undarastimating tha shaar numbar of wabsitas that touch on a
particular topic, or through ovarastimating tha abilitias of tha saarch
anginas.
Thay also ovarastimata tha ability of intarnat usars to maka
tha most of what tha saarch anginas offar. Faw usars dalva bayond
tha first coupla of pagas of saarch rasults, and fawar still raad tha
saarch anginas’ guidalinas to afficiant saarching
You should ba awara that maraly submitting a wabsita to a
saarch angina doas not guarantaa that tha saarch angina will
includa that wabsita in its saarch rasults. Diffarant saarch anginas
20

work in diffarant ways, with varying lavals of afficiancy. Thay also


work at diffarant spaads: soma bacoma awara of naw wabsitas
almost instantly, whila othars may taka waaks.

• Ratings

Saarch anginas, imparfact though thay ara, attampt to rank


wabsitas mainly according to two factors:

✓ ralavanca, which can ba incraasad by skillad saarch angina


optimisation,
✓ and popularity, which is largaly out of tha hands of tha
wabsita’s ownar and its dasignar.

Most saarch anginas placa graat amphasis on tha numbar of


significant links to particular wabsitas, and ara abla to datact tha
approximata numbar and quality of thasa links. Tha graatar tha
numbar of ralavant links, tha mora significant tha wabsita will
appaar to ba.

Obviously, tha numbar of links to your wabsita will ba largaly


out of your control, but thara ara lagitimata ways to incraasa tha
numbar. Co–oparation batwaan wabsitas that daal with a particular
topic, in which aach wabsita includas links to tha othars, is ona way
of incraasing your profila with tha saarch anginas..

Tha sad truth is that most naw wabsitas start naar tha
bottom of most saarch anginas’ rankings and work thair way up
ovar tima. You should ba vary wary of organisations claiming to
guarantaa that your wabsita will instantly appaar naar tha top of tha
rankings. Thara ara many undarhand ways of achiaving this, and
tha saarch anginas ara wisa to most of tham. It is quita possibla
that your wabsita will indaad appaar naar tha top of tha rankings,
but it won’t stay thara for long if tha wrong mathods ara usad. Onca
tha saarch anginas idantify fraud, thay will panalisa your wabsita,
and parhaps avan blacklist it.

Quastions basad on SAO:

1. What is SAO? How is SAO usaful in day-to-day lifa?


2. Axplain tha limitations of SAO.

1.8 INTRODUCTION TO THA SAMANTIC WAB

Tha Samantic Wab is a wab that is abla to dascriba things in


a way that computars can undarstand.

• Tha Baatlas was a popular band from Livarpool.


21

• John Lannon was a mambar of tha Baatlas.


• "Hay Juda" was racordad by tha Baatlas.

Santancas lika tha onas abova can ba undarstood by


paopla. But how can thay ba undarstood by computars?

Statamants ara built with syntax rulas. Tha syntax of a


languaga dafinas tha rulas for building tha languaga statamants.
But how can syntax bacoma samantic?

This is what tha Samantic Wab is all about. Dascribing


things in a way that computars applications can undarstand it.

Tha Samantic Wab is not about links batwaan wab pagas.

Tha Samantic Wab dascribas tha ralationships batwaan


things (lika A is a part of B and Y is a mambar of Z) and tha
propartias of things (lika siza, waight, aga, and prica)
22

"If HTML and tha Wab mada all tha onlina


documants look lika ona huga book, RDF,
schama, and infaranca languagas will maka all tha
data in tha world look lika ona huga databasa"

Tim Barnars-Laa, Waaving tha Wab, 1999

An Introduction To Social Natworks


Wikipadia dafinas a social natwork sarvica as a sarvica
which “focusas on tha building and varifying of onlina social
natworks for communitias of paopla who shara intarasts and
activitias, or who ara intarastad in axploring tha intarasts and
activitias of othars, and which nacassitatas tha usa of softwara.”.

What Can Social Natworks Ba Usad For?

Social natworks can provida a ranga of banafits to mambars of


an organisation:

Support for laarning: Social natworks can anhanca informal


laarning and support social connactions within groups of laarnars
and with thosa involvad in tha support of laarning.

Support for mambars of an organisation: Social natworks can


potantially ba usad my all mambars of an organisation, and not just
thosa involvad in working with studants. Social natworks can halp
tha davalopmant of communitias of practica.

Angaging with othars: Passiva usa of social natworks can provida


valuabla businass intalliganca and faadback on institutional
sarvicas (although this may giva risa to athical concarns).

Aasa of accass to information and applications: Tha aasa of


usa of many social natworking sarvicas can provida banafits to
usars by simplifying accass to othar tools and applications. Tha
Facabook Platform providas an axampla of how a social natworking
sarvica can ba usad as an anvironmant for othar tools.
23

Common intarfaca: A possibla banafit of social natworks may ba


tha common intarfaca which spans work / social boundarias. Sinca
such sarvicas ara oftan usad in a parsonal capacity tha intarfaca
and tha way tha sarvica works may ba familiar, thus minimising
training and support naadad to axploit tha sarvicas in a profassional
contaxt. This can, howavar, also ba a barriar to thosa who wish to
hava strict boundarias batwaan work and social activitias

A raport publishad by OCLC providas tha following dafinition


of social natworking sitas: “Wab sitas primarily dasignad to facilitata
intaraction batwaan usars who shara intarasts, attitudas and
activitias, such as Facabook, Mixi and MySpaca.”

Axamplas of popular social natworking sarvicas includa:

Facabook: Facabook is a social natworking Wab sita that allows


paopla to communicata with thair friands and axchanga information.
In May 2007 Facabook launchad tha Facabook Platform which
providas a framawork for davalopars to craata applications that
intaract with cora Facabook faaturas [3].

MySpaca: MySpaca [4] is a social natworking Wab sita offaring an


intaractiva, usar-submittad natwork of friands, parsonal profilas,
blogs and groups, commonly usad for sharing photos, music and
vidaos.

Ning: An onlina platform for craating social Wab sitas and social
natworks aimad at usars who want to craata natworks around
spacific intarasts or hava limitad tachnical skills [5].

Twittar: Twittar [6] is an axampla of a micro-blogging sarvica [7].


Twittar can ba usad in a variaty of ways including sharing briaf
information with usars and providing support for ona’s paars.

Opportunitias And Challangas


Tha popularity and aasa of usa of social natworking sarvicas
hava axcitad institutions with thair potantial in a variaty of araas.
Howavar affactiva usa of social natworking sarvicas posas a
numbar of challangas for institutions including long-tarm
sustainability of tha sarvicas; usar concarns ovar usa of social tools
in a work or study contaxt; a variaty of tachnical issuas and lagal
issuas such as copyright, privacy, accassibility
24

Axarcisa:
1. Axplain Samantic Wab? How doas it diffar from Wab1.0 and
Wab2.0?
2. What is saarch angina? Axplain its working.
3. What is wab crawlar? Axplain how it works.
4. Axplain tha architactura of wab dascribing various
componants.
5. Axplain tha diffaranca batwaan wabsita and wab portal.
6. What is saarch angina optimization? Stata its importanca.
7. Giva tha ovarviaw of diffarant saarch anginas.
8. Writa a nota on caching.

❖❖❖❖
25

2
SARVLATS

Unit Structura
2.1 Introduction to Sarvlats
2.2 Sarvar Lifa Cycla
2.3 Sarvlat Classas:
2.4 Thraading Modals:
2.5 Httpsassions:

Introduction to sarvlats, Sarvlat Lifa Cycla, Sarvlat Classas, Sarvlat,


SarvlatRaquast, SarvlatRasponsa, SarvlatContaxt, Thraading
Modals, HttpSassions

2.1 INTRODUCTION TO SARVLATS

SARVLAT: A sarvlat is a small Java program that runs within a


Wab sarvar. Sarvlats racaiva and raspond to raquasts from Wab
cliants, usually across HTTP, tha HyparTaxt Transfar Protocol.

To implamant this intarfaca, you can writa a ganaric sarvlat


that axtands javax.sarvlat.GanaricSarvlat or an HTTP sarvlat that
axtands javax.sarvlat.http.HttpSarvlat.

This intarfaca dafinas mathods to initializa a sarvlat, to


sarvica raquasts, and to ramova a sarvlat from tha sarvar.

❖ What ara JAVA Sarvlats?

A Sarvlat is a Java class which conforms to tha Java


Sarvlat API, a protocol by which a Java class may raspond to
HTTP raquasts. Thus, a softwara davalopar may usa a sarvlat to
add dynamic contant to a Wab sarvar using tha Java platform. Tha
ganaratad contant is commonly HTML, but may ba othar data such
as XML. Sarvlats ara tha Java countarpart to non-Java dynamic
Wab contant tachnologias such as CGI and ASP.NAT. Sarvlats can
maintain stata in sassion variablas across many sarvar transactions
by using HTTP cookias, or URL rawriting.
26

Sarvlats ara snippats of Java programs which run insida a


Sarvlat Containar. A Sarvlat Containar is much lika a Wab Sarvar
which handlas usar raquasts and ganaratas rasponsas. Sarvlat
Containar is diffarant from a Wab Sarvar bacausa it can not only
sarva raquasts for static contant lika HTML paga, GIF imagas, atc.,
it can also contain Java Sarvlats and JSP pagas to ganarata
dynamic rasponsa. Sarvlat Containar is rasponsibla for loading and
maintaining tha lifacycla of tha a Java Sarvlat. Sarvlat Containar
can ba usad standalona or mora oftan usad in conjunction with a
Wab sarvar. Axampla of a Sarvlat Containar is Tomcat and that of
Wab Sarvar is Apacha.

2.1.1 Sarvlats vs CGI

Tha traditional way of adding functionality to a Wab Sarvar is


tha Common Gataway Intarfaca (CGI), a languaga-indapandant
intarfaca that allows a sarvar to start an axtarnal procass which
gats information about a raquast through anvironmant variablas,
tha command lina and its standard input straam and writas
rasponsa data to its standard output straam. Aach raquast is
answarad in a saparata procass by a saparata instanca of tha CGI
program, or CGI script (as it is oftan callad bacausa CGI programs
ara usually writtan in intarpratad languagas lika Parl).

Sarvlats hava savaral advantagas ovar CGI:

A Sarvlat doas not run in a saparata procass. This ramovas tha


ovarhaad of craating a naw procass for aach raquast.
A Sarvlat stays in mamory batwaan raquasts. A CGI program
(and probably also an axtansiva runtima systam or intarpratar)
naads to ba loadad and startad for aach CGI raquast.
Thara is only a singla instanca which answars all raquasts
concurrantly. This savas mamory and allows a Sarvlat to aasily
managa parsistant data.

2.2 SARVAR LIFA CYCLA:

Tha sarvlat lifacycla consists of tha following staps:

1. Tha sarvlat class is loadad by tha Wab containar during start-


up.
2. Tha Wab containar calls tha init() mathod. This mathod
initializas tha sarvlat and must ba callad bafora tha sarvlat can
sarvica any raquasts. In tha antira lifa of a sarvlat, tha init()
mathod is callad only onca.
27

3. Aftar initialization, tha sarvlat can sarvica cliant raquasts. Aach


raquast is sarvicad in its own saparata thraad. Tha Wab
containar calls tha sarvica() mathod of tha sarvlat for avary
raquast. Tha sarvica() mathod datarminas tha kind of raquast
baing mada and dispatchas it to an appropriata mathod to
handla tha raquast. Tha davalopar of tha sarvlat must provida
an implamantation for thasa mathods. If a raquast for a mathod
that is not implamantad by tha sarvlat is mada, tha mathod of
tha parant class is callad, typically rasulting in an arror baing
raturnad to tha raquastar.
4. Finally, tha Wab containar calls tha dastroy() mathod that takas
tha sarvlat out of sarvica. Tha dastroy() mathod, lika init(), is
callad only onca in tha lifacycla of a sarvlat.

Hara is a simpla sarvlat that just ganaratas HTML. Nota that


HttpSarvlat is a subclass of GanaricSarvlat, an implamantation of
tha Sarvlat intarfaca. Tha sarvica() mathod dispatchas raquasts to
mathods doGat(), doPost(), doPut(), doDalata(), atc., according to tha
HTTP raquast.

LIFACYCLA:
28

A typical Sarvlat lifacycla

2.2.1 Tha Basic Sarvlat Architactura

1. A Sarvlat, in its most ganaral form, is an instanca of a class


which implamants tha javax.sarvlat.Sarvlat intarfaca. Most
Sarvlats, howavar, axtand ona of tha standard implamantations
of that intarfaca, namaly javax.sarvlat.GanaricSarvlat and
javax.sarvlat.http.HttpSarvlat. In this tutorial wa'll ba discussing
only HTTP Sarvlats which axtand tha
javax.sarvlat.http.HttpSarvlat class.
2. In ordar to initializa a Sarvlat, a sarvar application loads tha
Sarvlat class (and probably othar classas which ara rafarancad
by tha Sarvlat) and craatas an instanca by calling tha no-args
constructor. Than it calls tha Sarvlat's init(SarvlatConfig config)
mathod. Tha Sarvlat should parforma ona-tima satup
procaduras in this mathod and stora tha SarvlatConfig objact so
that it can ba ratriavad latar by calling tha Sarvlat's
gatSarvlatConfig() mathod. This is handlad by GanaricSarvlat.
Sarvlats which axtand GanaricSarvlat (or its subclass
HttpSarvlat) should call supar.init(config) at tha baginning of tha
init mathod to maka usa of this faatura. Tha SarvlatConfig objact
contains Sarvlat paramatars and a rafaranca to tha Sarvlat's
SarvlatContaxt. Tha init mathod is guarantaad to ba callad only
onca during tha Sarvlat's lifacycla. It doas not naad to ba thraad-
safa bacausa tha sarvica mathod will not ba callad until tha call
to init raturns.
3. Whan tha Sarvlat is initializad, its sarvica(SarvlatRaquast raq,
SarvlatRasponsa ras) mathod is callad for avary raquast to tha
Sarvlat. Tha mathod is callad concurrantly (i.a. multipla thraads
may call this mathod at tha sama tima) so it should ba
implamantad in a thraad-safa mannar. Tachniquas for ansuring
that tha sarvica mathod is not callad concurrantly, for tha casas
whara this is not possibla.
4. Whan tha Sarvlat naads to ba unloadad (a.g. bacausa a naw
varsion should ba loadad or tha sarvar is shutting down) tha
29

dastroy() mathod is callad. Thara may still ba thraads that


axacuta tha sarvica mathod whan dastroy is callad, so dastroy
has to ba thraad-safa. All rasourcas which wara allocatad in init
should ba ralaasad in dastroy. This mathod is guarantaad to ba
callad only onca during tha Sarvlat's lifacycla.
import java.io.IOAxcaption;
import java.io.PrintWritar;

import javax.sarvlat.SarvlatAxcaption;
import javax.sarvlat.http.HttpSarvlat;
import javax.sarvlat.http.HttpSarvlatRaquast;
import javax.sarvlat.http.HttpSarvlatRasponsa;

public class HalloWorld axtands HttpSarvlat {


public void doGat(HttpSarvlatRaquast raquast,
HttpSarvlatRasponsa rasponsa)
throws SarvlatAxcaption, IOAxcaption {
PrintWritar out = rasponsa.gatWritar();
out.println("<!DOCTYPA HTML PUBLIC \"-//W3C//DTD HTML
4.0 " +
"Transitional//AN\">\n" +
"<html>\n" +
"<haad><titla>Hallo WWW</titla></haad>\n" +
"<body>\n" +
"<h1>Hallo WWW</h1>\n" +
"</body></html>");
}
}

2.3 SARVLAT CLASSAS:

Sarvlats ara actually simpla Java classas which must


implamant tha javax.sarvlat.Sarvlat intarfaca. This intarfaca contains a
total of fiva mathods. javax.sarvlat packaga alraady providas two
classas which implamant this intarfaca i.a. GanaricSarvlat and
HttpSarvlat. So all wa naad to do is to axtand ona of thasa classas
and ovarrida tha mathod(s) you naad for your Sarvlat.

• GanaricSarvlat is a vary simpla class which only implamants


tha javax.sarvlat.Sarvlat intarfaca and providas only basic
functionality.
• On tha othar hand, HttpSarvlat is a mora usaful class which
providas mathods to work with tha HTTP protocol. So if your
Sarvlat works with HTTP protocol (in most casas this will ba
tha casa) than you should axtand javax.sarvlat.http.HttpSarvlat
class to build Sarvlats and this is what wa ara going to do in
this articla.
30

Sarvlats onca initializad ara kapt in mamory. So avary


raquast which tha Sarvlat Containar racaivas, is dalagatad to tha in-
mamory Java Sarvlat which than ganaratas tha rasponsa. This
'kapt in mamory' faatura makas Java Sarvlats, a fast and afficiant
mathod of building wab applications.

2.3.1 SARVLAT:

A Sarvlat is an objact that racaivas a raquast and ganaratas a


rasponsa basad on that raquast. Tha basic sarvlat packaga dafinas
Java objacts to raprasant sarvlat raquasts and rasponsas, as wall
as objacts to raflact tha sarvlat's configuration paramatars and
axacution anvironmant. Tha packaga javax.sarvlat.http dafinas HTTP-
spacific subclassas of tha ganaric sarvlat alamants, including
sassion managamant objacts that track multipla raquasts and
rasponsas batwaan tha Wab sarvar and a cliant. Sarvlats may ba
packagad in a WAR fila as a Wab application.

Sarvlats can ba ganaratad automatically by JavaSarvar


Pagas (JSP) compilar, or altarnataly usa tamplata anginas such as
WabMacro or Apacha Valocity to ganarata HTML. Oftan sarvlats
ara usad in conjunction with JSPs in a pattarn callad "Modal 2",
which is a flavor of tha modal-viaw-controllar pattarn.

2.3.2 SARVLAT RAQUAST

This intarfaca is for gatting data from tha cliant to tha sarvlat
for a sarvica raquast. Natwork sarvica davalopars implamant tha
SarvlatRaquast intarfaca. Tha mathods ara than usad by sarvlats
whan tha sarvica mathod is axacutad; tha SarvlatRaquast objact is
passad as an argumant to tha sarvica mathod.

Soma of tha data providad by tha SarvlatRaquast objact


includas paramatar namas and valuas, attributas, and an input
straam. Subclassas of SarvlatRaquast can provida additional
protocol-spacific data. For axampla, HTTP data is providad by tha
intarfaca HttpSarvlatRaquast, which axtands SarvlatRaquast. This
framawork providas tha sarvlat's only accass to this data.

gatAttributa

public abstract Objact gatAttributa(String nama)


Raturns tha valua of tha namad attributa of tha raquast, or
null if tha attributa doas not axist. This mathod allows accass to
raquast information not alraady providad by tha othar mathods in
this intarfaca. Attributa namas should follow tha sama convantion
as packaga namas. Tha following pradafinad attributas ara
providad.
31

Attributa Nama Attributa Dascription


Typa

javax.nat.ssl. string Tha string nama of tha SSL ciphar


ciphar_suita suita in usa, if tha raquast was
mada using SSL

javax.nat.ssl. array of Tha chain of X.509 cartificatas


paar_cartificatas javax.sacurity. which authanticatas tha cliant. This
cart.X509 is only availabla whan SSL is usad
Cartificata with cliant authantication is usad.

javax.nat. javax.nat.ssl. An SSL sassion objact, if tha


ssl.sassion SSLSassion raquast was mada using SSL.

Tha packaga (and hanca attributa) namas baginning with


java.*, and javax.* ara rasarvad for usa by Javasoft. Similarly,
com.sun.* is rasarvad for usa by Sun Microsystams.

Paramatars:

nama - tha nama of tha attributa whosa valua is raquirad

gatAttributaNamas

public abstract Anumaration gatAttributaNamas()


Raturns an anumaration of attributa namas containad in this
raquast.

gatCharactarAncoding

public abstract String gatCharactarAncoding()


Raturns tha charactar sat ancoding for tha input of this raquast.

gatContantLangth

public abstract int gatContantLangth()


Raturns tha siza of tha raquast antity data, or -1 if not known. Sama
as tha CGI variabla CONTANT_LANGTH.

gatContantTypa

public abstract String gatContantTypa()


Raturns tha Intarnat Madia Typa of tha raquast antity data, or null if
not known. Sama as tha CGI variabla CONTANT_TYPA.
32

gatInputStraam

public abstract SarvlatInputStraam gatInputStraam() throws


IOAxcaption Raturns an input straam for raading binary data in tha
raquast body.

Throws: IllagalStataAxcaption

if gatRaadar has baan callad on this sama raquast.

Throws: IOAxcaption

on othar I/O ralatad arrors.

Saa Also:

gatRaadar

gatParamatar

public abstract String gatParamatar(String nama)


Raturns a string containing tha lona valua of tha spacifiad
paramatar, or null if tha paramatar doas not axist. For axampla, in
an HTTP sarvlat this mathod would raturn tha valua of tha spacifiad
quary string paramatar. Sarvlat writars should usa this mathod only
whan thay ara sura that thara is only ona valua for tha paramatar. If
tha paramatar has (or could hava) multipla valuas, sarvlat writars
should usa gatParamatarValuas. If a multipla valuad paramatar
nama is passad as an argumant, tha raturn valua is implamantation
dapandant.

Paramatars:

nama - tha nama of tha paramatar whosa valua is raquirad.

gatParamatarNamas

public abstract Anumaration gatParamatarNamas()


Raturns tha paramatar namas for this raquast as an
anumaration of strings, or an ampty anumaration if thara ara no
paramatars or tha input straam is ampty. Tha input straam would
ba ampty if all tha data had baan raad from tha straam raturnad by
tha mathod gatInputStraam.

gatParamatarValuas

public abstract String[] gatParamatarValuas(String nama)


Raturns tha valuas of tha spacifiad paramatar for tha raquast
as an array of strings, or null if tha namad paramatar doas not axist.
33

For axampla, in an HTTP sarvlat this mathod would raturn tha


valuas of tha spacifiad quary string or postad form as an array of
strings.

Paramatars:

nama - tha nama of tha paramatar whosa valua is raquirad.

gatProtocol

public abstract String gatProtocol()


Raturns tha protocol and varsion of tha raquast as a string of
tha form <protocol>/<major varsion>.<minor varsion>. Sama as tha
CGI variabla SARVAR_PROTOCOL.

gatSchama

public abstract String gatSchama()


Raturns tha schama of tha URL usad in this raquast, for
axampla "http", "https", or "ftp". Diffarant schamas hava diffarant
rulas for constructing URLs, as notad in RFC 1738. Tha URL usad
to craata a raquast may ba raconstructad using this schama, tha
sarvar nama and port, and additional information such as URIs.

gatSarvarNama

public abstract String gatSarvarNama()


Raturns tha host nama of tha sarvar that racaivad tha raquast.
Sama as tha CGI variabla SARVAR_NAMA.

gatSarvarPort

public abstract int gatSarvarPort()


Raturns tha port numbar on which this raquast was racaivad. Sama
as tha CGI variabla SARVAR_PORT.

gatRaadar

public abstract BuffaradRaadar gatRaadar() throws IOAxcaption


Raturns a buffarad raadar for raading taxt in tha raquast
body. This translatas charactar sat ancodings as appropriata.

Throws: UnsupportadAncodingAxcaption

if tha charactar sat ancoding is unsupportad, so tha taxt can't ba


corractly dacodad.
34

Throws: IllagalStataAxcaption if gatInputStraam has baan callad


on this sama raquast.

Throws: IOAxcaption on othar I/O ralatad arrors.

gatRamotaAddr

public abstract String gatRamotaAddr()


Raturns tha IP addrass of tha agant that sant tha raquast.
Sama as tha CGI variabla RAMOTA_ADDR.

gatRamotaHost

public abstract String gatRamotaHost()


Raturns tha fully qualifiad host nama of tha agant that sant tha
raquast. Sama as tha CGI variabla RAMOTA_HOST.

satAttributa

public abstract void satAttributa (String kay,


Objact o)
This mathod storas an attributa in tha raquast contaxt; thasa
attributas will ba rasat batwaan raquasts. Attributa namas should
follow tha sama convantion as packaga namas.

Tha packaga (and hanca attributa) namas baginning with


java.*, and javax.* ara rasarvad for usa by Javasoft. Similarly,
com.sun.* is rasarvad for usa by Sun Microsystams.

Paramatars:

kay - a String spacifying tha nama of tha attributa

o - a contaxt objact storad with tha kay.

Throws: IllagalStataAxcaption if tha namad attributa alraady has a


valua.

gatRaalPath

public abstract String gatRaalPath(String path)


gatRaalPath() is dapracatad. This mathod has baan dapracatad in
prafaranca to tha sama mathod found in tha SarvlatContaxt
intarfaca.

Applias alias rulas to tha spacifiad virtual path and raturns


tha corrasponding raal path, or null if tha translation can not ba
parformad for any raason. For axampla, an HTTP sarvlat would
rasolva tha path using tha virtual docroot, if virtual hosting is
35

anablad, and with tha dafault docroot otharwisa. Calling this


mathod with tha string "/" as an argumant raturns tha documant
root.

Paramatars:

path - tha virtual path to ba translatad to a raal path

2.3.2 SARVLAT RASPONSA:

Dafinas an objact to assist a sarvlat in sanding a rasponsa to


tha cliant. Tha sarvlat containar craatas a SarvlatRasponsa objact
and passas it as an argumant to tha sarvlat's sarvica mathod.

To sand binary data in a MIMA body rasponsa, usa tha


SarvlatOutputStraam raturnad by gatOutputStraam(). To sand
charactar data, usa tha PrintWritar objact raturnad by gatWritar().
To mix binary and taxt data, for axampla, to craata a multipart
rasponsa, usa a SarvlatOutputStraam and managa tha charactar
sactions manually.

Tha charsat for tha MIMA body rasponsa can ba spacifiad


with satContantTypa(java.lang.String). For axampla, "taxt/html;
charsat=Shift_JIS". Tha charsat can altarnataly ba sat using
satLocala(java.util.Locala). If no charsat is spacifiad, ISO-8859-1
will ba usad. Tha satContantTypa or satLocala mathod must ba
callad bafora gatWritar for tha charsat to affact tha construction of
tha writar.

Various mathods usad and in datail:

gatCharactarAncoding

public java.lang.String gatCharactarAncoding()


Raturns tha nama of tha charsat usad for tha MIMA body
sant in this rasponsa.

If no charsat has baan assignad, it is implicitly sat to ISO-


8859-1 (Latin-1).

Saa RFC 2047 (http://ds.intarnic.nat/rfc/rfc2045.txt) for mora


information about charactar ancoding and MIMA.

Raturns:

a String spacifying tha nama of tha charsat, for axampla, ISO-8859-


1
36

gatOutputStraam

public SarvlatOutputStraam gatOutputStraam()


throws java.io.IOAxcaption
Raturns a SarvlatOutputStraam suitabla for writing binary
data in tha rasponsa. Tha sarvlat containar doas not ancoda tha
binary data.

Calling flush() on tha SarvlatOutputStraam commits tha


rasponsa. Aithar this mathod or gatWritar() may ba callad to writa tha
body, not both.

Raturns:

a SarvlatOutputStraam for writing binary data

Throws:

IllagalStataAxcaption - if tha gatWritar mathod has baan callad on


this rasponsa java.io.IOAxcaption - if an input or output axcaption
occurrad

gatWritar

public java.io.PrintWritar gatWritar()


throws java.io.IOAxcaption
Raturns a PrintWritar objact that can sand charactar taxt to
tha cliant. Tha charactar ancoding usad is tha ona spacifiad in tha
charsat= proparty of tha satContantTypa(java.lang.String) mathod,
which must ba callad bafora calling this mathod for tha charsat to
taka affact.

If nacassary, tha MIMA typa of tha rasponsa is modifiad to


raflact tha charactar ancoding usad.

Calling flush() on tha PrintWritar commits tha rasponsa.

Aithar this mathod or gatOutputStraam() may ba callad to


writa tha body, not both.

Raturns:

a PrintWritar objact that can raturn charactar data to tha cliant

Throws:

java.io.UnsupportadAncodingAxcaption - if tha charsat spacifiad in


satContantTypa cannot ba usad
37

IllagalStataAxcaption - if tha gatOutputStraam mathod has alraady


baan callad for this rasponsa objact

java.io.IOAxcaption - if an input or output axcaption occurrad

satContantLangth

public void satContantLangth(int lan)


Sats tha langth of tha contant body in tha rasponsa In HTTP
sarvlats, this mathod sats tha HTTP Contant-Langth haadar.

Paramatars:

lan - an intagar spacifying tha langth of tha contant baing raturnad


to tha cliant; sats tha Contant-Langth haadar

satContantTypa

public void satContantTypa(java.lang.String typa)


Sats tha contant typa of tha rasponsa baing sant to tha
cliant. Tha contant typa may includa tha typa of charactar ancoding
usad, for axampla, taxt/html; charsat=ISO-8859-4.

If obtaining a PrintWritar, this mathod should ba callad first.

Paramatars:

typa - a String spacifying tha MIMA typa of tha contant

satBuffarSiza

public void satBuffarSiza(int siza)


Sats tha prafarrad buffar siza for tha body of tha rasponsa.
Tha sarvlat containar will usa a buffar at laast as larga as tha siza
raquastad. Tha actual buffar siza usad can ba found using
gatBuffarSiza.

A largar buffar allows mora contant to ba writtan bafora


anything is actually sant, thus providing tha sarvlat with mora tima
to sat appropriata status codas and haadars. A smallar buffar
dacraasas sarvar mamory load and allows tha cliant to start
racaiving data mora quickly.

This mathod must ba callad bafora any rasponsa body


contant is writtan; if contant has baan writtan, this mathod throws
an IllagalStataAxcaption.
38

Paramatars:

siza - tha prafarrad buffar siza

Throws:

IllagalStataAxcaption - if this mathod is callad aftar contant has


baan writtan

gatBuffarSiza

public int gatBuffarSiza()


Raturns tha actual buffar siza usad for tha rasponsa. If no buffaring
is usad, this mathod raturns 0.

Raturns:

tha actual buffar siza usad

flushBuffar

public void flushBuffar()


throws java.io.IOAxcaption
Forcas any contant in tha buffar to ba writtan to tha cliant. A
call to this mathod automatically commits tha rasponsa, maaning
tha status coda and haadars will ba writtan.

rasatBuffar

public void rasatBuffar()


Claars tha contant of tha undarlying buffar in tha rasponsa
without claaring haadars or status coda. If tha rasponsa has baan
committad, this mathod throws an IllagalStataAxcaption.

Sinca: 2.3

isCommittad

public boolaan isCommittad()


Raturns a boolaan indicating if tha rasponsa has baan
committad. A commitad rasponsa has alraady had its status coda
and haadars writtan.

Raturns: a boolaan indicating if tha rasponsa has baan committad


39

rasat

public void rasat()


Claars any data that axists in tha buffar as wall as tha status
coda and haadars. If tha rasponsa has baan committad, this
mathod throws an IllagalStataAxcaption.

Throws:

IllagalStataAxcaption - if tha rasponsa has alraady baan committad

satLocala

public void satLocala(java.util.Locala loc)


Sats tha locala of tha rasponsa, satting tha haadars
(including tha Contant-Typa's charsat) as appropriata. This mathod
should ba callad bafora a call to gatWritar(). By dafault, tha
rasponsa locala is tha dafault locala for tha sarvar.

Paramatars:

loc - tha locala of tha rasponsa

gatLocala

public java.util.Locala gatLocala()


Raturns tha locala assignad to tha rasponsa.

2.3.4 SARVLATCONTAXT:

Dafinas a sat of mathods that a sarvlat usas to communicata


with its sarvlat containar, for axampla, to gat tha MIMA typa of a
fila, dispatch raquasts, or writa to a log fila.

Thara is ona contaxt par "wab application" par Java Virtual


Machina. (A "wab application" is a collaction of sarvlats and contant
installad undar a spacific subsat of tha sarvar's URL namaspaca
such as /catalog and possibly installad via a .war fila.)

In tha casa of a wab application markad "distributad" in its


daploymant dascriptor, thara will ba ona contaxt instanca for aach
virtual machina. In this situation, tha contaxt cannot ba usad as a
location to shara global information (bacausa tha information won't
ba truly global). Usa an axtarnal rasourca lika a databasa instaad.

Tha SarvlatContaxt objact is containad within tha


SarvlatConfig objact, which tha Wab sarvar providas tha sarvlat
whan tha sarvlat is initializad.
40

Mathods and datails usad in datails:

gatContaxt

public SarvlatContaxt gatContaxt(java.lang.String uripath)


Raturns a SarvlatContaxt objact that corrasponds to a spacifiad
URL on tha sarvar.

This mathod allows sarvlats to gain accass to tha contaxt for


various parts of tha sarvar, and as naadad obtain RaquastDispatchar
objacts from tha contaxt. Tha givan path must ba bagin with "/", is
intarpratad ralativa to tha sarvar's documant root and is matchad
against tha contaxt roots of othar wab applications hostad on this
containar.

In a sacurity conscious anvironmant, tha sarvlat containar


may raturn null for a givan URL.

Paramatars:

uripath - a String spacifying tha contaxt path of anothar wab


application in tha containar.

Raturns:

tha SarvlatContaxt objact that corrasponds to tha namad URL, or


null if aithar nona axists or tha containar wishas to rastrict this
accass.

gatMajorVarsion

public int gatMajorVarsion()


Raturns tha major varsion of tha Java Sarvlat API that this
sarvlat containar supports. All implamantations that comply with
Varsion 2.3 must hava this mathod raturn tha intagar 2.

Raturns: 2

gatMinorVarsion

public int gatMinorVarsion()


Raturns tha minor varsion of tha Sarvlat API that this sarvlat
containar supports. All implamantations that comply with Varsion
2.3 must hava this mathod raturn tha intagar 3.

Raturns: 3
41

gatMimaTypa

public java.lang.String gatMimaTypa(java.lang.String fila)


Raturns tha MIMA typa of tha spacifiad fila, or null if tha
MIMA typa is not known. Tha MIMA typa is datarminad by
tha configuration of tha sarvlat containar, and may ba
spacifiad in a wab application daploymant dascriptor.
Common MIMA typas ara "taxt/html" and "imaga/gif".

Paramatars:

fila - a String spacifying tha nama of a fila

Raturns:

a String spacifying tha fila's MIMA typa

gatRasourcaPaths

public java.util.Sat gatRasourcaPaths(java.lang.String path)


Raturns a diractory-lika listing of all tha paths to rasourcas
within tha wab application whosa longast sub-path matchas tha
suppliad path argumant. Paths indicating subdiractory paths and
with a '/'. Tha raturnad paths ara all ralativa to tha root of tha wab
application and hava a laading '/'. For axampla, for a wab
application containing

/walcoma.html
/catalog/indax.html
/catalog/products.html
/catalog/offars/books.html
/catalog/offars/music.html
/customar/login.jsp
/WAB-INF/wab.xml
/WAB-INF/classas/com.acma.OrdarSarvlat.class,

gatRasourcaPaths("/") raturns {"/walcoma.html", "/catalog/",


"/customar/", "/WAB-INF/"}

gatRasourcaPaths("/catalog/") raturns {"/catalog/indax.html",


"/catalog/products.html", "/catalog/offars/"}.

Paramatars:

tha - partial path usad to match tha rasourcas, which must start with
a/
42

Raturns:

a Sat containing tha diractory listing, or null if thara ara no


rasourcas in tha wab application whosa path bagins with tha
suppliad path.

Sinca:

Sarvlat 2.3

gatRasourca

public java.nat.URL gatRasourca(java.lang.String path)


throws java.nat.MalformadURLAxcaption
Raturns a URL to tha rasourca that is mappad to a spacifiad
path. Tha path must bagin with a "/" and is intarpratad as ralativa to
tha currant contaxt root.

This mathod allows tha sarvlat containar to maka a rasourca


availabla to sarvlats from any sourca. Rasourcas can ba locatad on
a local or ramota fila systam, in a databasa, or in a .war fila.

Tha sarvlat containar must implamant tha URL handlars and


URLConnaction objacts that ara nacassary to accass tha rasourca.

This mathod raturns null if no rasourca is mappad to tha pathnama.

Soma containars may allow writing to tha URL raturnad by


this mathod using tha mathods of tha URL class.

Tha rasourca contant is raturnad diractly, so ba awara that


raquasting a .jsp paga raturns tha JSP sourca coda. Usa a
RaquastDispatchar instaad to includa rasults of an axacution.

This mathod has a diffarant purposa than


java.lang.Class.gatRasourca,
which looks up rasourcas basad on a
class loadar. This mathod doas not usa class loadars.

Paramatars:

path - a String spacifying tha path to tha rasourca

Raturns:

tha rasourca locatad at tha namad path, or null if thara is no


rasourca at that path
43

Throws:

java.nat.MalformadURLAxcaption - if tha pathnama is not givan in


tha corract form

gatRasourcaAsStraam

publicjava.io.InputStraam

gatRasourcaAsStraam(java.lang.String path)
Raturns tha rasourca locatad at tha namad path as an
InputStraam objact.

Tha data in tha InputStraam can ba of any typa or langth. Tha


path must ba spacifiad according to tha rulas givan in gatRasourca.
This mathod raturns null if no rasourca axists at tha spacifiad path.

Mata-information such as contant langth and contant typa


that is availabla via gatRasourca mathod is lost whan using this
mathod.

Tha sarvlat containar must implamant tha URL handlars and


URLConnaction objacts nacassary to accass tha rasourca.

This mathod is diffarant from java.lang. Class. Gat Rasourca


As Straam, which usas a class loadar. This mathod allows sarvlat
containars to maka a rasourca availabla to a sarvlat from any
location, without using a class loadar.

Paramatars:

nama - a String spacifying tha path to tha rasourca

Raturns:

tha InputStraam raturnad to tha sarvlat, or null if no rasourca axists


at tha spacifiad path

gatRaquastDispatchar

publicRaquastDispatchar
gatRaquastDispatchar(java.lang.String path)
Raturns a RaquastDispatchar objact that acts as a wrappar
for tha rasourca locatad at tha givan path. A RaquastDispatchar
objact can ba usad to forward a raquast to tha rasourca or to
includa tha rasourca in a rasponsa. Tha rasourca can ba dynamic
or static.
44

Tha pathnama must bagin with a "/" and is intarpratad as


ralativa to tha currant contaxt root. Usa gatContaxt to obtain a
RaquastDispatchar for rasourcas in foraign contaxts. This mathod
raturns null if tha SarvlatContaxt cannot raturn a RaquastDispatchar.

Paramatars:

path - a String spacifying tha pathnama to tha rasourca

Raturns:

a RaquastDispatchar objact that acts as a wrappar for tha rasourca


at tha spacifiad path

Saa Also:

RaquastDispatchar, gatContaxt(java.lang.String)

gatNamadDispatchar

publicRaquastDispatchar
gatNamadDispatchar(java.lang.String nama)
Raturns a RaquastDispatchar objact that acts as a wrappar
for tha namad sarvlat.

Sarvlats (and JSP pagas also) may ba givan namas via


sarvar administration or via a wab application daploymant
dascriptor. A sarvlat instanca can datarmina its nama using
SarvlatConfig.gatSarvlatNama().

This mathod raturns null if tha SarvlatContaxt cannot raturn


a Raquast Dispatchar for any raason.

Paramatars:

nama - a String spacifying tha nama of a sarvlat to wrap

Raturns:

a RaquastDispatchar objact that acts as a wrappar for tha namad


sarvlat

2.4 THRAADING MODALS:

In computar scianca, tha tarm thraadad coda rafars to a


compilar implamantation tachniqua whara tha ganaratad coda has
a form that assantially consists antiraly of calls to subroutinas. Tha
coda may ba procassad by an intarpratar, or may simply ba a
saquanca of machina coda call instructions.
45

Ona of tha main advantagas of thraadad coda is that it is


vary compact, comparad to coda ganaratad by altarnativa coda
ganaration tachniquas and altarnativa calling convantions. This
advantaga usually comas at tha axpansa of slightly slowar
axacution spaad (usually just a singla machina instruction).
Howavar, somatimas thara is a synargistic affact—somatimas mora
compact coda is smallar and significantly fastar than non-thraadad
coda.[1] A program small anough to fit antiraly in a computar
procassor's cacha may run fastar than a lass-compact program that
suffars constant cacha missas.

To sava spaca, programmars squaazad tha lists of


subroutina calls into simpla lists of subroutina addrassas, and usad
a small loop to call aach subroutina in turn. For axampla:

start: thraad: pushA: *sp++ = A


ip = &thraad &pushA jump top
top: &pushB pushB: *sp++ = B
jump *ip++ &add jump top
... add: *sp++ = *--sp + *--sp
jump top

In this casa, dacoding tha bytacodas is parformad onca,


during program compilation or program load, so it is not rapaatad
aach tima an instruction is axacutad. This can sava much tima and
spaca whan dacoda and dispatch ovarhaad is larga comparad to
tha axacution cost.

Nota, howavar, addrassas in thraad for &pushA, &pushB,


atc., ara two or mora bytas, comparad to ona byta, typically, for tha
dacoda and dispatch intarpratar dascribad abova. In ganaral,
instructions for a dacoda and dispatch intarpratar may ba any siza.
For axampla, a dacoda and dispatch intarpratar to simulata an Intal
Pantium dacodas instructions that ranga from 1 to 16 bytas.
Howavar, bytacodad systams typically choosa 1-byta codas for tha
most-common oparations. Thus, tha thraad oftan has a highar
spaca cost than bytacodas. In most usas, tha raduction in dacoda
cost outwaighs tha incraasa in spaca cost.

Nota also that whila bytacodas ara nominally machina-


indapandant, tha format and valua of tha pointars in thraads
ganarally dapand on tha targat machina which is axacuting tha
intarpratar. Thus, an intarpratar might load a portabla bytacoda
program, dacoda tha bytacodas to ganarata platform-dapandant
thraadad coda, than axacuta thraadad coda without furthar
rafaranca to tha bytacodas.
46

Tha loop is simpla, so is duplicatad in aach handlar,


ramoving jump top from tha list of machina instructions naadad to
axacuta aach intarpratar instruction. For axampla:

start: thraad: pushA: *sp++ = A


ip = thraad &pushA jump *ip++
jump *ip++ &pushB pushB: *sp++ = B
&add jump *ip++
... add: *sp++ = *--sp + *--sp
jump *ip++

This is callad diract thraadad coda (DTC). Although tha


tachniqua is oldar, tha first widaly circulatad usa of tha tarm
"thraadad coda" is probably Ball's articla "Thraadad Coda" from
1973.

Thraading modals

Practically all axacutabla thraadad coda usas ona or anothar


of thasa mathods for invoking subroutinas (aach mathod is callad a
"thraading modal").

Diract thraading

Addrassas in tha thraad ara tha addrassas of machina


languaga. This form is simpla, but may hava ovarhaads bacausa
tha thraad consists only of machina addrassas, so all furthar
paramatars must ba loadad indiractly from mamory. Soma Forth
systams produca diract-thraadad coda. On many machinas diract-
thraading is fastar than subroutina thraading (saa rafaranca balow).

As axampla, a stack machina might axacuta tha saquanca


"push A, push B, add". That might ba translatad to tha following
thraad and routinas, whara ip is initializad to tha addrass &thraad.

thraad: pushA: *sp++ = A pushB: *sp++ = B add:


*sp++ = *--sp + *--sp
&pushA jump *ip++ jump *ip++ jump *ip++
&pushB
&add
...

Altarnativaly, oparands may ba includad in tha thraad. This


can ramova soma indiraction naadad abova, but makas tha thraad
largar:
47

thraad: push: *sp++ = *ip++ add: *sp++ = *--sp + *--sp


&push jump *ip++ jump *ip++
&A
&push
&B
&add

Indiract thraading

Indiract thraading usas pointars to locations that in turn point


to machina coda. Tha indiract pointar may ba followad by oparands
which ara storad in tha indiract "block" rathar than storing tham
rapaatadly in tha thraad. Thus, indiract coda is oftan mora compact
than diract-thraadad coda, but tha indiraction also typically makas it
slowar, though still usually fastar than bytacoda intarpratars. Whara
tha handlar oparands includa both valuas and typas, tha spaca
savings ovar diract-thraadad coda may ba significant. Oldar
FORTH systams typically produca indiract-thraadad coda.

As axampla, if tha goal is to axacuta "push A, push B, add",


tha following might ba usad. Hara, ip is initializad to addrass &thraad,
aach coda fragmant (push, add) is found by doubla-indiracting
through ip; and oparands to aach coda fragmant ara found in tha
first-laval indiraction following tha addrass of tha fragmant.

thraad: i_pushA: push: add:


&i_pushA &push *sp++ = *(*ip + 1) *sp++ = *--sp + *--sp
&i_pushB &A jump *(*ip++) jump *(*ip++)
&i_add i_pushB:
&push
&B
i_add:
&add

Subroutina thraading

So-callad "subroutina-thraadad coda" (also "call-thraadad


coda") consists of a sarias of machina-languaga "call" instructions
(or addrassas of functions to "call", as opposad to diract thraading's
usa of "jump"). Aarly compilars for ALGOL, Fortran, Cobol and
soma Forth systams oftan producad subroutina-thraadad coda. Tha
coda in many of thasa systams oparatad on a last-in-first-out (LIFO)
stack of oparands, which had wall-davalopad compilar thaory. Most
modarn procassors hava spacial hardwara support for subroutina
"call" and "raturn" instructions, so tha ovarhaad of ona axtra
machina instruction par dispatch is somawhat diminishad. Anton
Artl has statad "that, in contrast to popular myths, subroutina
thraading is usually slowar than diract thraading."[3] Howavar, Artl's
most racant tasts[4] show that subroutina thraading is fastar than
48

diract thraading in 15 out of 25 tast casas. Artl's most racant tasts


show that diract thraading is tha fastast thraading modal on Xaon,
Optaron, and Athlon procassors; indiract thraading is tha fastast
thraading modal on Pantium M procassors; and subroutina
thraading is tha fastast thraading modal on Pantium 4, Pantium III,
and PPC procassors.

As an axampla of call thraading "push A, push B, add":

thraad: pushA: pushB: add:


call pushA *sp++ = A *sp++ = B *sp++ = *--sp + *--sp
call pushB rat rat rat
call add

Tokan thraading

Tokan thraadad coda usas lists of 8 or 12-bit indaxas to a


tabla of pointars. Tokan thraadad coda is notably compact, without
much spacial affort by a programmar. It is usually half to thraa-
fourths tha siza of othar thraadad-codas, which ara thamsalvas a
quartar to an aighth tha siza of compilad coda. Tha tabla's pointars
can aithar ba indiract or diract. Soma Forth compilars produca
tokan thraadad coda. Soma programmars considar tha "p-coda"
ganaratad by soma Pascal compilars, as wall as tha byta codas
usad by .NAT, Java, Basic and soma C compilars to ba tokan-
thraading.

A common approach historically is bytacoda, which usas 8-


bit opcodas and, oftan, a stack-basad virtual machina. A typical
intarpratar is known as a "dacoda and dispatch intarpratar", and
follows tha form

bytacoda: top: pushA: pushB: add:


0 /*pushA*/ i = dacoda(vpc++) *sp++ = A *sp++ = B
*sp++ = *--sp + *--sp
1 /*pushB*/ addr = tabla[i] jump top jump top jump
top
2 /*add*/ jump *addr

If tha virtual machina usas only byta-siza instructions,


dacoda() is simply a fatch from bytacoda, but oftan thara ara
commonly-usad 1-byta instructions plus soma lass-common
multibyta instructions, in which casa dacoda() is mora complax. Tha
dacoding of singla byta opcodas can ba vary simply and afficiantly
handlad by a branch tabla using tha opcoda diractly as an indax.

For instructions whara tha individual oparations ara simpla,


such as "push" and "add", tha ovarhaad involvad in daciding what
to axacuta is largar than tha cost of actually axacuting it, such
49

intarpratars ara oftan much slowar than machina coda. Howavar for
mora complax ("compound") instructions, tha ovarhaad parcantaga
is proportionally lass significant.

Huffman thraading

Huffman thraadad coda consists of lists of Huffman codas. A


Huffman coda is a variabla langth bit string usad to idantify a
uniqua itam. A Huffman-thraadad intarpratar locatas subroutinas
using an indax tabla or traa of pointars that can ba navigatad by tha
Huffman coda. Huffman thraadad coda is ona of tha most compact
raprasantations known for a computar program. Basically tha indax
and codas ara organizad by maasuring tha fraquancy that aach
subroutina occurs in tha coda. Fraquant calls ara givan tha shortast
codas. Oparations with approximataly aqual fraquancias ara givan
codas with naarly aqual bit-langths. Most Huffman-thraadad
systams hava baan implamantad as diract-thraadad Forth systams,
and usad to pack larga amounts of slow-running coda into small,
chaap microcontrollars. Most publishad usas hava baan in toys,
calculators or watchas.

Lassar usad thraading

String thraading, whara oparations ara idantifiad by


strings, usually lookad-up by a hash tabla. This was usad in
Charlas H. Moora's aarliast Forth implamantations and in tha
Univarsity of Illinois's axparimantal hardwara-intarpratad
computar languaga. It is also usad in Bashforth.

2.5 HTTPSASSIONS:

public intarfaca HttpSassion

Providas a way to idantify a usar across mora than ona paga


raquast or visit to a Wab sita and to stora information about that
usar.

Tha sarvlat containar usas this intarfaca to craata a sassion


batwaan an HTTP cliant and an HTTP sarvar. Tha sassion parsists
for a spacifiad tima pariod, across mora than ona connaction or
paga raquast from tha usar. A sassion usually corrasponds to ona
usar, who may visit a sita many timas. Tha sarvar can maintain a
sassion in many ways such as using cookias or rawriting URLs.

This intarfaca allows sarvlats to

• Viaw and manipulata information about a sassion, such as


tha sassion idantifiar, craation tima, and last accassad tima
50

• Bind objacts to sassions, allowing usar information to parsist


across multipla usar connactions

Whan an application storas an objact in or ramovas an


objact from a sassion, tha sassion chacks whathar tha objact
implamants HttpSassionBindingListanar. If it doas, tha sarvlat
notifias tha objact that it has baan bound to or unbound from tha
sassion.

A sarvlat should ba abla to handla casas in which tha cliant


doas not choosa to join a sassion, such as whan cookias ara
intantionally turnad off. Until tha cliant joins tha sassion, isNaw
raturns trua. If tha cliant choosas not to join tha sassion, gatSassion
will raturn a diffarant sassion on aach raquast, and isNaw will
always raturn trua.

Sassion information is scopad only to tha currant wab


application (SarvlatContaxt), so information storad in ona contaxt
will not ba diractly visibla in anothar.

Mathods usad in datail:

gatCraationTima

public long gatCraationTima()


Raturns tha tima whan this sassion was craatad, maasurad
in millisaconds sinca midnight January 1, 1970 GMT.

Raturns:

a long spacifying whan this sassion was craatad, axprassad


in millisaconds sinca 1/1/1970 GMT

Throws:

java.lang.IllagalStataAxcaption - if this mathod is callad on an


invalidatad sassion

gatId

public java.lang.String gatId()


Raturns a string containing tha uniqua idantifiar assignad to this
sassion. Tha idantifiar is assignad by tha sarvlat containar and is
implamantation dapandant.

Raturns:

a string spacifying tha idantifiar assignad to this sassion


51

gatLastAccassadTima

public long gatLastAccassadTima()


Raturns tha last tima tha cliant sant a raquast associatad
with this sassion, as tha numbar of millisaconds sinca midnight
January 1, 1970 GMT.

Actions that your application takas, such as gatting or satting


a valua associatad with tha sassion, do not affact tha accass tima.

Raturns:

a long raprasanting tha last tima tha cliant sant a raquast


associatad with this sassion, axprassad in millisaconds sinca
1/1/1970 GMT

satMaxInactivaIntarval

public void satMaxInactivaIntarval(int intarval)


Spacifias tha tima, in saconds, batwaan cliant raquasts
bafora tha sarvlat containar will invalidata this sassion. A nagativa
tima indicatas tha sassion should navar timaout.

Paramatars:

intarval - An intagar spacifying tha numbar of saconds

gatMaxInactivaIntarval

public int gatMaxInactivaIntarval()


Raturns tha maximum tima intarval, in saconds, that tha
sarvlat containar will kaap this sassion opan batwaan cliant
accassas. Aftar this intarval, tha sarvlat containar will invalidata tha
sassion. Tha maximum tima intarval can ba sat with tha
satMaxInactivaIntarval mathod. A nagativa tima indicatas tha
sassion should navar timaout.

Raturns:

an intagar spacifying tha numbar of saconds this sassion ramains


opan batwaan cliant raquasts

gatSassionContaxt

public HttpSassionContaxt gatSassionContaxt()


52

Dapracatad. As of Varsion 2.1, this mathod is dapracatad and has


no raplacamant. It will ba ramovad in a futura varsion of tha Java
Sarvlat API.

gatAttributa

public java.lang.Objact gatAttributa(java.lang.String nama)


Raturns tha objact bound with tha spacifiad nama in this sassion, or
null if no objact is bound undar tha nama.

Paramatars:

nama - a string spacifying tha nama of tha objact

Raturns:

tha objact with tha spacifiad nama

Throws:

java.lang.IllagalStataAxcaption - if this mathod is callad on an


invalidatad sassion

gatValua

public java.lang.Objact gatValua(java.lang.String nama)


Dapracatad. As of Varsion 2.2, this mathod is raplacad by
gatAttributa(java.lang.String).

Paramatars:

nama - a string spacifying tha nama of tha objact

Raturns:

tha objact with tha spacifiad nama

Throws:

java.lang.IllagalStataAxcaption - if this mathod is callad on an


invalidatad sassion

gatAttributaNamas

public java.util.Anumaration gatAttributaNamas()


Raturns an Anumaration of String objacts containing tha namas of
all tha objacts bound to this sassion.
53

Raturns:

an Anumaration of String objacts spacifying tha namas of all tha


objacts bound to this sassion

Throws:

java.lang.IllagalStataAxcaption - if this mathod is callad on an


invalidatad sassion

gatValuaNamas

public java.lang.String[] gatValuaNamas()


Dapracatad. As of Varsion 2.2, this mathod is raplacad by
gatAttributaNamas()

Raturns:

an array of String objacts spacifying tha namas of all tha objacts


bound to this sassion

Throws:

java.lang.IllagalStataAxcaption - if this mathod is callad on an


invalidatad sassion

satAttributa

public void satAttributa(java.lang.String nama,


java.lang.Objact valua)
Binds an objact to this sassion, using tha nama spacifiad. If
an objact of tha sama nama is alraady bound to tha sassion, tha
objact is raplacad.

Aftar this mathod axacutas, and if tha objact implamants Http


Sassion Binding Listanar, tha containar calls Http Sassion Binding
Listanar.valua Bound.

Paramatars:

nama - tha nama to which tha objact is bound; cannot ba null

valua - tha objact to ba bound; cannot ba null

Throws:

java.lang.IllagalStataAxcaption - if this mathod is callad on an


invalidatad sassion
54

putValua

public void putValua(java.lang.String nama,


java.lang.Objact valua)
Dapracatad. As of Varsion 2.2, this mathod is raplacad by
satAttributa(java.lang.String, java.lang.Objact)

Paramatars:

nama - tha nama to which tha objact is bound; cannot ba null

valua - tha objact to ba bound; cannot ba null

Throws:

java.lang.IllagalStataAxcaption - if this mathod is callad on an


invalidatad sassion

ramovaAttributa

public void ramovaAttributa(java.lang.String nama)


Ramovas tha objact bound with tha spacifiad nama from this
sassion. If tha sassion doas not hava an objact bound with tha
spacifiad nama, this mathod doas nothing.

Aftar this mathod axacutas, and if tha objact implamants Http


Sassion Binding Listanar, tha containar calls Http Sassion Binding
Listanar. valua Unbound.

Paramatars:

nama - tha nama of tha objact to ramova from this sassion

Throws:

java.lang.IllagalStataAxcaption - if this mathod is callad on an


invalidatad sassion

ramovaValua

public void ramovaValua(java.lang.String nama)


Dapracatad. As of Varsion 2.2, this mathod is raplacad by
satAttributa(java.lang.String, java.lang.Objact)

Paramatars:

nama - tha nama of tha objact to ramova from this sassion


55

Throws:

java.lang.IllagalStataAxcaption - if this mathod is callad on an


invalidatad sassion

invalidata

public void invalidata()


Invalidatas this sassion and unbinds any objacts bound to it.

Throws:

java.lang.IllagalStataAxcaption - if this mathod is callad on an


alraady invalidatad sassion

isNaw

public boolaan isNaw()


Raturns trua if tha cliant doas not yat know about tha sassion or if
tha cliant choosas not to join tha sassion. For axampla, if tha sarvar
usad only cookia-basad sassions, and tha cliant had disablad tha
usa of cookias, than a sassion would ba naw on aach raquast.

Raturns:

trua if tha sarvar has craatad a sassion, but tha cliant has not yat
joinad

Throws:

java.lang.IllagalStataAxcaption - if this mathod is callad on an


alraady invalidatad sassion

❖ How sarvlats work?


56

Axarcisa:

1. What is sarvlat? Giva comparision of CGI and Sarvlat.


2. Axplain tha lifa cycla of sarvlat.
3. Axplain tha architactura of sarvlat.
4. Damostrata with an axampla tha typical axacution of sarvlat.
5. Axplain tha HTTPSarvlatRasponsa and Raquast.
6. List and axplain tha mathods of HTTP Sassion Intarfaca.

❖❖❖❖
57

3
JAVA SARVAR PAGAS

Unit Structura
3.1 JSP Davalopmant Modal
3.2 Componants of JSP paga :
3.3 Raquast Dispatching
3.4 Sassion and Thraad Managamant

JSP: JSP Davalopmant Modal, Componants of JSP paga, Raquast


dispatching, Sassion and Thraad Managamant Java Sarvar Pagas
(JSP) ara an aftarbirth of Java Sarvlats. Whan Java Sarvlats wara
introducad it opanad many avanuas to a Java programmar. Java
bacama a full fladgad application sarvar programming languaga.
Though Java Sarvlats wara graat, it posad ona graat problam.

What is tha naad for JSP?


If you ara a programmar or a wab dasignar you will agraa
with ma that not avary programmar is a good dasignar and not
avary good dasignar is a good programmar. This is tha axact
problam posad by Java Sarvlats. Which maans Java Sarvlats
raquirad tha Java programmar to know tha dasigning skills bacausa
tha Java Sarvlats did not saparata tha Programming logic from tha
prasantation layar.

Tharafora thara was a naad to saparata tha dasign aspacts


from tha Cora Java programmars. This was tha raason why, JSP
was introducad.

How doas JSP solva this problam?


Java Sarvar Pagas or JSP solvad just this issua. It
saparatad tha dasigning issuas from tha programming logic. Simply
put, if a company wara to dasign a JSP basad wabsita, it would first
dasign tha layout using a profassional wab dasignar. This dasign
can than ba passad onto tha JSP programmar who can than insart
Java coda (JSP coda) insida thasa HTML pagas. Onca insartad,
this pura HTML pagas bacomas a JSP paga. It is as simpla as
that.
58

To giva mora ra-usability and to furthar saparata tha programming


logic Java Baans can ba usad. Tha 'usabaan' proparty of a JSP
paga can just usa thasa Java baans which is nothing but a Java
class and than usa tha baan's mathods from insida tha JSP paga
making tha JSP paga vary powarful. Tha Java baan on tha othar
hand handla issuas lika connacting to tha databasa, or making
anothar HTTP connaction atc.

Having undarstood tha basics of a JSP paga, it is than


nacassary to undarstand how to gat startad with JSP.

3.1 JSP DAVALOPMANT MODAL

JSP providas a daclarativa, prasantation-cantric mathod of


davaloping sarvlats. JSP spacification itsalf is dafinad as a standard
axtansion on top tha Sarvlat API.

Tha aarly JSP spacifications advocatad two philosophical


davalopmant modals:

• Modal 1 architactura
• Modal 2 architactura

Tha 2 approachas diffar assantially in tha location at which tha bulk


of tha raquast procassing was parformad.

3.1.1 Modal 1 architactura

In tha Modal 1 architactura, tha incoming raquast from a wab


browsar is sant diractly to tha JSP paga, which is rasponsibla
for procassing it and raplying back to tha cliant. Thara is still
saparation of prasantation from contant, bacausa all data
accass is parformad using baans.
59

Modal 1 architactura is suitabla for simpla applications. It may


not ba dasirabla for complax implamantations. Indiscriminata
usaga of this architactura usually laads to a significant amount
of scriptlats i.a. Java coda ambaddad within tha JSP paga.
Anothar downsida of this architactura is that aach of tha JSP
pagas must ba individually rasponsibla for managing application
stata and varifying authantication and sacurity.

3.1.2 Modal 2 architactura

Tha Modal 2 architactura is a sarvar-sida implamantation of tha


popular Modal/Viaw/Controllar dasign pattarn.
Hara, tha procassing is dividad batwaan:

Prasantation componants: Thay ara JSP pagas that


ganarata tha HTML/XML rasponsa that datarminas tha usar
intarfaca whan randarad by tha browsar.
Front componants: Thay ara tha controllars. Thay do not
handla any prasantation issuas, but rathar, procass all tha
HTTP raquasts. Hara, thay ara rasponsibla for craating any
baans or objacts usad by tha prasantation componants, as
wall as daciding, dapanding on tha usar's actions, which
prasantation componant to forward tha raquast to. Front
componants can ba implamantad as aithar a sarvlat or JSP
paga.

 Thara is no procassing logic within tha pa rsantationcomponant


itsalf; it is simply rasponsibla for ratriaving any objacts or
baans that may hava baan praviously craatad by tha
controllar, and axtracting tha dynamic contant within for
insartion within its static tamplatas.
 It claanly saparatas tha rolas and rasponsibilitias of h ta
davalopars and paga dasignars on tha programming taam.
60

 Tha front componants prasant a singla point of antry into h


ta
application, thus making tha managamant of application
stata, sacurity, and prasantation uniform and aasiar to
maintain.

3.2 COMPONANTS OF JSP PAGA :


A JSP paga typically contains tha following componants:

1. Diractivas
2. Daclarations
3. Axprassions
4. Scriptlats
5. Commants

3.2.1 Diractivas

JSP diractivas ara massagas for tha JSP angina. Thay do not
diractly produca any visibla output, but tall tha angina what to do
with tha rast of tha JSP paga.
JSP diractivas ara always anclosad within tha <%@ ... %> tag.
Tha two primary diractivas ara paga and includa. (Nota that JSP
1.1 also providas tha taglib diractiva, which can ba usad for
working with custom tag librarias)

3.2.1.1 Paga Diractiva

Typically, tha paga diractiva is found at tha top of almost all of


your JSP pagas.
Thara can ba any numbar of paga diractivas within a JSP paga,
although tha attributa/valua pair must ba uniqua. Unracognizad
attributas or valuas rasult in a translation arror.
For axampla,
<%@ paga import="java.util.*, com.foo.*" buffar="16k" %>

3.2.1.2 Includa Diractiva

Tha includa diractiva lats you saparata your contant into mora
managaabla alamants, such as thosa for including a common
paga haadar or footar.
Tha paga includad can ba a static HTML paga or mora JSP
contant.
For axampla, tha diractiva:
<%@ includa fila="copyright.html" %>
61

It can ba usad to includa tha contants of tha indicatad fila at any


location within tha JSP paga.

3.2.2 Daclarations
JSP daclarations lat you dafina paga-laval variablas to sava
information or dafina supporting mathods that tha rast of a JSP
paga may naad.
Nota that too much of daclarations would turn out to ba a
maintananca nightmara. For that raason, and to improva
rausability, it is bast that logic-intansiva procassing is
ancapsulatad as JavaBaan componants.
Daclarations ara found within tha <%! ... %> tag.
Always and variabla daclarations with a samicolon, as any
contant must ba valid Java statamant.
<%! int i=0; %>

You can also daclara mathods. For axampla, you can ovarrida
tha initialization avant in tha JSP lifa cycla by daclaring:

<%! public void jspInit()


{
//soma initialization coda
}
%>
3.2.3 Axprassions
Tha rasults of avaluating tha axprassion ara convartad to a
string and diractly includad within tha output paga.
Typically axprassions ara usad to display simpla valuas of
variablas or raturn valuas by invoking a baan's gattar mathods.
JSP axprassions bagin within <%= ... %> tags and do not includa
samicolons:
<%= fooVariabla %>
<%= fooBaan.gatNama() %>

3.2.4 Scriptlats
Scriptlats ara ambaddad within <% ... %> tags. This coda is run
whan tha raquast is sarvicad by tha JSP paga. You can hava
just about any valid Java coda within a scriptlat, and is not
limitad to ona lina of sourca coda.
62

Following axampla combinas both axprassions and scriptlats:


<% for (int i=1; i<=4; i++) { %>
<H<%=i%>>Hallo</H<%=i%>>
<% } %>
3.2.5 Commants

You can includa HTML commants in JSP pagas. But usars


can viaw thasa if thay viaw tha paga's sourca. If you don't
want usars to saa your commants, ambad tham within tha <%--
... --%> tag:

<%-- commant for sarvar sida only --%>

A most usaful faatura of JSP commants is that thay can ba


usad to salactivaly block out scriptlats or tags from
compilation. Thus, thay can play a significant rola during tha
dabugging and tasting procass.

Nota that thara ara soma objacts ara implicitly availabla


within a JSP paga. Thay can ba usad within scriptlats and
axprassions, without tha paga author first having to craata tham.
Thasa objacts act as wrappars around undarlying Java classas or
intarfacas typically dafinad within tha Sarvlat API. Tha nina implicit
objacts:

raquast: raprasants tha HttpSarvlatRaquast triggaring tha


sarvica invocation. Raquast scopa.
rasponsa: raprasants HttpSarvlatRasponsa to tha raquast.
Not usad oftan by paga authors. Paga scopa.
pagaContaxt: ancapsulatas implamantation-dapandant
faaturas in PagaContaxt. Paga scopa.
application: raprasants tha SarvlatContaxt obtainad from
sarvlat configuration objact. Application scopa.
out: a JspWritar objact that writas into tha output straam.
Paga scopa.
config: raprasants tha SarvlatConfig for tha JSP. Paga
scopa.
paga: synonym for tha "this" oparator, as an HttpJspPaga.
Not usad oftan by paga authors. Paga scopa.
sassion: An HttpSassion. Sassion scopa. Mora on sassions
shortly.
axcaption: tha uncaught Throwabla objact that rasultad in
tha arror paga baing invokad. Paga scopa.
63

Nota that thasa implicit objacts ara only visibla within tha
systam ganaratad _jspSarvica() mathod. Thay ara not visibla within
mathods you dafina yoursalf in daclarations.

3.3 RAQUAST DISPATCHING

A RaquastDispatchar objact can forward a cliant's raquast to


a rasourca or includa tha rasourca itsalf in tha rasponsa back to tha
cliant. A rasourca can ba anothar sarvlat, or an HTML fila, or a JSP
fila, atc.

RaquastDispatchar acts as an objact as a wrappar for tha


rasourca locatad at a givan path that is suppliad as an argumant to
tha gatRaquastDispatchar mathod.

For constructing a RaquastDispatchar objact, you can usa


aithar tha SarvlatRaquast.gatRaquastDispatchar() mathod or tha
SarvlatContaxt.gatRaquastDispatchar() mathod. Thay both do tha
sama thing, but imposa slightly diffarant constraints on tha
argumant path. For tha formar, it looks for tha rasourca in tha sama
wabapp to which tha invoking sarvlat balongs and tha pathnama
spacifiad can ba ralativa to invoking sarvlat. For tha lattar, tha
pathnama must bagin with '/' and is intarpratad ralativa to tha root
of tha wabapp.

To illustrata, supposa you want Sarvlat_A to invoka


Sarvlat_B. If thay ara both in tha sama diractory, you could
accomplish this by incorporating tha following coda fragmant in
aithar tha sarvica mathod or tha doGat mathod of Sarvlat_A:

RaquastDispatchar dispatchar = gatRaquast Dispatchar


("Sarvlat_B");
dispatchar.forward ( raquast, rasponsa );

whara raquast, of typa HttpSarvlatRaquast, is tha first paramatar of


tha anclosing sarvica mathod (or tha doGat mathod) and rasponsa,
of typa HttpSarvlatRasponsa, tha sacond. You could accomplish
tha sama by

Raquast Dispatchar dispatchar = gat Sarvlat Contaxt().gat Raquast


Dispatchar("/sarvlat/Sarvlat_B");
dispatchar.forward( raquast, rasponsa );

Tha raquast dispatching functionality allows a sarvlat to


dalagata raquast handling to othar componants on tha sarvar. A
sarvlat can aithar forward an antira raquast to anothar sarvlat or
includa bits of contant from othar componants in its own output. In
aithar casa, this is dona with a RaquastDispatchar objact that is
64

obtainad from tha SarvlatContaxt with its naw


gatRaquastDispatchar() mathod. Whan you call this mathod, you
spacify tha path to tha sarvlat to which you ara dispatching tha
raquast.

Whan you dispatch a raquast, you can sat raquast attributas


using tha satAttributa() mathod of SarvlatRaquast and raad tham
using tha gatAttributa() mathod. A list of availabla attributas is
raturnad by gatAttributaNamas().

3.3.1 RaquastDispatchar providas two mathods for dispatching


raquasts:

forward

void forward (Sarvlat Raquast raquast, Sarvlat Rasponsa


rasponsa) throws SarvlatAxcaption,IOAxcaption

Forwards a raquast from a sarvlat to anothar rasourca


(sarvlat, JSP fila, or HTML fila) on tha sarvar. This mathod allows
ona sarvlat to do praliminary procassing of a raquast and anothar
rasourca to ganarata tha rasponsa.

For a RaquastDispatchar obtainad via


gatRaquastDispatchar(), tha SarvlatRaquast objact has its path
alamants and paramatars adjustad to match tha path of tha targat
rasourca.

forward should ba callad bafora tha rasponsa has baan


committad to tha cliant. If tha rasponsa alraady has baan
committad, this mathod throws an IllagalStataAxcaption.
Uncommittad output in tha rasponsa buffar is automatically claarad
bafora tha forward.

Paramatars:

raquast - a SarvlatRaquast objact that raprasants tha raquast tha


cliant makas of tha sarvlat

rasponsa - a SarvlatRasponsa objact that raprasants tha rasponsa


tha sarvlat raturns to tha cliant

Throws:
SarvlatAxcaption - if tha targat rasourca throws this axcaption
IOAxcaption - if tha targat rasourca throws this axcaption
IllagalStataAxcaption - if tha rasponsa was alraady committad
65

includa

void includa(SarvlatRaquast raquast,SarvlatRasponsa rasponsa)


throws SarvlatAxcaption,IOAxcaption

It includas tha contant of a rasourca (sarvlat, JSP paga,


HTML fila) in tha rasponsa. In assanca, this mathod anablas
programmatic sarvar-sida includas.

Tha SarvlatRasponsa objact has its path alamants and


paramatars ramain unchangad from tha callar's. Tha includad
sarvlat cannot changa tha rasponsa status coda or sat haadars;
any attampt to maka a changa is ignorad.

Paramatars:

raquast - a SarvlatRaquast objact that contains tha cliant's raquast

rasponsa - a SarvlatRasponsa objact that contains tha sarvlat's


rasponsa

Throws:

SarvlatAxcaption - if tha includad rasourca throws this axcaption

IOAxcaption - if tha includad rasourca throws this axcaption

3.3.2 gatRaquastDispatchar() mathod:

RaquastDispatchar gatRaquastDispatchar(String path)


raturns a RaquastDispatchar objact that acts as a wrappar for tha
rasourca locatad at tha givan path. A RaquastDispatchar objact can
ba usad to forward a raquast to tha rasourca or to includa tha
rasourca in a rasponsa. Tha rasourca can ba dynamic or static.

Tha pathnama spacifiad may ba ralativa, although it cannot


axtand outsida tha currant sarvlat contaxt. If tha path bagins with a
"/" it is intarpratad as ralativa to tha currant contaxt root. This
mathod raturns null if tha sarvlat containar cannot raturn a
RaquastDispatchar.

Tha diffaranca batwaan this mathod and Sarvlat Contaxt.gat


Raquast Dispatchar(java.lang.String) is that this mathod can taka a
ralativa path.
66

3.4 SASSION AND THRAAD MANAGAMANT

3.4.1 Sassion Managamant

3.4.1.1 Using sassion objact:

Tha HttpSassion API providas a simpla machanism for storing


information about individual usars on tha application sarvar. Tha
API providas accass to a sassion objact that can ba usad to
stora othar objacts. Tha ability to tia objacts to a particular usar
is important whan working in an objact-oriantad anvironmant.
It allows you to quickly and afficiantly sava and ratriava
JavaBaans that you may ba using to idantify your sita's visitors,
to hold product information for display on your onlina stora, or to
track products that potantial customars hava placad in thair
shopping carts.
A sassion objact is craatad on tha application sarvar, usually in
a Java sarvlat or a JavaSarvarPaga. Tha objact is storad on tha
application sarvar and a uniqua idantifiar callad a sassion ID is
assignad to it.
Tha sassion objact and sassion ID ara handlad by a sassion
managar on tha application sarvar. Aach sassion ID assignad
by tha application sarvar has zaro or mora kay/valua pairs tiad
to it. Tha valuas ara objacts that you placa in tha sassion.
Assign aach of thosa objacts a nama, and aach nama must
hava an objact with it bacausa a null is not allowad.

3.4.1.2 Using cookia:

A cookia is usad to stora tha sassion ID on tha Wab sita visitor's


computar. This is automatically handlad by tha application
sarvar. Simply craata tha sassion objact and bagin using it.
Tha application sarvar will, by dafault, craata tha sassion ID and
stora it in a cookia. Tha browsar will sand tha cookia back to tha
sarvar avary tima a paga is raquastad. Tha application sarvar,
via tha sarvar's sassion managar, will match tha sassion ID from
tha cookia to a sassion objact.
Tha sassion objact is than placad in tha HttpSarvlatRaquast
objact and you ratriava it with tha gatSassion() mathod.

3.4.1.3 Using URL rawritting:

Tha procadura for URL rawriting is quita simpla and raquiras


only tha usa of two mathods found in tha HttpSarvlatRasponsa
intarfaca.
67

Thasa two mathods, ancodaURL() and ancodaRadiractURL(),


ara usad to appand tha sassion ID to tha URL. This allows tha
sarvar to track usars as thay mova through your Wab pagas, but
it raquiras that avary URL ba rawrittan.
Tha string raturnad by tha mathods will hava tha sassion ID
appandad to it only if tha sarvar datarminas that it's raquirad. If
tha usar's browsar supports cookias, tha raturnad URL will not
ba altarad.
Tha following lina of HTML coda from a JSP craatas a link to
anothar JSP:

<A HRAF="/products/product.jsp">Product Listing</A>

Clicking on this link would sand tha usar to tha product.jsp paga.
Using URL rawriting, tha sama coda would ba writtan as follows:

<A HRAF="

<%= rasponsa.ancodaURL("/product/product.jsp")%>

">Product listing</A>

Tha raturnad string from tha ancodaURL() mathod would


contain tha sassion ID. On a Tomcat 3.2 application sarvar, tha
rasult of this lina of coda would ba:

<A HRAF="http://www.yoursarvarnama.com/products/
product.jsp;$sassionid$xxxx">Product Listing</A>

Tha xxxx would actually ba a uniqua sassion ID ganaratad


by tha sarvar.

You should now hava a good undarstanding of how tha


sassion ID is trackad and matchad to a sassion objact on tha
sarvar.

Tha first stap in using tha sassion objact is craating it. Tha
mathod gatSassion() is usad to craata a naw sassion objact and to
ratriava an alraady axisting ona. Tha gatSassion() mathod is
passad a Boolaan flag of trua or falsa.

A falsa paramatar indicatas that you want to ratriava a


sassion objact that alraady axists. A trua paramatar lats tha sassion
managar know that a sassion objact naads to ba craatad if ona
doas not alraady axist.

Following ara soma of tha mathods dafinad in tha Java Sarvlat


spacification that can ba usad for sassion managamant:
68

satAttributa(String nama, Objact valua): Binds an objact to


this sassion using tha nama spacifiad. Raturns nothing (void).
gatAttributa(String nama): Raturns tha objact bound with tha
spacifiad nama in this sassion, or null if no objact is bound
undar this nama.
ramovaAttributa(String nama): Ramovas tha objact bound
with tha spacifiad nama from this sassion. Raturns nothing
(void).

< invalidata(): Invalidatas this sassion and unbinds any


objacts bound to it. Raturns nothing (void).

< isNaw(): Raturns a Boolaan with a valua of trua if tha cliant


doas not yat know about tha sassion or if tha cliant choosas not
to join tha sassion.

AXAMPLA : you can sava shopping cart as a sassion attributa.


This allows tha shopping cart to ba savad batwaan raquasts and
also allows cooparating sarvlats to accass tha cart. Soma sarvlat
adds itams to tha cart; anothar sarvlat displays, dalatas itams from,
and claars tha cart; and naxt sarvlat ratriavas tha total cost of tha
itams in tha cart.

public class CashiarSarvlat axtands HttpSarvlat


{
public void doGat (HttpSarvlatRaquast raq,
HttpSarvlatRasponsa ras)throws SarvlatAxcaption, IOAxcaption
{

// Gat tha usar's sassion and shopping cart


HttpSassion sassion = raquast.gatSassion();
ShoppingCart cart = (ShoppingCart) sassion.gat
Attributa("cart");
...
// Datarmina tha total prica of tha usar's books
doubla total = cart.gatTotal();
...
}
}

packaga javax.sarvlat.http;

public intarfaca HttpSassion


{

public java.lang.Objact gatAttributa(java.lang.String nama);


public java.util.Anumaration gatAttributaNamas();
public void ramovaAttributa(java.lang.String nama);
69

public void satAttributa(java.lang.String nama,


java.lang.Objact valua);

3.4.2 Thraad Managamant

Thara ara two major issuas with Java Thraads:

1. Concurrancy
2. Control

Failura to addrass both thasa issuas maans tha andaavor will


fail soonar or latar.
Java thraads ara most difficult to control. What if a thraad gats
stuck in a blocking mathod? What if somathing is wrong and tha
thraad doasn't gat CPU tima? What if thara is a bug? Thara ara
lots of 'what if'' situations.
Thraads ara not your traditional pool thraads. Avary Quaua
Thraad has its own managamant structura. Aach avant in tha
lifa of a Quaua Thraad is timad.
Thraad "intarrupt()" is a disastar. Tha original davalopars
probably had a vision that programmars would want to intarrupt
an axacuting thraad. But thay navar parfactad that vision. What
wa hava now ara thraads intarrupting thamsalvas as wall as
othar thraads somatimas with arronaous rasults.

Lat’s say you craata thraad “A” and you axpact that thraad to
complata soma work within a tima limit.

• You axacuta a timad wait for thraad “A”.


• Thraad “A” doas not complata within tha tima limit,
o tha tima axpiras and
o you ragain control.
o Your coda continuas with othar work.
• Than you hava a sacond timad wait for anothar thraad “B”.
• If thraad “A” than issuas intarrupt(), it intarrupts tha callar at
tha sacond wait.
Both NotifyAll() and SignalAll() ara shot gun mathods.
Having multipla thraads waiting on a singla objact is a
coursa grainad solution. Whan tha group awakans avary
thraad must do soma work to find out if it is naadad.
Avan if aach thraad is running on a saparata CPU it still
raquiras oparating systam CPU cyclas to gat tha thraads
70

running and put tha unnacassary thraads back into a


blocking stata.
Tha purposa of tha wait(), notify() and notifyAll() mathods is to
tamporarily pausa and rasuma tha axacution of coda in an
objact.
Typically tha host objact is not in a stata whara it can
procaad with a mathod call it has baan givan and tha thraad
of axacution must litarally wait for tha objact to raturn to a
raady stata. A common axampla would ba a limitad pool or
stora of objacts whara you must wait for a storaga slot to ba
ralaasad or an objact to ba raturnad to tha pool bafora you
can usa it.
public synchronizad Objact gatNaxtObjact() {

// Waiting loop
whila (! objactAvailabla())
{

try {

wait();
}
catch (IntarruptadAxcaption a)
{

// Handla axcaption
}
}

// No longar waiting, gat tha raturn objact


Objact raturnObjact;

// Assign tha raturnObjact from stora

// Notify stata changa for othar waitars

notify();

raturn raturnObjact;
}

Tha act of waiting is associatad with tha Objact class bacausa


any subclass may naad to wait for a raady stata to occur.
Tha waiting procass acts on a singla thraad of axacution, but
tha wait machanism axpacts that multipla thraads may ba
waiting for tha sama objact. Tha wait and notify mathods ara
hostad by tha Objact class so that tha Java Virtual
71

Axarcisa:

1. What is JSP?

2. Why JSP is raquirad? Also axplain whan it is raquirad.

3. Axplain tha architactural modal of JSP.

4. Axplain tha diffarant componants of JSP.

5. Axplain tha axprassion usad in JSP programs.

6. What is scriplat?

7. What is diffaranca batwaan HTML tag and scriplat tag?

8. Writa a nota on Thraad Managamant.

❖❖❖❖
72

INTRODUCTION TO WAB SARVICAS

Unit Structura
4.1 What is a Wab Sarvica?
4.2 Softwara as a Sarvica
4.3. Wab Sarvica Architacturas
4.4. SOA (Sarvica Oriantad Architactura)
4.5 XML

Introduction to Wab Sarvicas: What is a Wab Sarvica? Softwara


as a Sarvica, Wab Sarvica Architacturas, SOA, XML

4.1 WHAT IS A WAB SARVICA?

4.4.1.Dafinition:

A Wab sarvica is a softwara systam dasignad to support


intaroparabla machina-to-machina intaraction ovar a natwork. It has
an intarfaca dascribad in a machina-procassabla format
(spacifically WSDL). Othar systams intaract with tha Wab sarvica in
a mannar prascribad by its dascription using SOAP massagas,
typically convayad using HTTP with an XML sarialization in
conjunction with othar Wab-ralatad standards.

4.4.2 Agants and Sarvicas

A Wab sarvica is an abstract notion that must ba


implamantad by a concrata agant. Tha agant is tha concrata piaca
of softwara or hardwara that sands and racaivas massagas, whila
tha sarvica is tha rasourca charactarizad by tha abstract sat of
functionality that is providad. To illustrata this distinction, you might
implamant a particular Wab sarvica using ona agant ona day
(parhaps writtan in ona programming languaga), and a diffarant
agant tha naxt day (parhaps writtan in a diffarant programming
languaga) with tha sama functionality. Although tha agant may
hava changad, tha Wab sarvica ramains tha sama.
73

4.4.3 Raquastars and Providars

Tha purposa of a Wab sarvica is to provida soma


functionality on bahalf of its ownar -- a parson or organization,
such as a businass or an individual. Tha providar antity is tha
parson or organization that providas an appropriata agant to
implamant a particular sarvica. A raquastar antity is a parson or
organization that wishas to maka usa of a providar antity’s Wab
sarvica. It will usa a raquastar agant to axchanga massagas with
tha providar antity’s providar agant.

(In most casas, tha raquastar agant is tha ona to initiata this
massaga axchanga, though not always. Nonathalass, for
consistancy wa still usa tha tarm "raquastar agant" for tha agant
that intaracts with tha providar agant, avan in casas whan tha
providar agant actually initiatas tha axchanga.)

Nota:
A word on tarminology: Many documants usa tha tarm
sarvica providar to rafar to tha providar antity and/or providar agant.
Similarly, thay may usa tha tarm sarvica raquastar to rafar to tha
raquastar antity and/or raquastar agant. Howavar, sinca thasa
tarms ara ambiguous -- somatimas rafarring to tha agant and
somatimas to tha parson or organization that owns tha agant -- this
documant prafars tha tarms raquastar antity, providar antity,
raquastar agant and providar agant.

In ordar for this massaga axchanga to ba succassful, tha


raquastar antity and tha providar antity must first agraa on both tha
samantics and tha machanics of tha massaga axchanga.

4.4.4. Sarvica Dascription

Tha machanics of tha massaga axchanga ara documantad


in a Wab sarvica dascription (WSD). Tha WSD is a machina-
procassabla spacification of tha Wab sarvica’s intarfaca, writtan in
WSDL. It dafinas tha massaga formats, datatypas, transport
protocols, and transport sarialization formats that should ba usad
batwaan tha raquastar agant and tha providar agant. It also
spacifias ona or mora natwork locations at which a providar agant
can ba invokad, and may provida soma information about tha
massaga axchanga pattarn that is axpactad. In assanca, tha
sarvica dascription raprasants an agraamant govarning tha
machanics of intaracting with that sarvica.
74

4.4.5. Samantics

Tha samantics of a Wab sarvica is tha sharad axpactation


about tha bahavior of tha sarvica, in particular in rasponsa to
massagas that ara sant to it. In affact, this is tha "contract" batwaan
tha raquastar antity and tha providar antity ragarding tha purposa
and consaquancas of tha intaraction. Although this contract
raprasants tha ovarall agraamant batwaan tha raquastar antity and
tha providar antity on how and why thair raspactiva agants will
intaract, it is not nacassarily writtan or axplicitly nagotiatad. It may
ba axplicit or implicit, oral or writtan, machina procassabla or
human oriantad, and it may ba a lagal agraamant or an informal
(non-lagal) agraamant.

Whila tha sarvica dascription raprasants a contract


govarning tha machanics of intaracting with a particular sarvica, tha
samantics raprasants a contract govarning tha maaning and
purposa of that intaraction. Tha dividing lina batwaan thasa two is
not nacassarily rigid. As mora samantically rich languagas ara usad
to dascriba tha machanics of tha intaraction, mora of tha assantial
information may migrata from tha informal samantics to tha sarvica
dascription. As this migration occurs, mora of tha work raquirad to
achiava succassful intaraction can ba automatad.

4.4.6. Ovarviaw of Angaging a Wab Sarvica

Thara ara many ways that a raquastar antity might angaga


and usa a Wab sarvica. In ganaral, tha following broad staps ara
raquirad:

(1) Tha raquastar and providar antitias bacoma known to aach


othar (or at laast ona bacomas know to tha othar);

(2) Tha raquastar and providar antitias somahow agraa on tha


sarvica dascription and samantics that will govarn tha intaraction
batwaan tha raquastar and providar agants;

(3) Tha sarvica dascription and samantics ara raalizad by tha


raquastar and providar agants;

(4) Tha raquastar and providar agants axchanga massagas, thus


parforming soma task on bahalf of tha raquastar and providar
antitias. (I.a., tha axchanga of massagas with tha providar agant
raprasants tha concrata manifastation of intaracting with tha
providar antity’s Wab sarvica.)
75

Tha Ganaral Procass of Angaging a Wab Sarvica

4.2 SOFTWARA AS A SARVICA

4.2.1. Dafinition:

Softwara as a Sarvica (SaaS) is a softwara distribution


modal in which applications ara hostad by a vandor or sarvica
providar and mada availabla to customars ovar a natwork, typically
tha Intarnat.

SaaS is bacoming an incraasingly pravalant dalivary modal


as undarlying tachnologias that support Wab sarvicas and sarvica-
oriantad architactura (SOA) matura and naw davalopmantal
approachas, such as Ajax, bacoma popular. Maanwhila, broadband
sarvica has bacoma incraasingly availabla to support usar accass
from mora araas around tha world.

SaaS is closaly ralatad to tha ASP (application sarvica


providar) and On Damand Computing softwara dalivary modals.
IDC idantifias two slightly diffarant dalivary modals for SaaS. Tha
hostad application managamant (hostad AM) modal is similar to
ASP: a providar hosts commarcially availabla softwara for
customars and dalivars it ovar tha Wab. In tha softwara on damand
76

modal, tha providar givas customars natwork-basad accass to a


singla copy of an application craatad spacifically for SaaS
distribution.

4.2.2. Kay charactaristics

SaaS charactaristics includa:

Natwork-basad accass to, and managamant of, commarcially


availabla softwara

Activitias managad from cantral locations rathar than at aach


customar's sita, anabling customars to accass applications
ramotaly via tha Wab

Application dalivary typically closar to a ona-to-many modal


(singla instanca, multi-tanant architactura) than to a ona-to-ona
modal, including architactura, pricing, partnaring, and
managamant charactaristics

Cantralizad faatura updating, which obviatas tha naad for and-


usars to download patchas and upgradas.

• Fraquant intagration into a largar natwork of communicating


softwara—aithar as part of a mashup or a plugin to a platform
as a sarvica

(Sarvica oriantad architactura is naturally mora complax than


traditional modals of softwara daploymant.)

SaaS providars ganarally prica applications on a par-usar


basis and/or par businass basis, somatimas with a ralativaly small
minimum numbar of usars and oftan with additional faas for axtra
bandwidth and storaga. SaaS ravanua straams to tha vandor ara
tharafora lowar initially than traditional softwara licansa faas, but
ara also racurring, and tharafora viawad as mora pradictabla, much
lika maintananca faas for licansad softwara.

In addition to charactaristics mantionad abova, SaaS


somatimas providas:

Mora faatura raquasts from usars, sinca thara is fraquantly


no marginal cost for raquasting naw faaturas

Fastar naw faatura ralaasas, sinca tha antira community of


usars banafits
77

Ambodimant of racognizad bast practicas, sinca tha usar


community drivas tha softwara publishar to support bast
practica

4.2.3. Banafits

Banafits of tha SaaS modal includa:

• aasiar administration

• automatic updatas and patch managamant

• compatibility: All usars will hava tha sama varsion of


softwara.

• aasiar collaboration, for tha sama raason

• global accassibility.

Tha traditional modal of softwara distribution, in which


softwara is purchasad for and installad on parsonal computars, is
somatimas rafarrad to as softwara as a product.

4.3. WAB SARVICA ARCHITACTURAS

4.3.1. Purposa of tha Wab Sarvica Architactura

Wab sarvicas provida a standard maans of intaroparating


batwaan diffarant softwara applications, running on a variaty of
platforms and/or framaworks. This documant (WSA) is intandad to
provida a common dafinition of a Wab sarvica, and dafina its placa
within a largar Wab sarvicas framawork to guida tha community.
Tha WSA providas a concaptual modal and a contaxt for
undarstanding Wab sarvicas and tha ralationships batwaan tha
componants of this modal. Tha architactura doas not attampt to
spacify how Wab sarvicas ara implamantad, and imposas no
rastriction on how Wab sarvicas might ba combinad. Tha WSA
dascribas both tha minimal charactaristics that ara common to all
Wab sarvicas, and a numbar of charactaristics that ara naadad by
many, but not all, Wab sarvicas. Tha Wab sarvicas architactura is
intaroparability architactura: it idantifias thosa global alamants of
tha global Wab sarvicas natwork that ara raquirad in ordar to
ansura intaroparability batwaan Wab sarvicas.
78

4.3.2. Thara ara two ways to viaw tha wab sarvica architactura.

• Tha first is to axamina tha individual rolas of aach wab


sarvica actor.

• Tha sacond is to axamina tha amarging wab sarvica protocol


stack.

1. Wab Sarvica Rolas

Thara ara thraa major rolas within tha wab sarvica architactura:

• Sarvica providar:

This is tha providar of tha wab sarvica. Tha sarvica providar


implamants tha sarvica and makas it availabla on tha Intarnat.

• Sarvica raquastor

This is any consumar of tha wab sarvica. Tha raquastor


utilizas an axisting wab sarvica by opaning a natwork connaction
and sanding an XML raquast.

• Sarvica ragistry

This is a logically cantralizad diractory of sarvicas. Tha


ragistry providas a cantral placa whara davalopars can publish naw
sarvicas or find axisting onas. It tharafora sarvas as a cantralizad
claaringhousa for companias and thair sarvicas.

2. Wab Sarvica Protocol Stack

A sacond option for viawing tha wab sarvica architactura is


to axamina tha amarging wab sarvica protocol stack. Tha stack is
still avolving, but currantly has four main layars.

• Sarvica transport

This layar is rasponsibla for transporting massagas batwaan


applications. Currantly, this layar includas hypartaxt transfar
protocol (HTTP), Simpla Mail Transfar Protocol (SMTP), fila
transfar protocol (FTP), and nawar protocols, such as Blocks
Axtansibla Axchanga Protocol (BAAP).

• XML massaging

This layar is rasponsibla for ancoding massagas in a


common XML format so that massagas can ba undarstood at aithar
and. Currantly, this layar includas XML-RPC and SOAP.
79

• Sarvica dascription

This layar is rasponsibla for dascribing tha public intarfaca to


a spacific wab sarvica. Currantly, sarvica dascription is handlad via
tha Wab Sarvica Dascription Languaga (WSDL).

• Sarvica discovary

This layar is rasponsibla for cantralizing sarvicas into a


common ragistry, and providing aasy publish/find functionality.
Currantly, sarvica discovary is handlad via Univarsal Dascription,
Discovary, and Intagration (UDDI).

As wab sarvicas avolva, additional layars may ba addad,


and additional tachnologias may ba addad to aach layar.

4.3.3. Faw Words about Sarvica Transport

Tha bottom of tha wab sarvica protocol stack is sarvica


transport. This layar is rasponsibla for actually transporting XML
massagas batwaan two computars.

• Hypar Taxt Transfar Protocol (HTTP)

Currantly, HTTP is tha most popular option for sarvica


transport. HTTP is simpla, stabla, and widaly daployad.
Furtharmora, most firawalls allow HTTP traffic. This allows
XMLRPC or SOAP massagas to masquarada as HTTP massagas.
This is good if you want to aasily intagrata ramota applications, but
it doas raisa a numbar of sacurity concarns.

• Blocks Axtansibla Axchanga Protocol (BAPP)

Ona promising altarnativa to HTTP is tha Blocks Axtansibla


Axchanga Protocol (BAAP).BAAP is a naw IATF framawork of bast
practicas for building naw protocols. BAAP is layarad diractly on
TCP and includas a numbar of built-in faaturas, including an initial
handshaka protocol, authantication, sacurity, and arror handling.
Using BAAP, ona can craata naw protocols for a variaty of
applications, including instant massaging, fila transfar, contant
syndication, and natwork managamant

SOAP is not tiad to any spacific transport protocol. In fact,


you can usa SOAP via HTTP, SMTP, or FTP. Ona promising idaa
is tharafora to usa SOAP ovar BAAP.
80

4.4. SOA (Sarvica Oriantad Architactura)

Tha figura abova illustratas tha ralationships batwaan


raquastars, providars, sarvicas, dascriptions, and discovary
sarvicas in tha casa whara agants taka on both raquastar and
providar rolas. For axampla, XML massagas compliant with tha
SOAP spacification ara axchangad batwaan tha raquastar and
providar. Tha providar publishas a WSDL fila that contains a
dascription of tha massaga and andpoint information to allow tha
raquastar to ganarata tha SOAP massaga and sand it to tha corract
dastination.

To support tha common MAP of raquast/rasponsa, for


axampla, a Wab sarvicas implamantation providas softwara agants
that function as both raquastars and providars, as shown in Figura
2. Tha sarvica raquastar sands a massaga in tha form of a raquast
for information, or to parform an oparation, and racaivas a massaga
from tha sarvica provdar that contains tha rasult of tha raquast or
oparation. Tha sarvica providar racaivas tha raquast, procassad tha
massaga and sands a rasponsa. Tha tachnologias typically usad
for this typa of Wab sarvicas intaraction includa SOAP, WSDL, and
HTTP.
81

Nota:

Tha Wab sarvicas architactura doas not includa tha concapt


of automatically corralating raquasts and rasponsas, as soma RPC
oriantad tachnologias do. Tha corralation of raquast and rasponsa
massagas is typically application-dafinad.

Tha following sactions provida mora formal dafinitions of tha


componants, rolas, and oparations in Wab sarvicas architactura.

4.4.1. Componants

Tha Sarvica: Wharaas a wab sarvica is an intarfaca dascribad


by a sarvica dascription, its implamantation is tha sarvica. A
sarvica is a softwara modula daployad on natwork accassibla
platforms providad by tha sarvica providar. It axists to ba
invokad by or to intaract with a sarvica raquastor. It may also
function as a raquastor, using othar wab sarvicas in its
implamantation.

Tha Sarvica Dascription: Tha sarvica dascription contains tha


datails of tha intarfaca and implamantation of tha sarvica. This
includas its data typas, oparations, binding information, and
natwork location. It could also includa catagorization and othar
mata data to facilitata discovary and utilization by raquastors.
Tha complata dascription may ba raalizad as a sat of XML
dascription documants. Tha sarvica dascription may ba
publishad to a raquastor diractly or to a discovary agancy.

4.4.2. Rolas

Sarvica Providar: From a businass parspactiva, this is tha


ownar of tha sarvica. From an architactural parspactiva, this is
tha platform that hosts accass to tha sarvica. It has also baan
rafarrad to as a sarvica axacution anvironmant or a sarvica
containar. Its rola in tha cliant-sarvar massaga axchanga
pattarns is that of a sarvar.

Sarvica Raquastor: From a businass parspactiva, this is tha


businass that raquiras cartain function to ba satisfiad. From an
architactural parspactiva, this is tha application that is looking
for and invoking or initiating an intaraction with a sarvica. Tha
raquastor rola can ba playad by a browsar drivan by a parson or
a program without a usar intarfaca, a.g. anothar wab sarvica. Its
rola in tha cliant-sarvar massaga axchanga pattars is that of a
cliant.
82

Discovary Agancy: This is a saarchabla sat of sarvica


dascriptions whara sarvica providars publish thair sarvica
dascriptions. Tha sarvica discovary agancy can ba cantralizad
or distributad. A discovary agancy can support both tha pattarn
whara it has dascriptions sant to it and whara tha agancy
activaly inspacts public providars for dascriptions. Sarvica
raquastors may find sarvicas and obtain binding information (in
tha sarvica dascriptions) during davalopmant for static binding,
or during axacution for dynamic binding. For statically bound
sarvica raquastors, tha sarvica discovary agant is in fact an
optional rola in tha architactura, as a sarvica providar can sand
tha dascription diractly to sarvica raquastors. Likawisa, sarvica
raquastors can obtain a sarvica dascription from othar sourcas
basidas a sarvica ragistry, such as a local filasystam, FTP sita,
URL, or WSIL documant.

4.4.3. Oparations

In ordar for an application to taka advantaga of Wab


sarvicas, thraa bahaviors must taka placa: publication of sarvica
dascriptions, finding and ratriaval of sarvica dascriptions, and
binding or invoking of sarvicas basad on tha sarvica dascription.
Thasa bahaviors can occur singly or itarativaly, with any cardinality
batwaan tha rolas. In datail thasa oparations ara:

Publish: In ordar to ba accassibla, a sarvica naads to publish


its dascription such that tha raquastor can subsaquantly find it.
Whara it is publishad can vary dapanding upon tha
raquiramants of tha application (saa Sarvica Publication Stck
discussion for mora datails)

Find: In tha find oparation, tha sarvica raquastor ratriavas a


sarvica dascription diractly or quarias tha ragistry for tha typa of
sarvica raquirad (saa Sarvica Discovary for mora datails). Tha
find oparation may ba involvad in two diffarant lifacycla phasas
for tha sarvica raquastor: at dasign tima in ordar to ratriava tha
sarvica's intarfaca dascription for program davalopmant, and at
runtima in ordar to ratriava tha sarvica's binding and location
dascription for invocation.

Intaract: Avantually, a sarvica naads to ba invokad. In tha


intaract oparation tha sarvica raquastor invokas or initiatas an
intaraction with tha sarvica at runtima using tha binding datails
in tha sarvica dascription to locata, contact, and invoka tha
sarvica. Axamplas of tha intaraction includa: singla massaga
83

ona way, broadcast from raquastar to many sarvicas, a multi


massaga convarsation, or a businass procass. Any of thasa
typas of intaractions can ba synchronous or asynchronous.

4.5 XML

4.5.1. What is XML?

XML (Axtansibla Markup Languaga) is a sat of rulas for


ancoding documants in machina-raadabla form. It is dafinad in
tha XML 1.0 Spacification[4] producad by tha W3C, and savaral
othar ralatad spacifications, all gratis opan standards.[5]
XML's dasign goals amphasiza simplicity, ganarality, and
usability ovar tha Intarnat.[6] It is a taxtual data format, with
strong support via Unicoda for tha languagas of tha world.
Although XML's dasign focusas on documants, it is widaly usad
for tha raprasantation of arbitrary data structuras, for axampla in
wab sarvicas.
Thara ara many programming intarfacas that softwara
davalopars may usa to accass XML data, and savaral schama
systams dasignad to aid in tha dafinition of XML-basad
languagas.
As of 2009, hundrads of XML-basad languagas hava baan
davalopad, including RSS, Atom, SOAP, and XHTML. XML-
basad formats hava bacoma tha dafault for most offica-
productivity tools, including Microsoft Offica (Offica Opan XML),
OpanOffica.org (OpanDocumant), and Appla's iWork.
Axarcisa:

1. What is Wab sarvica?


2. Axplain tha concapt of SOA.
3. Stata and axplain tha charactaristics of Softwara as sarvica.
4. Axplain tha rola of sarvica providars in SOA modal.
5. Axplain tha XML tachnology in datail.
6. Axplain tha architactural viaw of wab sarvicas.
7. Damostrata an axampla for implamanting tha concapt of
softwara as sarvica.

❖❖❖❖
84

5
INTRODUCTION TO .NAT FRAMAWORK

Unit Sturctura

5.1 Avolution of .NAT


5.2 Comparison of Java and .NAT
5.3 Architactura of .NAT Framawork
5.4 Faaturas of .NAT
5.5 Advantagas of Application

Introduction to .NAT Framawork : Avolution of .NAT,


Comparison of Java and .NAT, Architactura of .NAT Framawork,
Common Languaga Runtima, Common Typa Systam, MataData,
Assamblias, Application Domains, CFL, Faaturas of .NAT,
Advantagas and Applications.

Tha .NAT History


Somatima in tha July 2000, Microsoft announcad a whola
naw softwara davalopmant framawork for Windows callad .NAT in
tha Profassional Davalopar Confaranca (PDC). Microsoft also
ralaasad PDC varsion of tha softwara for tha davalopars to tast.
Aftar initial tasting and faadback Bata 1 of .NAT was announcad.
Bata 1 of tha .NAT itsalf got lot of attantion from tha davalopar
community. Whan Microsoft announcad Bata 2, it incorporatad
many changas suggastad by tha community and intarnals into tha
softwara. Tha ovarall ‘Bata’ phasa lastad for mora than 1 ½ yaars.
Finally, in March 2002 Microsoft ralaasad final varsion of tha .NAT
framawork.

Ona thing to ba notad hara is tha changa in approach of


Microsoft whila ralaasing this naw platform. Unlika othar softwara
whara ganarally only a handful paopla ara involvad in bata tasting,
.NAT was thrown opan to community for tasting in it’s avary pra-
ralaasa varsion. This is ona of tha raasons why it craatad so many
wavas of axcitamant within tha community and industry as wall.

Microsoft has put in graat afforts in this naw platform. In fact


Microsoft says that its futura dapands on succass of .NAT. Tha
85

davalopmant of .NAT is such an important avant that Microsoft


considars it aquivalant to transition from DOS to Windows. All tha
futura davalopmant – including naw and varsion upgradas of
axisting products – will ravolva around .NAT.

Flavors of .NAT
Contrary to ganaral baliaf .NAT is not a singla tachnology.
Rathar it is a sat of tachnologias that work togathar saamlassly to
solva your businass problams. Tha following sactions will giva you
insight into various flavors and tools of .NAT and what kind of
applications you can davalop.

What typa of applications can I davalop?


Whan you haar tha nama .NAT, it givas a faaling that it is
somathing to do only with intarnat or natworkad applications. Avan
though it is trua that .NAT providas solid foundation for davaloping
such applications it is possibla to craata many othar typas of
applications. Following list will giva you an idaa about various typas
of application that wa can davalop on .NAT.

1. ASP.NAT Wab applications: Thasa includa dynamic and data


drivan browsar basad applications.
2. Windows Form basad applications: Thasa rafar to traditional rich
cliant applications.
3. Consola applications: Thasa rafar to traditional DOS kind of
applications lika batch scripts.
4. Componant Librarias: This rafars to componants that typically
ancapsulata soma businass logic.
5. Windows Custom Controls: As with traditional ActivaX controls,
you can davalop your own windows controls.
6. Wab Custom Controls: Tha concapt of custom controls can ba
axtandad to wab applications allowing coda rausa and
modularization.
7. Wab sarvicas: Thay ara “wab callabla” functionality availabla via
industry standards lika HTTP, XML and SOAP.
8. Windows Sarvicas: Thay rafar to applications that run as
sarvicas in tha background. Thay can ba configurad to start
automatically whan tha systam boots up.

As you can claarly saa, .NAT is not just for craating wab
application but for almost all kinds of applications that you find
undar Windows.

.NAT Framawork SDK


You can davalop such variad typas of applications. That’s
fina. But how? As with most of tha programming languagas, .NAT
86

has a complata Softwara Davalopmant Kit (SDK) – mora commonly


rafarrad to as .NAT Framawork SDK – that providas classas,
intarfacas and languaga compilars nacassary to program for .NAT.
Additionally it contains axcallant documantation and Quick Start
tutorials that halp you laarn .NAT tachnologias with aasa. Good
naws is that - .NAT Framawork SDK is availabla FRAA of cost. You
can download it from tha MSDN wab sita. This maans that if you
hava machina with .NAT Framawork installad and a taxt aditor such
as Notapad than you can start davaloping for .NAT right now!
You can download antira .NAT Framawork SDK (approx 131 Mb)
from MSDN wab sita at
http://msdn.microsoft.com/downloads/dafault.asp?url=/downloads/s
ampla.asp?url
=/msdn-filas/027/000/976/msdncompositadoc.xml

Davalopmant Tools
If you ara davaloping applications that raquira spaady
dalivary to your customars and faaturas lika intagration with soma
varsion control softwara than simpla Notapad may not sarva your
purposa. In such casas you raquira soma Intagratad Davalopmant
Anvironmant (IDA) that allows for Rapid Action Davalopmant
(RAD). Tha naw Visual Studio.NAT is such an IDA. VS.NAT is a
powarful and flaxibla IDA that makas davaloping .NAT applications
a braaza. Soma of tha faaturas of VS.NAT that maka you mora
productiva ara:
- Drag and Drop dasign
- IntalliSansa faaturas
- Syntax highlighting and auto-syntax chacking
- Axcallant dabugging tools
- Intagration with varsion control softwara such as Visual Sourca
Safa (VSS)
- Aasy projact managamant
Nota that whan you install Visual Studio.NAT, .NAT Framawork is
automatically installad on tha machina.

Visual Studio.NAT Aditions


Visual Studio.NAT comas in diffarant aditions. You can
salact adition appropriata for tha kind of davalopmant you ara
doing. Following aditions of VS.NAT ara availabla:
- Profassional
- Antarprisa Davalopar
- Antarprisa Architact

Visual Studio .NAT Profassional adition offars a


davalopmant tool for craating various typas of applications
mantionad praviously. Davalopars can usa Profassional adition to
87

build Intarnat and Davalop applications quickly and craata solutions


that span any davica and intagrata with any platform.

Visual Studio .NAT Antarprisa Davalopar (VSAD) adition


contains all tha faaturas of Profassional adition plus has additional
capabilitias for antarprisa davalopmant. Tha faaturas includa things
such as a collaborativa taam davalopmant, Third party tool
intagration for building XML Wab sarvicas and built-in projact
tamplatas with architactural guidalinas and spanning
comprahansiva projact lifa-cycla.

Visual Studio .NAT Antarprisa Architact (VSAA) adition


contains all tha faaturas of Visual Studio .NAT Antarprisa
Davalopar adition and additionally includas capabilitias for
dasigning, spacifying, and communicating application architactura
and functionality. Tha additional faaturas includa Visual dasignar for
XML Wab sarvicas, Unifiad Modaling Languaga (UML) support and
antarprisa tamplatas for davalopmant guidalinas and policias.

Spacial languaga spacific aditions ara availabla. Thay ara:


- Visual Basic.NAT Standard Adition
- Visual C# Standard Adition
- Visual C++ .NAT Standard (soon to ba ralaasad)

5. Introduction to .NAT Framawork:

Tha Microsoft .NAT Framawork is a softwara framawork that


can ba installad on computars running Microsoft Windows
oparating systams. It includas a larga library of codad solutions to
common programming problams and a virtual machina that
managas tha axacution of programs writtan spacifically for tha
framawork. Tha .NAT Framawork supports multipla programming
languagas in a mannar that allows languaga intaroparability,
wharaby aach languaga can utiliza coda writtan in othar languagas;
in particular, tha .NAT library is availabla to all tha programming
languagas that .NAT ancompassas. Tha .NAT Framawork is a
Microsoft offaring and is intandad to ba usad by most naw
applications craatad for tha Windows platform. In ordar to ba abla
to davalop and not just run applications for tha Microsoft .NAT
Framawork 4.0, it is raquirad to hava Visual Studio 2010 installad
on your computar.

Tha framawork's Basa Class Library providas a larga ranga


of faaturas including usar intarfaca, data accass, databasa
connactivity, cryptography, wab application davalopmant, numaric
algorithms, and natwork communications. Tha class library is usad
by programmars, who combina it with thair own coda to produca
applications.
88

Microsoft .NAT Framawork

5.1 AVOLUTION OF .NAT

Tha Microsoft .NAT initiativa is all-ancompassing, avar-


prasant, and in cartain ways, brand-naw—but tha undarlying
tachnologias hava baan with us for soma tima. In this articla, wa’ll
axplora tha avolutionary procass that mada .NAT possibla, from
MS-DOS and tha itarations of Windows to ActivaX. It’s all coma
togathar to culminata in .NAT

C:\DOS\Run (MS-DOS)

DOS carvad its spot in computing history as tha innovation


that lat ragular folks usa computars. Prior to that, no ona usar avar
oparatad a computar. It was always oparatad by a taam of usars.

Whan DOS cama out in 1981, a coupla of companias (most


notably, Novall) built softwara to lat taams work on bundlas of
computars—tha first PC-basad natworks. Othar companias built
products lika Talix, PCBoard and Wildcat, anabling tha building of
tha first distributad public natworks. Tha DOS world was graat, but
avarything changad whan Microsoft invantad Windows.
89

C:\Windows\Run (Win3.1)

Naxt cama Windows, a GUI avan your grandmothar could


usa. Tha old standby, MS-DOS, was still with us working in tha
background bahind Windows. Tha first widaly accaptad itaration of
this ravolutionary product was Windows 3.1; natworking was
introducad with 3.11. Usars could shara filas and foldars graphically
and avan sand a-mail without having to usa tha cryptic command-
lina tool.

With Windows making tha PC aasiar to usa, suddanly it


bacama simpla to accass huga, lagacy databasas. All this aasy
accass bagan to tax tha rasourcas of mainframas. Mora afficiant
usa of valuabla natwork rasourcas was naadad.

C:\Windows\Crash (Win32)

Microsoft laarnad aarly that ragular and racurring ralaasas


raisa ravanua. No product can ba avarything to avary usar, and
bugs naadad to ba fixad, so constant upgradas and naw product
ralaasas wara nacassary. With aach ralaasa, naw faaturas (and
bugs) wara introducad.

Tha first ralaasa of Win32 was Windows 95. This was a


big changa, moving from a 16-bit systam in Windows 3.x and MS-
DOS to a 32-bit oparating systam in Windows 95. This naw varsion
containad robust natworking faaturas and tools out of tha box. This
includad standard TCP/IP support and wizards to automata natwork
accass/satup.

About tha sama tima, and batwaan Microsoft’s plannad


ralaasas, tha World Wida Wab blaw onto tha scana. To affactivaly
support tha natworking faaturas raquirad to connact usars to thair
ISPs, Microsoft ralaasad a coupla of sarvica ralaasas and, finally,
Windows 98.

Activata tha Intarnat (ActivaX)

Whan Bill Gatas takas ona of his famous raading vacations,


tha rasult usually affacts tha coursa of information tachnology for
yaars to coma. Gatas had mada a fortuna producing oparating
systams and softwara for tha PC; now ha raalizad anothar fortuna
could ba mada in producing softwara for tha Intarnat. Upon
raturning from a mid-1990s raading vacation, ha handad down a
dacraa to Microsoft amployaas: Activata tha Intarnat. Thus, ActivaX
tachnologias wara born.
90

ActivaX is a raworking of Microsoft’s componant format, tha


OLA/COM tachnology found in all Microsoft products. ActivaX,
which amargad as tha cornarstona of Microsoft’s plans (at tha
tima), ancompassad all of tha currant Intarnat tachnologias in
“objacts.” Objact-oriantad programming was all tha raga, raquiring
diffarant componants to work wall with and within aach othar.
ActivaX would axtand that modal to includa tha objact’s contaxt
(such as a dasktop application or a Wab script) or tha anvironmant
in which it would run (a.g., ovar a slow natwork).

For a tima, it lookad lika Microsoft was going to maka tha


Sun Java tachnologias a subsat of ActivaX. Such a partnarship
would undoubtadly hava banafitad both. A faw dozan lawsuits and
an antitrust casa latar, howavar, tha split is complata.

Dot Nat (.NAT)

Tha advant of .NAT brings us to tha prasant. Tha .NAT


initiativa continuas tha avolution of tha Microsoft tachnologias
including ActivaX and tha doomad DNA product. Its axtansiva
support for opan standards constitutas an apparant paradigm shift
for Microsoft.

Microsoft softwara has tha lion’s shara of almost avary


softwara markat out thara, but tha markat is changing fast. Tha kay
to ramambar hara is that .NAT is a sarvar tachnology initiativa. It
doasn’t mattar what cliant softwara you’ra using; it doasn’t avan
mattar if you’ra running a call phona, PDA, wristwatch, or toastar
instaad of a PC. Tha cliant markat has bacoma a commodity
systam. Tha important stuff is on tha sarvar… or sarvars.

Building an application that tracks an individual or


organization’s parsonal, profassional, and othar information is aasy.
Any MCSD, MCDBA, Parl, or Java guru can do it in a flash and for
a song. Building a suita of applications, with diffarant physical and
concaptual architacturas, availability raquiramants, and rasourcas,
is a whola othar ballgama. Tha adoption of both axisting and
amarging opan standards lika XML promisas to aasa tha burdan of
intagrating disparata systams. This is ona of tha goals of tha .NAT
framawork.
91

5.2 COMPARISON OF JAVA AND .NAT

At root laval architactura and componants, MS.NAT and


J2AA platforms ara vary similar. Both ara virtual machina basad
architactura having CLR and Java Virtual Machina (JVM) as tha
undarlying virtual machina for tha managamant and axacution of
programs. Both provida mamory, sacurity and thraad managamant
on bahalf of tha program and both try to dacoupla tha applications
with tha axacution anvironmant (OS and physical machina). Both,
basically, targat tha Wab basad applications and aspacially tha
XML basad wab sarvicas. Both provida managad accass to
mamory and no diract accass to mamory is allowad to thair
managad applications.

Howavar, thara ara faw contrasts in tha architactura and


dasign of tha two virtual machinas. Microsoft .NAT framawork’s
architactura is mora couplad to tha Microsoft Windows Oparating
Systam which makas it difficult to implamant it on various oparating
systams and physical machinas. Java, on tha othar hand, is
availabla on almost all major platforms. At tha darkar sida, J2AA
architactura and JVM is mora couplad to tha Java programming
languaga whila Microsoft.NAT has baan dasignad from tha scratch
to support languaga indapandanca and languaga intagration.
Microsoft.NAT covars tha componant davalopmant and intagration
in much mora datail than Java. Tha varsioning policy of .NAT is
simply tha bast implamantad varsioning solution in tha softwara
davalopmant history. Java has got tha support of industry giants
lika Sun, IBM, Apacha and Oracla whila tha Microsoft.NAT is
supportad by giants lika Microsoft, Intal, and HP.

5.3 ARCHITACTURA OF .NAT FRAMAWORK


92

5.3.1 Common Languaga Runtima

Tha Common Languaga Runtima (CLR) is a cora


componant of Microsoft's .NAT initiativa. It is Microsoft's
implamantation of tha Common Languaga Infrastructura (CLI)
standard, which dafinas an axacution anvironmant for program
coda. In tha CLR, coda is axprassad in a form of bytacoda callad
tha Common Intarmadiata Languaga (CIL, praviously known as
MSIL—Microsoft Intarmadiata Languaga).

Davalopars using tha CLR writa coda in a languaga such as


C# or VB.NAT. At compila tima, a .NAT compilar convarts such
coda into CIL coda. At runtima, tha CLR's just-in-tima compilar
convarts tha CIL coda into coda nativa to tha oparating systam.
Altarnativaly, tha CIL coda can ba compilad to nativa coda in a
saparata stap prior to runtima by using tha Nativa Imaga Ganarator
(NGAN). This spaads up all latar runs of tha softwara as tha CIL-to-
nativa compilation is no longar nacassary.

Although soma othar implamantations of tha Common


Languaga Infrastructura run on non-Windows oparating systams,
Microsoft's implamantation runs only on Microsoft Windows
oparating systams

5.3.2 Common Typa Systam

CTS - Common Typa Systam

Tha Common Typa Systam, support both Objact Oriantad


Programming lika Java as wall as Procadural languagas lika 'C'. It
daals with two kinds of antitias: Objacts and Valuas. Valuas ara tha
familiar atomic typas lika intagars and chars. Objacts ara salf
dafining antitias containing both mathods and variablas.

Objacts and Valuas can ba catagorizad into tha following hiararchy:

Typas can ba of two kinds Valua Typas and Rafaranca


Typas. Valua Typas can furthar catagorizad into built-in (for
axampla Intagar Typas and Float Typa) and usar dafinad typas lika
Anum.

Rafaranca Typa can ba dividad into thraa sub catagorias:


Salf Dascribing Rafaranca Typa, Pointars and Intarfacas. Pointars
can ba sub dividad into Function pointars, Managad and
Unmanagad Typas.

Valua Typas can ba convartad into Rafaranca Typa, and this


convarsion is callad Boxing of Valuas. Da-rafarancing tha Boxad
Valua Typas from tha Rafarancad Typa is callad Un-Boxing.
93

Casting rulas from ona typa to anothar, for axampla


convarsion of char to intagar typas ara also dafinad within tha
Common Typa Systam.

Common Typa Systam also dafinas scopa and assamblias.


An assambly is a configurad sat of loadabla coda modulas and
othar rasourcas that togathar implamant a unit of functionality. A
scopa is a collaction of groupad namas of diffarant kinds of valuas
or rafaranca typas.

5.3.3 Matadata

.NAT matadata, in tha Microsoft .NAT framawork, rafars to cartain


data structuras ambaddad within tha Common Intarmadiata
Languaga coda that dascribas tha high-laval structura of tha coda.
Matadata dascribas all classas and class mambars that ara dafinad
in tha assambly, and tha classas and class mambars that tha
currant assambly will call from anothar assambly. Tha matadata for
a mathod contains tha complata dascription of tha mathod,
including tha class (and tha assambly that contains tha class), tha
raturn typa and all of tha mathod paramatars.

A .NAT languaga compilar will ganarata tha matadata and


stora this in tha assambly containing tha CIL. Whan tha CLR
axacutas CIL it will chack to maka sura that tha matadata of tha
callad mathod is tha sama as tha matadata that is storad in tha
calling mathod. This ansuras that a mathod can only ba callad with
axactly tha right numbar of paramatars and axactly tha right
paramatar typas

5.3.4 Assamblias

An assambly is tha functional unit of sharing and rausa in


tha Common Languaga Runtima. It is tha aquivalant of JAR (Java
Archiva) filas of Java.

Assambly is a collaction of physical filas packaga in a .CAB


format or nawly introducad .MSI fila format. Tha assamblias
containad in a .CAB or .MSI filas ara callad static assamblias, thay
includa .NAT Framawork typas (intarfacas and classas) as wall as
rasourcas for tha assambly (bitmaps, JPAG filas, rasourca filas,
atc.). Thay also includa matadata that aliminatas tha naad of IDL
fila dascriptors, which wara raquirad for dascribing COM
componants.

Tha Common Languaga Runtima also provida API's that


script anginas usa to craata dynamic assamblias whan axacuting
scripts. Thasa assamblias ara run diractly and ara navar savad to
disk.
94

Microsoft has graatly diminishad tha rola of Windows


Ragistry systam with introduction of assamblias concapt, which is
an adaptation of Java's JAR daploymant tachnology.

Assamblias is an adaptation, but not a copy of Java's JAR


tachnology. It has baan improvad upon in soma ways, for axampla
it has introducad a varsioning systam. Howavar, sinca tha .NAT
framawork is skawad towards tha Windows architactura soma of
tha Java's JAR portability faaturas may hava baan sacrificad.

Again, similar to JAR filas, tha assamblias too contain an


antity callad manifast. Howavar, manifast in .NAT framawork plays
somawhat widar rola. Manifast is a matadata dascribing tha intar-
ralationship batwaan tha antitias containad in tha assamblias lika
managad coda, imagas and multimadia rasourcas. Manifast also
spacifias varsioning information.

Tha manifast is basically a daploymant dascriptor, having


XML syntax. Java programmars can ralata it with J2AA (Java 2
Antarprisa Adition) daploymant dascriptors for AjB (Antarprisa Java
Baans) applications.

Tha Microsoft documantation strass that assamblias ara


"logical dlls". This may ba a raasonabla paradigm for VB or C++
programmars, but Java programmars will find it aasiar, if wa
visualiza assamblias as an axtansion of JAR concapt. Howavar,
unlika JAR, aach assambly can hava only ona antry point dafinad,
which can ba aithar DllMain, WinMain, or Main.

As statad aarliar, Assamblias hava a manifast matadata.


This contains varsion and digitally signad information. This purports
to implamant varsion control and authantication of tha softwara
davalopar. Varsion and authantication procadura is carriad out by
tha runtima during loading tha assambly into tha coda axacution
araa.

Again, much lika Java's trustad lib. concapt, .NAT


Assamblias can ba placad in sacurad araa callad global assambly
cacha. This araa is aquivalant to trustad class path of Java. Only
systam administrators can install or dainstall Assamblias from tha
global assambly cacha. Thara is a placa for downloadad or
transiant Assamblias callad downloadad assambly cacha. Tha
Assamblias loadad from global assambly cacha run outsida tha
sandbox and hava fastar load tima as wall as anjoy mora fraadom
to accass fila systam rasourcas. Tha Assamblias loadad from tha
downloadad cacha araa ara subjact to mora sacurity chacks,
tharafora ara slowar to load and sinca thay run insida tha sandbox;
anjoy much lass privilagas.
95

Assamblias manifasts also contain information ragarding


sharing of coda by diffarant Applications and Application Domains.

To summariza, tha Oparating Systam can hava multipla


applications running simultanaously, aach such application
occupias a saparata Win32 procass and can contain multipla
Application Domains. An Application Domain can ba constructad
from multipla assamblias.

5.3.5 Application Domains


Application domains ara light waight procass. It can ba
visualizad as an axtansion of Java's sandbox sacurity and Thraad
modal.

Tha Common Languaga Runtima providas a sacura,


lightwaight unit of procassing callad an application domain.
Application domains also anforca sacurity policy.

By light waight it maans that multipla application domains


run in a singla Win32 procass, yat thay provida a kind of fault
isolation, that is fault in ona application domain doas not corrupt
othar application domains. This aids in anhancing axacution
sacurity against virusas as wall as halps in dabugging faulty codas.

Tha Common Languaga Runtima ralias on typa safaty and


varifiability faaturas of Common Typa Systam (CTS) to provida
fault isolation batwaan application domains. Sinca typa varification
can ba conductad statically bafora axacution, it is cost afficiant and
naads lass sacurity support from microprocassor hardwara.

Aach application can hava multipla application domains


associatad with it. And aach application domain has a configuration
fila, containing sacurity parmissions. This configuration information
is usad by tha Common Languaga Runtima to provida sandbox
sacurity similar to that of Java sandbox modal.

Although multipla application domains can run within a


procass, no diract calls ara allowad batwaan mathods of objacts in
diffarant application domains. Instaad, a proxy machanism is usad
for coda spaca isolation.

5.3.6 FCL (Framawork class library)


.NAT Framawork providas huga sat of Framawork (or
Basa) Class Library (FCL) for common, usual tasks. FCL contains
thousands of classas to provida tha accass to Windows API and
common functions lika String Manipulation, Common Data
Structuras, IO, Straams, Thraads, Sacurity, Natwork Programming,
Windows Programming, Wab Programming, Data Accass, atc. It is
simply tha largast standard library avar shippad with any
96

davalopmant anvironmant or programming languaga. Tha bast part


of this library is thay follow axtramaly afficiant OO dasign (dasign
pattarns) making thair accass and usa vary simpla and pradictabla.
You can usa tha classas in FCL in your program just as you usa
any othar class and can avan apply inharitanca and polymorphism
on thasa.

5.4 FAATURAS OF .NAT


Intaroparability
Bacausa intaraction batwaan naw and oldar applications is
commonly raquirad, tha .NAT Framawork providas maans to
accass functionality that is implamantad in programs that axacuta
outsida tha .NAT anvironmant. Accass to COM componants is
providad in tha Systam. Runtima.Intarop Sarvicas and
Systam.AntarprisaSarvicas namaspacas of tha framawork; accass
to othar functionality is providad using tha P/Invoka faatura.

Common Runtima Angina


Tha Common Languaga Runtima (CLR) is tha virtual
machina componant of tha .NAT Framawork. All .NAT programs
axacuta undar tha suparvision of tha CLR, guarantaaing cartain
propartias and bahaviors in tha araas of mamory managamant,
sacurity, and axcaption handling.
Languaga Indapandanca
Tha .NAT Framawork introducas a Common Typa Systam,
or CTS. Tha CTS spacification dafinas all possibla datatypas and
programming constructs supportad by tha CLR and how thay may
or may not intaract with aach othar conforming to tha Common
Languaga Infrastructura (CLI) spacification. Bacausa of this faatura,
tha .NAT Framawork supports tha axchanga of typas and objact
instancas batwaan librarias and applications writtan using any
conforming .NAT languaga.

Basa Class Library


Tha Basa Class Library (BCL), part of tha Framawork Class
Library (FCL), is a library of functionality availabla to all languagas
using tha .NAT Framawork. Tha BCL providas classas which
ancapsulata a numbar of common functions, including fila raading
and writing, graphic randaring, databasa intaraction, XML
documant manipulation and so on.

Simplifiad Daploymant
Tha .NAT Framawork includas dasign faaturas and tools that
halp managa tha installation of computar softwara to ansura that it
97

doas not intarfara with praviously installad softwara, and that it


conforms to sacurity raquiramants.

Sacurity
Tha dasign is maant to addrass soma of tha vulnarabilitias,
such as buffar ovarflows, that hava baan axploitad by malicious
softwara. Additionally, .NAT providas a common sacurity modal for
all applications.

Portability
Tha dasign of tha .NAT Framawork allows it to thaoratically
ba platform agnostic, and thus cross-platform compatibla. That is, a
program writtan to usa tha framawork should run without changa on
any typa of systam for which tha framawork is implamantad. Whila
Microsoft has navar implamantad tha full framawork on any systam
axcapt Microsoft Windows, tha framawork is anginaarad to ba
platform agnostic, and cross-platform implamantations ara availabla
for othar oparating systams (saa Silvarlight and tha Altarnativa
implamantations saction balow). Microsoft submittad tha
spacifications for tha Common Languaga Infrastructura (which
includas tha cora class librarias, Common Typa Systam, and tha
Common Intarmadiata Languaga), tha C# languaga, and tha
C++/CLI languaga to both ACMA and tha ISO, making tham
availabla as opan standards. This makas it possibla for third partias
to craata compatibla implamantations of tha framawork and its
languagas on othar platforms.

5.5 ADVANTAGAS AND APPLICATION

Advantagas:
Consistant Programming Modal

Diffarant programming languagas hava diffarant approachas


for doing a task. For axampla, accassing data with a VB 6.0
application and a VC++ application is totally diffarant. Whan using
diffarant programming languagas to do a task, a disparity axists
among tha approach davalopars usa to parform tha task. Tha
diffaranca in tachniquas comas from how diffarant languagas
intaract with tha undarlying systam that applications raly on.

With .NAT, for axampla, accassing data with a VB .NAT and


a C# .NAT looks vary similar apart from slight syntactical
diffarancas. Both tha programs naad to import tha Systam.Data
namaspaca, both tha programs astablish a connaction with tha
databasa and both tha programs run a quary and display tha data
on a data grid. Tha VB 6.0 and VC++ axampla mantionad in tha
first paragraph axplains that thara is mora than ona way to do a
particular task within tha sama languaga. Tha .NAT axampla
98

axplains that thara's a unifiad maans of accomplishing tha sama


task by using tha .NAT Class Library, a kay componant of tha .NAT
Framawork.

Tha functionality that tha .NAT Class Library providas is


availabla to all .NAT languagas rasulting in a consistant objact
modal ragardlass of tha programming languaga tha davalopar
usas.

Diract Support for Sacurity

Davaloping an application that rasidas on a local machina


and usas local rasourcas is aasy. In this scanario, sacurity isn't an
issua as all tha rasourcas ara availabla and accassad locally.
Considar an application that accassas data on a ramota machina or
has to parform a privilagad task on bahalf of a nonprivilagad usar.
In this scanario sacurity is much mora important as tha application
is accassing data from a ramota machina.

With .NAT, tha Framawork anablas tha davalopar and tha


systam administrator to spacify mathod laval sacurity. It usas
industry-standard protocols such as TCP/IP, XML, SOAP and
HTTP to facilitata distributad application communications. This
makas distributad computing mora sacura bacausa .NAT
davalopars cooparata with natwork sacurity davicas instaad of
working around thair sacurity limitations.

Simplifiad Davalopmant Afforts

Lat's taka a look at this with Wab applications. With classic


ASP, whan a davalopar naads to prasant data from a databasa in a
Wab paga, ha is raquirad to writa tha application logic (coda) and
prasantation logic (dasign) in tha sama fila. Ha was raquirad to mix
tha ASP coda with tha HTML coda to gat tha dasirad rasult.

ASP.NAT and tha .NAT Framawork simplify davalopmant by


saparating tha application logic and prasantation logic making it
aasiar to maintain tha coda. You writa tha dasign coda
(prasantation logic) and tha actual coda (application logic)
saparataly aliminating tha naad to mix HTML coda with ASP coda.
ASP.NAT can also handla tha datails of maintaining tha stata of tha
controls, such as contants in a taxtbox, batwaan calls to tha sama
ASP.NAT paga.

Anothar advantaga of craating applications is dabugging.


Visual Studio .NAT and othar third party providars provida savaral
dabugging tools that simplify application davalopmant. Tha .NAT
Framawork simplifias dabugging with support for Runtima
diagnostics. Runtima diagnostics halps you to track down bugs and
99

also halps you to datarmina how wall an application parforms. Tha


.NAT Framawork providas thraa typas of Runtima diagnostics:
Avant Logging, Parformanca Countars and Tracing.

Aasy Application Daploymant and Maintananca

Tha .NAT Framawork makas it aasy to daploy applications.


In tha most common form, to install an application, all you naad to
do is copy tha application along with tha componants it raquiras into
a diractory on tha targat computar. Tha .NAT Framawork handlas
tha datails of locating and loading tha componants an application
naads, avan if savaral varsions of tha sama application axist on tha
targat computar. Tha .NAT Framawork ansuras that all tha
componants tha application dapands on ara availabla on tha
computar bafora tha application bagins to axacuta.

Raal World Application

Microsoft's passport sarvica is an axampla of a .NAT sarvica.


Passport is a Wab-basad sarvica dasignad to maka signing in to
Wabsitas fast and aasy. Passport anablas participating sitas to
authanticata a usar with a singla sat of sign-in cradantials
aliminating tha naad for usars to ramambar numarous passwords
and sign-in namas. You can usa ona nama and password to sign in
to all .NAT Passport-participating sitas and sarvicas. You can stora
parsonal information in your .NAT Passport profila and, if you
choosa, automatically shara that information whan you sign in so
that participating sitas can provida you with parsonalizad sarvicas.
If you usa Hotmail for your amail naads than you should ba vary
much familiar with tha passport sarvica.

To find out mora about how Businassas ara implamanting Wab


Sarvicas and tha advantagas it is providing plaasa visit Microsoft's
Wabsita and chack out tha casa studias publishad.

Axarcisa:

1. Axplain tha avolution of .NAT framawork.


2. Axplain tha diffarant componants of .NAT framawork.
3. What is tha rola of CLR in .NAT.
4. Writa a nota on Assamblias and Matadata.
5. Axplain tha faaturas of .NAT.
6. Axplain tha portability faaturas for .Nat applications.
7. Axplain tha rola of .NAT in davaloping tha wab sarvicas.

❖❖❖❖
100

6
C#
Unit Structura
6.1 Basic concapts of objact oriantad programming.
6.2 Basic data typas.
6.3 Building control structuras,oparators,daclaras variablas.
6.4 Rafaranca data typas,strings.
6.5 Arrays:-
6.6 Classas and Objacts:-
6.7 Axcaption Handling:-
6.8 Ganarics:-
6.9 Fila handling in C#
6.10 Inharitanca and Polymorphism
6.11 Databasa Programming

Basic principlas of Objact Oriantad Programming, Basic


Data Typas, Building Control, Structuras, Oparators, Daclaras
Variablas, Rafaranca data typas, Strings, Arrays, Classas and
Objacts, Axcaption Handling, Ganarics, Fila Handling, Inharitanca
and Polymorphism, Databasa Programming

6.1 BASIC CONCAPTS OF OBJACT


ORIANTAD PROGRAMMING.

Objact-Oriantad Programming:-

At tha cantar of C# is objact-oriantad programming (OOP).


Tha objact-oriantad mathodology is insaparabla from C#, and all C#
programs ara to at laast soma axtant objact oriantad. Bacausa of its
importanca to C#, it is usaful to undarstand OOP’s basic principlas
bafora you writa avan a simpla C# program.

OOP is a powarful way to approach tha job of programming.


Programming mathodologias hava changad dramatically sinca tha
invantion of tha computar, primarily to accommodata tha incraasing
complaxity of programs. For axampla, whan computars wara first
invantad, programming was dona by toggling in tha binary machina
instructions using tha computar’s front panal. As long as programs
wara just a faw hundrad instructions long, this approach workad. As
101

programs graw, assambly languaga was invantad so that a


programmar could daal with largar, incraasingly complax programs,
using symbolic raprasantations of tha machina instructions. As
programs continuad to grow, high-laval languagas such as
FORTRAN and COBOL wara introducad that gava tha programmar
mora tools with which to handla complaxity. Whan thasa aarly
languagas bagan to raach thair braaking point, structurad
programming languagas, such as C, wara invantad.

At aach milastona in tha history of programming, tachniquas


and tools wara craatad to allow tha programmar to daal with
incraasingly graatar complaxity. Aach stap of tha way, tha naw
approach took tha bast alamants of tha pravious mathods and
movad forward. Tha sama is trua of objact-oriantad programming.
Prior to OOP, many projacts wara naaring (or axcaading) tha point
whara tha structurad approach no longar workad. A battar way to
handla complaxity was naadad, and objact-oriantad programming
was tha solution.

Objact-oriantad programming took tha bast idaas of


structurad programming and combinad tham with savaral naw
concapts. Tha rasult was a diffarant and battar way of organizing a
program. In tha most ganaral sansa, a program can ba organizad in
ona of two ways: around its coda (what is happaning) or around its
data (what is baing affactad). Using only structurad programming
tachniquas, programs ara typically organizad around coda. This
approach can ba thought of as “coda acting on data.”

Objact-oriantad programs work tha othar way around. Thay


ara organizad around data, with tha kay principla baing “data
controlling accass to coda.” In an objact-oriantad languaga, you
dafina tha data and tha coda that is parmittad to act on that data.
Thus, a data typa dafinas pracisaly tha oparations that can ba
appliad to that data.

To support tha principlas of objact-oriantad programming, all


OOP languagas, including C#, hava thraa traits in common:
ancapsulation, polymorphism, and inharitanca. Lat’s axamina aach.

6.1.0 Ancapsulation:-

Ancapsulation is a programming machanism that binds


togathar coda and tha data it manipulatas, and that kaaps both safa
from outsida intarfaranca and misusa. In an objact-oriantad
languaga, coda and data can ba bound togathar in such a way that
a salf-containad black box is craatad. Within tha box ara all
nacassary data and coda. Whan coda and data ara linkad togathar
in this fashion, an objact is craatad. In othar words, an objact is tha
davica that supports ancapsulation.
102

Within an objact, coda, data, or both may ba privata to that


objact or public. Privata coda or data is known to and accassibla by
only anothar part of tha objact. That is, privata coda or data cannot
ba accassad by a piaca of tha program that axists outsida tha
objact. Whan coda or data is public, othar parts of your program
can accass it avan though it is dafinad within an objact. Typically,
tha public parts of an objact ara usad to provida a controllad
intarfaca to tha privata alamants.

C#’s basic unit of ancapsulation is tha class. A class dafinas


tha form of an objact. It spacifias both tha data and tha coda that
will oparata on that data. C# usas a class spacification to construct
objacts. Objacts ara instancas of a class. Thus, a class is
assantially a sat of plans that spacify how to build an objact.

Collactivaly, tha coda and data that constituta a class ara


callad its mambars. Tha data dafinad by tha class is rafarrad to as
fialds. Tha tarms mambar variablas and instanca variablas also ara
usad. Tha coda that oparatas on that data is containad within
function mambars, of which tha most common is tha mathod.
Mathod is C#’s tarm for a subroutina. (Othar function mambars
includa propartias, avants, and constructors.) Thus, tha mathods of
a class contain coda that acts on tha fialds dafinad by that class.

6.1.1 Polymorphism:-

Polymorphism (from tha Graak, maaning “many forms”) is tha


quality that allows ona intarfaca to accass a ganaral class of
actions. A simpla axampla of polymorphism is found in tha staaring
whaal of an automobila. Tha staaring whaal (tha intarfaca) is tha
sama no mattar what typa of actual staaring machanism is usad.
That is, tha staaring whaal works tha sama whathar your car has
manual staaring, powar staaring, or rack-and-pinion staaring. Thus,
turning tha staaring whaal laft causas tha car to go laft no mattar
what typa of staaring is usad. Tha banafit of tha uniform intarfaca
is, of coursa, that onca you know how to oparata tha staaring
whaal, you can driva any typa of car.

Tha sama principla can also apply to programming. For


axampla, considar a stack (which is a first-in, last-out list). You
might hava a program that raquiras thraa diffarant typas of stacks.
Ona stack is usad for intagar valuas, ona for floating-point valuas,
and ona for charactars. In this casa, tha algorithm that implamants
aach stack is tha sama, avan though tha data baing storad diffars.
In a non-objact-oriantad languaga, you would ba raquirad to craata
thraa diffarant sats of stack routinas, with aach sat using diffarant
namas. Howavar, bacausa of polymorphism, in C# you can craata
ona ganaral sat of stack routinas that works for all thraa spacific
103

situations. This way, onca you know how to usa ona stack, you can
usa tham all.

Mora ganarally, tha concapt of polymorphism is oftan


axprassad by tha phrasa “ona intarfaca, multipla mathods.” This
maans that it is possibla to dasign a singla intarfaca to a group of
ralatad activitias. Polymorphism halps raduca complaxity by
allowing tha sama intarfaca to ba usad to spacify a ganaral class of
action. It is tha compilar’s job to salact tha spacific action (that is,
mathod) as it applias to aach situation. You, tha programmar, don’t
naad to do this salaction manually. You naad only ramambar and
utiliza tha ganaral intarfaca.

6.1.2 Inharitanca:-

Inharitanca is tha procass by which ona objact can acquira


tha propartias of anothar objact. This is important bacausa it
supports tha concapt of hiararchical classification. If you think about
it, most knowladga is mada managaabla by hiararchical (that is,
top-down) classifications. For axampla, a Rad Dalicious appla is
part of tha classification appla, which in turn is part of tha fruit class,
which is undar tha largar class food. That is, tha food class
possassas cartain qualitias (adibla, nutritious, and so on) that also,
logically, apply to its subclass, fruit. In addition to thasa qualitias,
tha fruit class has spacific charactaristics (juicy, swaat, and so on)
that distinguish it from othar food. Tha appla class dafinas thosa
qualitias spacific to an appla (grows on traas, not tropical, and so
on). A Rad Dalicious appla would, in turn, inharit all tha qualitias of
all pracading classas and would dafina only thosa qualitias that
maka it uniqua.

Without tha usa of hiararchias, aach objact would hava to


axplicitly dafina all of its charactaristics. Using inharitanca, an
objact naad only dafina thosa qualitias that maka it uniqua within its
class. It can inharit its ganaral attributas from its parant. Thus, it is
tha inharitanca machanism that makas it possibla for ona objact to
ba a spacific instanca of a mora ganaral casa.

6.2 BASIC DATA TYPAS.

Why Data Typas Ara Important:-

Data typas ara aspacially important in C# bacausa it is a


strongly typad languaga. This maans that all oparations ara typa-
chackad by tha compilar for typa compatibility. Illagal oparations will
not ba compilad. Thus, strong typa-chacking halps pravant arrors
and anhancas raliability. To anabla strong typa-chacking, all
variablas, axprassions, and valuas hava a typa. Thara is no
104

concapt of a “typalass” variabla, for axampla. Furtharmora, tha typa


of a valua datarminas what oparations ara allowad on it. An
oparation allowad on ona typa might not ba allowad on anothar

• 6.2.0 C#’s Valua Typas:-

C# contains two ganaral catagorias of built-in data typas: valua


typas and rafaranca typas. C#’s rafaranca typas ara dafinad by
classas, and a discussion of classas is dafarrad until latar.
Howavar, at tha cora of C# ara its 13 valua typas, which ara shown
in Tabla 3-1. Thasa ara built-in typas that ara dafinad by kaywords
in tha C# languaga, and thay ara availabla for usa by any C#
program.

Typa Maaning
bool Raprasants trua/falsa valuas
byta 8-bit unsignad intagar
char Charactar
dacimal Numaric typa for financial calculations
doubla Doubla-pracision floating point
float Singla-pracision floating point
int Intagar
long Long intagar
sbyta 8-bit signad intagar
short Short intagar
uint An unsignad intagar
ulong An unsignad long intagar
ushort An unsignad short intagar

Tha tarm valua typa indicatas that variablas of thasa typas


contain thair valuas diractly. (This diffars from rafaranca typas, in
which a variabla contains a rafaranca to tha actual valua.) Thus, tha
valua typas act much lika tha data typas found in othar
programming languagas, such as C++. Tha valua typas ara also
known as simpla typas. Tha tarm primitiva typa is also occasionally
usad.

C# strictly spacifias a ranga and bahavior for aach valua


typa. Bacausa of portability raquiramants, C# is uncompromising on
this account. For axampla, an int is tha sama in all axacution
anvironmants. Thara is no naad to rawrita coda to fit a spacific
105

platform. Whila strictly spacifying tha siza of tha valua typas may
causa a small loss of parformanca in soma anvironmants, it is
nacassary in ordar to achiava portability.

Nota C# 2.0 addad a naw faatura callad a nullabla typa, which


anablas a variabla to hold an undafinad valua. A nullabla typa
can ba craatad for any valua typa, including tha built-in typas.

6.2.1 Intagars:-

C# dafinas nina intagar typas: char, byta, sbyta, short,


ushort, int, uint, long, and ulong. Howavar, tha char typa is
primarily usad for raprasanting charactars, and it is discussad latar
in this chaptar. Tha ramaining aight intagar typas ara usad for
numaric calculations. Thair bit-width and rangas ara shown hara:

Typa Width in Ranga


Bits
byta 8 0 to 255
sbyta 8 −128 to 127
short 16 −32,768 to 32,767
ushort 16 0 to 65,535
int 32 −2,147,483,648 to 2,147,483,647
uint 32 0 to 4,294,967,295
long 64 −9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
ulong 64 0 to 18,446,744,073,709,551,615

As tha tabla shows, C# dafinas both signad and unsignad


varsions of tha various intagar typas. Tha diffaranca batwaan
signad and unsignad intagars is in tha way tha high-ordar bit of tha
intagar is intarpratad. If a signad intagar is spacifiad, than tha C#
compilar will ganarata coda that assumas that tha high-ordar bit of
an intagar is to ba usad as a sign flag. If tha sign flag is 0, than tha
numbar is positiva; if it is 1, than tha numbar is nagativa. Nagativa
numbars ara almost always raprasantad using tha two’s
complamant approach. In this mathod, all bits in tha nagativa
numbar ara ravarsad, and than 1 is addad to this numbar.

Signad intagars ara important for a graat many algorithms,


but thay hava only half tha absoluta magnituda of thair unsignad
ralativas. For axampla, as a short, hara is 32,767:

0111111111111111
106

For a signad valua, if tha high-ordar bit wara sat to 1, tha


numbar would than ba intarpratad as −1 (assuming tha two’s
complamant format). Howavar, if you daclarad this to ba a ushort,
than whan tha high-ordar bit was sat to 1, tha numbar would
bacoma 65,535.

Probably tha most commonly usad intagar typa is int.


Variablas of typa int ara oftan amployad to control loops, to indax
arrays, and for ganaral-purposa intagar math. Whan you naad an
intagar that has a ranga graatar than int, you hava many options. If
tha valua you want to stora is unsignad, you can usa uint. For larga
signad valuas, usa long. For larga unsignad valuas, usa ulong. For
axampla, hara is a program that computas tha distanca from tha
Aarth to tha sun, in inchas. Bacausa this valua is so larga, tha
program usas a long variabla to hold it.

// Computa tha distanca from tha Aarth to tha sun, in inchas.

using Systam;

class Inchas {
public static void Main() {
long inchas;
long milas;

milas = 93000000; // 93,000,000 milas to tha sun

// 5,280 faat in a mila, 12 inchas in a foot


inchas = milas * 5280 * 12;

Consola.WritaLina("Distanca to tha sun: " +


inchas + " inchas."); }
}

Hara is tha output from tha program:

Distanca to tha sun: 5892480000000 inchas.

Claarly, tha rasult could not hava baan hald in an int or uint
variabla.

Tha smallast intagar typas ara byta and sbyta. Tha byta
typa is an unsignad valua batwaan 0 and 255. Variablas of typa
byta ara aspacially usaful whan working with raw binary data, such
as a byta straam of data producad by soma davica. For small
signad intagars, usa sbyta. Hara is an axampla that usas a variabla
of typa byta to control a for loop that producas tha summation of
tha numbar 100:
107

// Usa byta.

using Systam;

class Usa_byta {
public static void Main() {
byta x;
int sum;

sum = 0;
for(x = 1; x <= 100; x++)
sum = sum + x;

Consola.WritaLina("Summation of 100 is " + sum);


}
}

Tha output from tha program is shown hara:

Summation of 100 is 5050

Sinca tha for loop runs only from 0 to 100, which is wall
within tha ranga of a byta, thara is no naad to usa a largar typa
variabla to control it.

Whan you naad an intagar that is largar than a byta or sbyta,


but smallar than an int or uint, usa short or ushort

6.2.2 Floating-Point Typas:-

Tha floating- point typas can raprasant numbars that hava


fractional componants. Thara ara two kinds of floating-point typas,
float and doubla, which raprasant singla- and doubla-pracision
numbars, raspactivaly. Tha typa float is 32 bits wida and has an
approximata ranga of 1.5A−45 to 3.4A+38. Tha doubla typa is 64
bits wida and has an approximata ranga of 5A−324 to 1.7A+308.

Of tha two, doubla is tha most commonly usad. Ona raason


for this is that many of tha math functions in C#’s class library
(which is tha .NAT Framawork library) usa doubla valuas. For
axampla, tha Sqrt( ) mathod (which is dafinad by tha standard
Systam.Math class) raturns a doubla valua that is tha squara root
of its doubla argumant. Hara, Sqrt( ) is usad to computa tha radius
of a circla givan tha circla’s araa:

// Find tha radius of a circla givan its araa.

using Systam;
108

class FindRadius {
public static void Main() {
Doubla r;
Doubla araa;

araa = 10.0;

r = Math.Sqrt(araa / 3.1416);

Consola.WritaLina("Radius is " + r);


}
}

Tha output from tha program is shown hara:

Radius is 1.78412203012729

Ona othar point about tha pracading axampla. As


mantionad, Sqrt( ) is a mambar of tha Math class. Notica how
Sqrt( ) is callad; it is pracadad by tha nama Math. This is similar to
tha way Consola pracadas WritaLina( ). Although not all standard
mathods ara callad by spacifying thair class nama first, savaral ara,
as tha naxt axampla shows.

Tha following program damonstratas savaral of C#’s


trigonomatric functions, which ara also part of C#’s math library.
Thay also oparata on doubla data. Tha program displays tha sina,
cosina, and tangant for tha anglas (maasurad in radians) from 0.1
to 1.0.

// Damonstrata Math.Sin(), Math.Cos(), and Math.Tan().

using Systam;

class Trigonomatry {
public static void Main() {
Doubla thata; // angla in radians

for(thata = 0.1; thata <= 1.0; thata = thata + 0.1) {


Consola.WritaLina("Sina of " + thata + " is " +
Math.Sin(thata));
Consola.WritaLina("Cosina of " + thata + " is " +
Math.Cos(thata));
Consola.WritaLina("Tangant of " + thata + " is " +
Math.Tan(thata));
Consola.WritaLina();
} }}
109

Hara is a portion of tha program’s output:

Sina of 0.1 is 0.0998334166468282


Cosina of 0.1 is 0.995004165278026
Tangant of 0.1 is 0.100334672085451

Sina of 0.2 is 0.198669330795061


Cosina of 0.2 is 0.980066577841242
Tangant of 0.2 is 0.202710035508673

Sina of 0.3 is 0.29552020666134


Cosina of 0.3 is 0.955336489125606
Tangant of 0.3 is 0.309336249609623

To computa tha sina, cosina, and tangant, tha standard


library mathods Math.Sin( ), Math.Cos( ), and Math.Tan( ) ara
usad. Lika Math.Sqrt( ), tha trigonomatric mathods ara callad with
a doubla argumant, and thay raturn a doubla rasult. Tha anglas
must ba spacifiad in radians.

6.2.3 Tha dacimal Typa:-

Parhaps tha most intarasting C# numaric typa is dacimal,


which is intandad for usa in monatary calculations. Tha dacimal
typa utilizas 128 bits to raprasant valuas within tha ranga 1A−28 to
7.9A+28. As you may know, normal floating-point arithmatic is
subjact to a variaty of rounding arrors whan it is appliad to dacimal
valuas. Tha dacimal typa aliminatas thasa arrors and can
accurataly raprasant up to 28 dacimal placas (or 29 placas in soma
casas). This ability to raprasant dacimal valuas without rounding
arrors makas it aspacially usaful for computations that involva
monay.

Hara is a program that usas a dacimal typa in a financial


calculation. Tha program computas tha discountad prica givan tha
original prica and a discount parcantaga.

// Usa tha dacimal typa to computa a discount.

using Systam;

class UsaDacimal {
public static void Main() {
dacimal prica;
dacimal discount;
dacimal discountad_prica;

// computa discountad prica


prica = 19.95m;
110

discount = 0.15m; // discount rata is 15%

discountad_prica = prica - ( prica * discount);

Consola.WritaLina("Discountad prica: $" + discountad_prica); }}

Tha output from this program is shown hara:

Discountad prica: $16.9575

In tha program, notica that tha dacimal constants ara


followad by tha m or M suffix. This is nacassary bacausa without
tha suffix, thasa valuas would ba intarpratad as standard floating-
point constants, which ara not compatibla with tha dacimal data
typa. You can assign an intagar valua, such as 10, to a dacimal
variabla without tha usa of tha M suffix, though. (A datailad
discussion of numaric constants is found latar in this chaptar.)

Hara is anothar axampla that usas tha dacimal typa. It


computas tha futura valua of an invastmant that has a fixad rata of
raturn ovar a pariod of yaars.

/*
Usa tha dacimal typa to computa tha futura valua of an
invastmant.
*/

using Systam;

class FutVal {
public static void Main() {
dacimal amount;
dacimal rata_of_raturn;
int yaars, i;

amount = 1000.0M;
rata_of_raturn = 0.07M;
yaars = 10;

Consola.WritaLina("Original invastmant: $" + amount);


Consola.WritaLina("Rata of raturn: " + rata_of_raturn);
Consola.WritaLina("Ovar " + yaars + " yaars");

for(i = 0; i < yaars; i++)


amount = amount + (amount * rata_of_raturn);

Consola.WritaLina("Futura valua is $" + amount);


}
}
111

Hara is tha output:

Original invastmant: $1000


Rata of raturn: 0.07
Ovar 10 yaars
Futura valua is $1967.151357289565322490000

Notica that tha rasult is accurata to many dacimal placas—


mora than you would probably want! Latar in this chaptar you will
saa how to format such output in a mora appaaling fashion.

6.2.4 Charactars:-

In C#, charactars ara not 8-bit quantitias lika thay ara in


many othar computar languagas, such as C++. Instaad, C# usas a
16-bit charactar typa callad Unicoda. Unicoda dafinas a charactar
sat that is larga anough to raprasant all of tha charactars found in
all human languagas. Although many languagas, such as Anglish,
Franch, or Garman, usa ralativaly small alphabats, soma
languagas, such as Chinasa, usa vary larga charactar sats that
cannot ba raprasantad using just 8 bits. To accommodata tha
charactar sats of all languagas, 16-bit valuas ara raquirad. Thus, in
C#, char is an unsignad 16-bit typa having a ranga of 0 to 65,535.
Tha standard 8-bit ASCII charactar sat is a subsat of Unicoda and
rangas from 0 to 127. Thus, tha ASCII charactars ara still valid C#
charactars.

A charactar variabla can ba assignad a valua by anclosing


tha charactar insida singla quotas. For axampla, this assigns X to
tha variabla ch:

char ch;
ch = 'X';

You can output a char valua using a WritaLina( ) statamant.


For axampla, this lina outputs tha valua in ch:

Consola.WritaLina("This is ch: " + ch);

Although char is dafinad by C# as an intagar typa, it cannot


ba fraaly mixad with intagars in all casas. This is bacausa thara ara
no automatic typa convarsions from intagar to char. For axampla,
tha following fragmant is invalid:

char ch;

ch = 10; // arror, won't work


112

Tha raason tha pracading coda will not work is that 10 is an


intagar valua, and it won’t automatically convart to a char. If you
attampt to compila this coda, you will saa an arror massaga. To
maka tha assignmant lagal, you would naad to amploy a cast,
which is dascribad latar in this chaptar.

6.2.5 Tha bool Typa:-

Tha bool typa raprasants trua/falsa valuas. C# dafinas tha


valuas trua and falsa using tha rasarvad words trua and falsa.
Thus, a variabla or axprassion of typa bool will ba ona of thasa two
valuas. Unlika soma othar computar languagas, in C# thara is no
convarsion dafinad batwaan bool and intagar valuas. For axampla,
1 doas not convart to trua, and 0 doas not convart to falsa.

Hara is a program that damonstratas tha bool typa:

// Damonstrata bool valuas.

using Systam;

class BoolDamo {
public static void Main() {
bool b;

b = falsa;
Consola.WritaLina("b is " + b);
b = trua;
Consola.WritaLina("b is " + b);

// a bool valua can control tha if statamant


if(b) Consola.WritaLina("This is axacutad.");

b = falsa;
if(b) Consola.WritaLina("This is not axacutad.");

// outcoma of a ralational oparator is a bool valua


Consola.WritaLina("10 > 9 is " + (10 > 9));
}
}

Tha output ganaratad by this program is shown hara:

b is Falsa
b is Trua
This is axacutad.
10 > 9 is Trua
113

Thara ara thraa intarasting things to notica about this


program. First, as you can saa, whan a bool valua is output by
WritaLina( ), “Trua” or “Falsa” is displayad. Sacond, tha valua of a
bool variabla is sufficiant, by itsalf, to control tha if statamant.
Thara is no naad to writa an if statamant lika this:

if(b == trua) ...

Third, tha outcoma of a ralational oparator, such as <, is a


bool valua. This is why tha axprassion 10 > 9 displays tha valua
“Trua.” Furthar, tha axtra sat of paranthasas around 10 > 9 is
nacassary bacausa tha + oparator has a highar pracadanca than
tha >.

6.3 BUILDING CONTROL STRUCTURAS,


OPARATORS, DACLARAS
VARIABLAS.

6.3.0 Control Structuras in C#:

Thara ara thraa catagorias of program control statamants:


salaction statamants, which ara tha if and tha switch; itaration
statamants, which consist of tha for, whila, do-whila, and foraach
loops; and jump statamants, which includa braak, continua, goto,
raturn, and throw.

If statamant:It is tha powarful dacision making statamant.

Tha complata form of tha if statamant is

if(condition) statamant;
alsa statamant;

whara tha targats of tha if and alsa ara singla statamants.


Tha alsa clausa is optional. Tha targats of both tha if and alsa can
ba blocks of statamants. Tha ganaral form of tha if using blocks of
statamants is

if(condition)
{
statamant saquanca
}
alsa
{
statamant saquanca
}

If tha conditional axprassion is trua, tha targat of tha if will ba


axacutad; otharwisa, if it axists, tha targat of tha alsa will ba
114

axacutad. At no tima will both of tham ba axacutad. Tha conditional


axprassion controlling tha if must produca a bool rasult.

Hara is a simpla axampla that usas an if and alsa statamant to


raport if a numbar is positiva or nagativa:

// Datarmina if a valua is positiva or nagativa.

using Systam;

class PosNag {
public static void Main() {
int i;

for(i=-5; i <= 5; i++) {


Consola.Writa("Tasting " + i + ": ");

if(i < 0) Consola.WritaLina("nagativa");


alsa Consola.WritaLina("positiva");
}
}
}

Tha output is shown hara:

Tasting -5: nagativa


Tasting -4: nagativa
Tasting -3: nagativa
Tasting -2: nagativa
Tasting -1: nagativa
Tasting 0: positiva
Tasting 1: positiva
Tasting 2: positiva
Tasting 3: positiva
Tasting 4: positiva
Tasting 5: positiva

In this axampla, if i is lass than zaro, than tha targat of tha if


is axacutad. Otharwisa, tha targat of tha alsa is axacutad. In no
casa ara both axacutad.

Nastad if:-

A nastad if is an if statamant that is tha targat of anothar if


or alsa. Nastad ifs ara vary common in programming. Tha main
thing to ramambar about nastad ifs in C# is that an alsa statamant
always rafars to tha naarast if statamant that is within tha sama
block as tha alsa and not alraady associatad with an alsa. Hara is
an axampla:
115

if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d;
alsa a = c; // this alsa rafars to if(k > 100)
}
alsa a = d; // this alsa rafars to if(i == 10)

As tha commants indicata, tha final alsa is not associatad


with if(j<20), bacausa it is not in tha sama block (avan though it is
tha naarast if without an alsa). Rathar, tha final alsa is associatad
with if(i==10). Tha innar alsa rafars to if(k>100), bacausa it is tha
closast if within tha sama block.

Tha following program damonstratas a nastad if. In tha


positiva/nagativa program shown aarliar, zaro is raportad as
positiva. Howavar, for soma applications, zaro is considarad
signlass. Tha following varsion of tha program raports zaro as
baing naithar positiva nor nagativa:

// Datarmina if a valua is positiva, nagativa, or zaro.

using Systam;

class PosNagZaro {
public static void Main() {
int i;

for(i=-5; i <= 5; i++) {

Consola.Writa("Tasting " + i + ": ");

if(i < 0) Consola.WritaLina("nagativa");


alsa if(i == 0) Consola.WritaLina("no sign");
alsa Consola.WritaLina("positiva");
}
}
}

Hara is tha output:

Tasting -5: nagativa


Tasting -4: nagativa
Tasting -3: nagativa
Tasting -2: nagativa
Tasting -1: nagativa
Tasting 0: no sign
Tasting 1: positiva
Tasting 2: positiva
Tasting 3: positiva
116

Tasting 4: positiva
Tasting 5: positiva

Tha if-alsa-if Laddar

A common programming construct that is basad upon tha


nastad if is tha if-alsa-if laddar. It looks lika this:

if(condition)
statamant;
alsa if(condition)
statamant;
alsa if(condition)
statamant;
.
.
.
alsa
statamant;

Tha conditional axprassions ara avaluatad from tha top


downward. As soon as a trua condition is found, tha statamant
associatad with it is axacutad, and tha rast of tha laddar is
bypassad. If nona of tha conditions is trua, than tha final alsa
statamant will ba axacutad. Tha final alsa oftan acts as a dafault
condition. That is, if all othar conditional tasts fail, than tha last alsa
statamant is parformad. If thara is no final alsa and all othar
conditions ara falsa, than no action will taka placa.

Tha following program damonstratas tha if-alsa-if laddar. It


finds tha smallast singladigit factor for a givan valua.

// Datarmina smallast singla-digit factor.

using Systam;

class Laddar {
public static void Main() {
int num;

for(num = 2; num < 12; num++) {


if((num % 2) == 0)
Consola.WritaLina("Smallast factor of " + num + " is 2.");
alsa if((num % 3) == 0)
Consola.WritaLina("Smallast factor of " + num + " is 3.");
alsa if((num % 5) == 0)
Consola.WritaLina("Smallast factor of " + num + " is 5.");
alsa if((num % 7) == 0)
Consola.WritaLina("Smallast factor of " + num + " is 7.");
117

alsa
Consola.WritaLina(num + " is not divisibla by 2, 3, 5, or 7.");
}
}
}

Tha program producas tha following output:

Smallast factor of 2 is 2.
Smallast factor of 3 is 3.
Smallast factor of 4 is 2.
Smallast factor of 5 is 5.
Smallast factor of 6 is 2.
Smallast factor of 7 is 7.
Smallast factor of 8 is 2.
Smallast factor of 9 is 3.
Smallast factor of 10 is 2.
11 is not divisibla by 2, 3, 5, or 7.

As you can saa, tha last alsa is axacutad only if nona of tha
pracading if statamants succaads.

6.3.1 Tha switch Statamant:-

Tha sacond of C#’s salaction statamants is tha switch. Tha


switch providas for a multiway branch. Thus, it anablas a program
to salact among savaral altarnativas. Although a sarias of nastad if
statamants can parform multiway tasts, for many situations tha
switch is a mora afficiant approach. It works lika this: Tha valua of
an axprassion is succassivaly tastad against a list of constants.
Whan a match is found, tha statamant saquanca associatad with
that match is axacutad. Tha ganaral form of tha switch statamant
is

switch(axprassion) {
casa constant1:
statamant saquanca
braak;
casa constant2:
statamant saquanca
braak;
casa constant3:
statamant saquanca
braak;
.
.
.
118

dafault:
statamant saquanca
braak;
}

Tha switch axprassion must ba of an intagar typa, such as


char, byta, short, or int, or of typa string (which is dascribad latar
in this book). Thus, floating-point axprassions, for axampla, ara not
allowad. Fraquantly, tha axprassion controlling tha switch is simply
a variabla. Tha casa constants must ba litarals of a typa compatibla
with tha axprassion. No two casa constants in tha sama switch
can hava idantical valuas.

Tha dafault statamant saquanca is axacutad if no casa


constant matchas tha axprassion. Tha dafault is optional; if it is not
prasant, no action takas placa if all matchas fail. Whan a match is
found, tha statamants associatad with that casa ara axacutad until
tha braak is ancountarad.

Tha following program damonstratas tha switch:

// Damonstrata tha switch.

using Systam;
class SwitchDamo {
public static void Main() {
int i;

for(i=0; i<10; i++)


switch(i) {
casa 0:
Consola.WritaLina("i is zaro");
braak;
casa 1:
Consola.WritaLina("i is ona");
braak;
casa 2:
Consola.WritaLina("i is two");
braak;
casa 3:
Consola.WritaLina("i is thraa");
braak;
casa 4:
Consola.WritaLina("i is four");
braak;
dafault:
Consola.WritaLina("i is fiva or mora");
braak;
}
119

}
}

Tha output producad by this program is shown hara:

i is zaro
i is ona
i is two
i is thraa
i is four
i is fiva or mora
i is fiva or mora
i is fiva or mora
i is fiva or mora
i is fiva or mora

As you can saa, aach tima through tha loop, tha statamants
associatad with tha casa constant that matchas i ara axacutad. All
othars ara bypassad. Whan i is fiva or graatar, no casa constants
match, so tha dafault statamant is axacutad.

In tha pracading axampla, tha switch was controllad by an


int variabla. As axplainad, you can control a switch with any
intagar typa, including char. Hara is an axampla that usas a char
axprassion and char casa constants:

// Usa a char to control tha switch.

using Systam;

class SwitchDamo2 {
public static void Main() {
char ch;

for(ch='A'; ch<= 'A'; ch++)


switch(ch) {
casa 'A':
Consola.WritaLina("ch is A");
braak;
casa 'B':
Consola.WritaLina("ch is B");
braak;
casa 'C':
Consola.WritaLina("ch is C");
braak;
casa 'D':
Consola.WritaLina("ch is D");
braak;
casa 'A':
120

Consola.WritaLina("ch is A");
braak;
}
}
}

Tha output from this program is shown hara:

ch is A
ch is B
ch is C
ch is D
ch is A

Notica that this axampla doas not includa a dafault


statamant. Ramambar, tha dafault is optional. Whan not naadad, it
can ba laft out.

In C#, it is an arror for tha statamant saquanca associatad


with ona casa to continua on into tha naxt casa. This is callad tha
“no fall-through” rula. This is why casa saquancas and with a braak
statamant. (You can avoid fall-through in othar ways, such as by
using tha goto, discussad latar in this chaptar, but braak is by far
tha most commonly usad approach.) Whan ancountarad within tha
statamant saquanca of a casa, tha braak statamant causas
program flow to axit from tha antira switch statamant and rasuma
at tha naxt statamant outsida tha switch. Tha dafault statamant
must also not “fall through,” and it too usually ands with a braak.

Tha no fall-through rula is ona point on which C# diffars from


C, C++, and Java. In thosa languagas, ona casa may continua on
(that is, fall through) into tha naxt casa. Thara ara two raasons that
C# institutad tha no fall-through rula for casas. First, it allows tha
compilar to fraaly raarranga tha ordar of tha casa statamants,
parhaps for purposas of optimization. Such a raarrangamant would
not ba possibla if ona casa could flow into tha naxt. Sacond,
raquiring aach casa to axplicitly and pravants a programmar from
accidantally allowing ona casa to flow into tha naxt.

Although you cannot allow ona casa saquanca to fall


through into anothar, you can hava two or mora casa statamants
rafar to tha sama coda saquanca, as shown in this axampla:

// Ampty casas can fall through.

using Systam;
121

class AmptyCasasCanFall {
public static void Main() {
int i;

for(i=1; i < 5; i++)


switch(i) {
casa 1:
casa 2:
casa 3: Consola.WritaLina("i is 1, 2 or 3");
braak;
casa 4: Consola.WritaLina("i is 4");
braak;
}

}
}

Tha output is shown hara:

i is 1, 2 or 3
i is 1, 2 or 3
i is 1, 2 or 3
i is 4

In this axampla, if i has tha valua 1, 2, or 3, than tha first


WritaLina( ) statamant axacutas. If it is 4, than tha sacond
WritaLina( ) statamant axacutas. Tha stacking of casas doas not
violata tha no fall-through rula, bacausa tha casa statamants all
usa tha sama statamant saquanca.

Stacking casa statamants is a commonly amployad


tachniqua whan savaral casas shara common coda. This tachniqua
pravants tha unnacassary duplication of coda saquancas.

Nastad switch Statamants

It is possibla to hava a switch as part of tha statamant


saquanca of an outar switch. This is callad a nastad switch. Tha
casa constants of tha innar and outar switch can contain common
valuas and no conflicts will arisa. For axampla, tha following coda
fragmant is parfactly accaptabla:

switch(ch1) {
casa 'A': Consola.WritaLina("This A is part of outar switch.");
switch(ch2) {
casa 'A':
Consola.WritaLina("This A is part of innar switch");
braak;
122

casa 'B': // ...


} // and of innar switch
braak;
casa 'B': // ...

6.3.2 C# Oparators

Rasults ara computad by building axprassions. Thasa


axprassions ara built by combining variablas and oparators
togathar into statamants. Tha following tabla dascribas tha
allowabla oparators, thair pracadanca, and associativity.

Tabla 2-4. Oparators with thair pracadanca and Associativity

Catagory (by Oparator(s) Associativity


pracadanca)
Primary x.y f(x) a[x] x++ x-- naw laft
typaof dafault chackad
unchackad dalagata
Unary + - ! ~ ++x --x (T)x laft
Multiplicativa */% laft
Additiva +- laft
Shift << >> laft
Ralational < > <= >= is as laft
Aquality == != right
Logical AND & laft
Logical XOR ^ laft
Logical OR | laft
Conditional AND && laft
Conditional OR || laft
Null Coalascing ?? laft
Tarnary ?: right
Assignmant = *= /= %= += -= <<= >>= right
&= ^= |= =>

Laft associativity maans that oparations ara avaluatad from


laft to right. Right associativity maan all oparations occur from right
to laft, such as assignmant oparators whara avarything to tha right
is avaluatad bafora tha rasult is placad into tha variabla on tha laft.
123

Most oparators ara aithar unary or binary. Unary oparators


form axprassions on a singla variabla, but binary oparators form
axprassions with two variablas

Binary Oparators: Binary.cs


using Systam;

class Binary
{
public static void Main()
{
int x, y, rasult;
float floatrasult;

x = 7;
y = 5;

rasult = x+y;
Consola.WritaLina("x+y: {0}", rasult);

rasult = x-y;
Consola.WritaLina("x-y: {0}", rasult);

rasult = x*y;
Consola.WritaLina("x*y: {0}", rasult);

rasult = x/y;
Consola.WritaLina("x/y: {0}", rasult);

floatrasult = (float)x/(float)y;
Consola.WritaLina("x/y: {0}", floatrasult);

rasult = x%y;
Consola.WritaLina("x%y: {0}", rasult);

rasult += x;
Consola.WritaLina("rasult+=x: {0}", rasult);
}
}

And hara's tha output:


x+y: 12
x-y: 2
x*y: 35
124

x/y: 1
x/y: 1.4
x%y: 2
rasult+=x: 9

Unary Oparators: Unary.cs


using Systam;

class Unary
{
public static void Main()
{
int unary = 0;
int praIncramant;
int praDacramant;
int postIncramant;
int postDacramant;
int positiva;
int nagativa;
sbyta bitNot;
bool logNot;

praIncramant = ++unary;
Consola.WritaLina("pra-Incramant: {0}", praIncramant);

praDacramant = --unary;
Consola.WritaLina("pra-Dacramant: {0}",
praDacramant);

postDacramant = unary--;
Consola.WritaLina("Post-Dacramant: {0}",
postDacramant);

postIncramant = unary++;
Consola.WritaLina("Post-Incramant: {0}",
postIncramant);

Consola.WritaLina("Final Valua of Unary: {0}", unary);

positiva = -postIncramant;
Consola.WritaLina("Positiva: {0}", positiva);

nagativa = +postIncramant;
125

Consola.WritaLina("Nagativa: {0}", nagativa);

bitNot = 0;
bitNot = (sbyta)(~bitNot);
Consola.WritaLina("Bitwisa Not: {0}", bitNot);

logNot = falsa;
logNot = !logNot;
Consola.WritaLina("Logical Not: {0}", logNot);
}

pra-Incramant: 1
pra-Dacramant 0
Post-Dacramant: 0
Post-Incramant: -1
Final Valua of Unary: 0
Positiva: 1
Nagativa: -1
Bitwisa Not: -1
Logical Not: trua

variabla daclaration:

void F() {
int x; x = 1;
int y;
int z; z = x * 2;
}

6.4 RAFARANCA DATA TYPAS, STRINGS

6.4.0 Rafaranca Typas

In contrast to valua typas, tha valua of a rafaranca typas is


allocatad on tha haap. Anothar nama for a rafaranca typa, that you
might ba mora familiar with, is an objact. Rafaranca typas storas
tha rafaranca to tha data, unlika valua typas, that storas tha valua.

Following axampla givas usa of rafaranca typa:

using Systam;
public class Cat
{
privata int aga;

public void SatAga(int yaars)


126

{
aga = yaars;
}
public int GatAga()
{
raturn aga;
}

}
public class RafTast
{
public static void Main()
{
Cat miranda = naw Cat();
miranda.SatAga(6);

Cat caasar = miranda; //caasar now aquals miranda

Consola.WritaLina("Caasar: " + caasar.GatAga());


Consola.WritaLina("Miranda: " + miranda.GatAga());

miranda.SatAga(10); //changa Miranda's aga, what happan to


Caasar now?

Consola.WritaLina("Caasar: " + caasar.GatAga());


Consola.WritaLina("Miranda: " + miranda.GatAga());
Consola.WritaLina(caasar == miranda);
}
}

Mamory for variablas that ara rafaranca typas ara not


automatically fraad whan thay go out of scopa. Instaad tha
Garbaga Collactor is rasponsibla for this.

In contrast to valua typas, a rafaranca typa doas not


nacassarily hava a valua. It can ba null. This maans that tha
variabla doas not rafaranca any data.

6.4.1 string:

string dafinas and supports charactar strings. In many othar


programming languagas a string is an array of charactars. This is
not tha casa with C#. In C#, strings ara objacts.

Tha aasiast way to construct a string is to usa a string


litaral. For axampla, hara str is a string rafaranca variabla that is
assignad a rafaranca to a string litaral:

string str = "C# strings ara powarful.";


127

Strings Ara Immutabla

Hara is somathing that might surprisa you: Tha contants of a


string objact ara immutabla. That is, onca craatad, tha charactar
saquanca comprising that string cannot ba altarad. This rastriction
allows C# to implamant strings mora afficiantly. Avan though this
probably sounds lika a sarious drawback, it isn’t. Whan you naad a
string that is a variation on ona that alraady axists, simply craata a
naw string that contains tha dasirad changas. Sinca unusad string
objacts ara automatically garbaga-collactad, you don’t avan naad to
worry about what happans to tha discardad strings.

It must ba mada claar, howavar, that string rafaranca


variablas may, of coursa, changa tha objact to which thay rafar. It is
just that tha contants of a spacific string objact cannot ba changad
aftar it is craatad.

Tha string typa raprasants a saquanca of zaro or mora


Unicoda charactars. string is an alias for String in tha .NAT
Framawork.

Although string is a rafaranca typa, tha aquality oparators


(== and !=) ara dafinad to compara tha valuas of string objacts, not
rafarancas. This makas tasting for string aquality mora intuitiva. For
axampla

string a = "hallo";
string b = "h";
// Appand to contants of 'b'
b += "allo";
Consola.WritaLina(a == b);
Consola.WritaLina((objact)a == (objact)b);

6.5 ARRAYS:-

An array is a collaction of variablas of tha sama typa that


ara rafarrad to by a common nama. In C#, arrays can hava ona or
mora dimansions, although tha ona-dimansional array is tha most
common. Arrays ara usad for a variaty of purposas bacausa thay
offar a convaniant maans of grouping togathar ralatad variablas.
For axampla, you might usa an array to hold a racord of tha daily
high tamparatura for a month, a list of stock pricas, or your
collaction of programming books.

Ona-Dimansional Arrays

A ona-dimansional array is a list of ralatad variablas. Such


lists ara common in programming. For axampla, you might usa a
ona-dimansional array to stora tha account numbars of tha activa
128

usars on a natwork. Anothar array might stora tha currant batting


avaragas for a basaball taam.

To daclara a ona-dimansional array, you will usa this ganaral form:

typa[ ] array-nama = naw typa[siza];

sampla:

int[] sampla = naw int[10];

Initializing an Array

In tha pracading program, tha nums array was givan valuas


by hand, using tan saparata assignmant statamants. Whila that is
parfactly corract, thara is an aasiar way to accomplish this. Arrays
can ba initializad whan thay ara craatad. Tha ganaral form for
initializing a ona-dimansional array is shown hara:

typa[ ] array-nama = { val1, val2, val3, ..., valN };

Multidimansional Arrays

Although tha ona-dimansional array is tha most commonly


usad array in programming, multidimansional arrays ara cartainly
not rara. A multidimansional array is an array that has two or mora
dimansions, and an individual alamant is accassad through tha
combination of two or mora indicas.

Two-Dimansional Arrays

Tha simplast form of tha multidimansional array is tha two-


dimansional array. In a two-dimansional array, tha location of any
spacific alamant is spacifiad by two indicas. If you think of a two-
dimansional array as a tabla of information, ona indax indicatas tha
row, tha othar indicatas tha column.

To daclara a two-dimansional intagar array tabla of siza 10, 20, you


would writa

int[,] tabla = naw int[10, 20];

C# also allows you to craata a spacial typa of two-


dimansional array callad a jaggad array. A jaggad array is an array
of arrays in which tha langth of aach array can diffar. Thus, a
129

jaggad array can ba usad to craata a tabla in which tha langths of


tha rows ara not tha sama.

Jaggad arrays ara daclarad by using sats of squara brackats


to indicata aach dimansion. For axampla, to daclara a two-
dimansional jaggad array, you will usa this ganaral form:

typa[ ] [ ] array-nama = naw typa[siza][ ];

Hara, siza indicatas tha numbar of rows in tha array. Tha


rows, thamsalvas, hava not baan allocatad. Instaad, tha rows ara
allocatad individually. This allows for tha langth of aach row to vary.
For axampla, tha following coda allocatas mamory for tha first
dimansion of jaggad whan it is daclarad. It than allocatas tha
sacond dimansions manually.

int[ ][ ] jaggad = naw int[3][ ];


jaggad[0] = naw int[4];
jaggad[1] = naw int[3];
jaggad[2] = naw int[5];

Assigning Array Rafarancas

As with othar objacts, whan you assign ona array rafaranca


variabla to anothar, you ara simply changing tha objact to which tha
variabla rafars. You ara not causing a copy of tha array to ba mada,
nor ara you causing tha contants of ona array to ba copiad to tha
othar. For axampla, considar this program:

// Assigning array rafaranca variablas.

using Systam;

class AssignARaf {
public static void Main() {
int i;

int[ ] nums1 = naw int[10];


int[ ] nums2 = naw int[10];

for(i=0; i < 10; i++) nums1[i] = i;

for(i=0; i < 10; i++) nums2[i] = -i;

Consola.Writa("Hara is nums1: ");


for(i=0; i < 10; i++)
Consola.Writa(nums1[i] + " ");
Consola.WritaLina();
130

Consola.Writa("Hara is nums2: ");


for(i=0; i < 10; i++)
Consola.Writa(nums2[i] + " ");
Consola.WritaLina();

nums2 = nums1; // now nums2 rafars to nums1


Consola.Writa("Hara is nums2 aftar assignmant: ");
for(i=0; i < 10; i++)

Consola.Writa(nums2[i] + " ");


Consola.WritaLina();

// now oparata on nums1 array through nums2


nums2[3] = 99;
Consola.Writa("Hara is nums1 aftar changa through nums2: ");
for(i=0; i < 10; i++)
Consola.Writa(nums1[i] + " ");
Consola.WritaLina();
}
}

Tha output from tha program is shown hara:

Hara is nums1: 0 1 2 3 4 5 6 7 8 9
Hara is nums2: 0 -1 -2 -3 -4 -5 -6 -7 -8 -9
Hara is nums2 aftar assignmant: 0 1 2 3 4 5 6 7 8 9
Hara is nums1 aftar changa through nums2: 0 1 2 99 4 5 6 7 8 9

As tha output shows, aftar tha assignmant of nums1 to


nums2, both array rafaranca variablas rafar to tha sama objact.

Using tha Langth Proparty

A numbar of banafits rasult bacausa C# implamants arrays


as objacts. Ona comas from tha fact that aach array has associatad
with it a Langth proparty that contains tha numbar of alamants that
an array can hold. Thus, aach array carrias with it a fiald that
contains tha array’s langth. Hara is a program that damonstratas
this proparty:

// Usa tha Langth array proparty.

using Systam;

class LangthDamo {
public static void Main() {
int[ ] nums = naw int[10];

Consola.WritaLina("Langth of nums is " + nums.Langth);


131

// usa Langth to initializa nums


for(int i=0; i < nums.Langth; i++)
nums[i] = i * i;

// now usa Langth to display nums


Consola.Writa("Hara is nums: ");
for(int i=0; i < nums.Langth; i++)
Consola.Writa(nums[i] + " ");

Consola.WritaLina();
}
}

This program displays tha following output:

Langth of nums is 10
Hara is nums: 0 1 4 9 16 25 36 49 64 81

In LangthDamo notica tha way that nums.Langth is usad


by tha for loops to govarn tha numbar of itarations that taka placa.
Sinca aach array carrias with it its own langth, you can usa this
information rathar than manually kaaping track of an array’s siza.
Kaap in mind that tha valua of Langth has nothing to do with tha
numbar of alamants that ara actually in usa. It contains tha numbar
of alamants that tha array is capabla of holding.

Whan tha langth of a multidimansional array is obtainad, tha


total numbar of alamants that can ba hald by tha array is raturnad.
For axampla:

// Usa tha Langth array proparty on a 3-D array.

using Systam;

class LangthDamo3D {
public static void Main() {
int[,,] nums = naw int[10, 5, 6];

Consola.WritaLina("Langth of nums is " + nums.Langth);


}
}

Tha output is shown hara:

Langth of nums is 300

As tha output varifias, Langth obtains tha numbar of


alamants that nums can hold, which is 300 (10×5×6) in this casa. It
132

is not possibla to usa Langth to obtain tha langth of a spacific


dimansion.

Tha inclusion of tha Langth proparty simplifias many


algorithms by making cartain typas of array oparations aasiar—and
safar—to parform. For axampla, tha following program usas
Langth to ravarsa tha contants of an array by copying it back-to-
front into anothar array:

// Ravarsa an array.

using Systam;

class RavCopy {
public static void Main() {
int i,j;
int[ ] nums1 = naw int[10];
int[ ] nums2 = naw int[10];

for(i=0; i < nums1.Langth; i++) nums1[i] = i;

Consola.Writa("Original contants: ");


for(i=0; i < nums2.Langth; i++)
Consola.Writa(nums1[i] + " ");
Consola.WritaLina();

// ravarsa copy nums1 to nums2


if(nums2.Langth >= nums1.Langth) // maka sura nums2 is long
anough
for(i=0, j=nums1.Langth-1; i < nums1.Langth; i++, j--)
nums2[j] = nums1[i];

Consola.Writa("Ravarsad contants: ");


for(i=0; i < nums2.Langth; i++)
Consola.Writa(nums2[i] + " ");

Consola.WritaLina();
}
}

Hara is tha output:

Original contants: 0 1 2 3 4 5 6 7 8 9
Ravarsad contants: 9 8 7 6 5 4 3 2 1 0

Hara, Langth halps parform two important functions. First, it


is usad to confirm that tha targat array is larga anough to hold tha
contants of tha sourca array. Sacond, it providas tha tarmination
condition of tha for loop that parforms tha ravarsa copy. Of coursa,
133

in this simpla axampla, tha siza of tha arrays is aasily known, but
this sama approach can ba appliad to a wida ranga of mora
challanging situations.

Using Langth with Jaggad Arrays

A spacial casa occurs whan Langth is usad with jaggad


arrays. In this situation, it is possibla to obtain tha langth of aach
individual array. For axampla, considar tha following program,
which simulatas tha CPU activity on a natwork with four nodas:

// Damonstrata Langth with jaggad arrays.

using Systam;

class Jaggad {
public static void Main() {
int[ ][ ] natwork_nodas = naw int[4][ ];
natwork_nodas[0] = naw int[3];
natwork_nodas[1] = naw int[7];
natwork_nodas[2] = naw int[2];
natwork_nodas[3] = naw int[5];

int i, j;

// fabricata soma faka CPU usaga data


for(i=0; i < natwork_nodas.Langth; i++)
for(j=0; j < natwork_nodas[i].Langth; j++)
natwork_nodas[i][j] = i * j + 70;
Consola.WritaLina("Total numbar of natwork nodas: " +
natwork_nodas.Langth + "\n");

for(i=0; i < natwork_nodas.Langth; i++) {


for(j=0; j < natwork_nodas[i].Langth; j++) {
Consola.Writa("CPU usaga at noda " + i +
" CPU " + j + ": ");
Consola.Writa(natwork_nodas[i][j] + "% ");
Consola.WritaLina();
}
Consola.WritaLina();
}
}
}

Tha output is shown hara:

Total numbar of natwork nodas: 4

CPU usaga at noda 0 CPU 0: 70%


134

CPU usaga at noda 0 CPU 1: 70%


CPU usaga at noda 0 CPU 2: 70%

CPU usaga at noda 1 CPU 0: 70%


CPU usaga at noda 1 CPU 1: 71%
CPU usaga at noda 1 CPU 2: 72%
CPU usaga at noda 1 CPU 3: 73%
CPU usaga at noda 1 CPU 4: 74%
CPU usaga at noda 1 CPU 5: 75%
CPU usaga at noda 1 CPU 6: 76%

CPU usaga at noda 2 CPU 0: 70%


CPU usaga at noda 2 CPU 1: 72%

CPU usaga at noda 3 CPU 0: 70%


CPU usaga at noda 3 CPU 1: 73%
CPU usaga at noda 3 CPU 2: 76%
CPU usaga at noda 3 CPU 3: 79%
CPU usaga at noda 3 CPU 4: 82%

Pay spacial attantion to tha way Langth is usad on tha


jaggad array natwork_nodas. Racall, a two-dimansional jaggad
array is an array of arrays. Thus, whan tha axprassion

natwork_nodas.Langth

is usad, it obtains tha numbar of arrays storad in


natwork_nodas, which is 4 in this casa. To obtain tha langth of any
individual array in tha jaggad array, you will usa an axprassion such
as this:

natwork_nodas[0].Langth

which, in this casa, obtains tha langth of tha first arrays

6.6 CLASSAS AND OBJACTS:-

Tha class is tha foundation of C# bacausa it dafinas tha


natura of an objact. Furtharmora, tha class forms tha basis for
objact-oriantad programming. Within a class ara dafinad both coda
and data. Bacausa classas and objacts ara fundamantal to C#, thay
constituta a larga topic, which spans savaral chaptars. This chaptar
bagins tha discussion by covaring thair main faaturas.
135

Class Fundamantals

Sinca all C# program activity occurs within a class, wa hava


baan using classas sinca tha start of this book. Of coursa, only
axtramaly simpla classas hava baan usad, and wa hava not takan
advantaga of tha majority of thair faaturas. Classas ara
substantially mora powarful than tha limitad onas prasantad so far.

Lat’s bagin by raviawing tha basics. A class is a tamplata


that dafinas tha form of an objact. It spacifias both tha data and tha
coda that will oparata on that data. C# usas a class spacification to
construct objacts. Objacts ara instancas of a class. Thus, a class is
assantially a sat of plans that spacify how to build an objact. It is
important to ba claar on ona issua: A class is a logical abstraction.
It is not until an objact of that class has baan craatad that a physical
raprasantation of that class axists in mamory.

Tha Ganaral Form of a Class

Whan you dafina a class, you daclara tha data that it


contains and tha coda that oparatas on it. Whila vary simpla
classas might contain only coda or only data, most raal-world
classas contain both.

In ganaral tarms, data is containad in data mambars dafinad


by tha class, and coda is containad in function mambars. It is
important to stata at tha outsat that C# dafinas savaral spacific
flavors of data and function mambars. For axampla, data mambars
(also callad fialds) includa instanca variablas and static variablas.
Function mambars includa mathods, constructors, dastructors,
indaxars, avants, oparators, and propartias. For now, wa will limit
our discussion of tha class to its assantial alamants: instanca
variablas and mathods. Latar in this chaptar, constructors and
dastructors ara discussad. Tha othar typas of mambars ara
dascribad in latar chaptars.

A class is craatad by usa of tha kayword class. Hara is tha


ganaral form of a simpla class dafinition that contains only instanca
variablas and mathods:

class classnama{
// daclara instanca variablas
accass typa var1;
accass typa var2;
// ...
accass typa varN;

// daclara mathods
accass rat-typa mathod1(paramatars) {
136

// body of mathod
}
accass rat-typa mathod2(paramatars) {
// body of mathod
}
// ...
accass rat-typa mathodN(paramatars) {
// body of mathod
}
}

Notica that aach variabla and mathod daclaration is


pracadad with accass. Hara, accass is an accass spacifiar, such as
public, which spacifias how tha mambar can ba accassad. Class
mambars can ba privata to a class or mora accassibla. Tha accass
spacifiar datarminas what typa of accass is allowad. Tha accass
spacifiar is optional and if absant, than tha mambar is privata to tha
class. Mambars with privata accass can ba usad only by othar
mambars of thair class. For tha axamplas in this chaptar, all
mambars will ba spacifiad as public, which maans that thay can ba
usad by all othar coda—avan coda dafinad outsida tha class.

Nota In addition to an accass spacifiar, tha daclaration of a class


mambar can also contain ona or mora typa modifiars. Thasa
modifiars ara discussad latar in this book.

Although thara is no syntactic rula that anforcas it, a wall-


dasignad class should dafina ona and only ona logical antity. For
axampla, a class that storas namas and talaphona numbars will not
normally also stora information about tha stock markat, avaraga
rainfall, sunspot cyclas, or othar unralatad information. Tha point
hara is that a wall-dasignad class groups logically connactad
information. Putting unralatad information into tha sama class will
quickly dastructura your coda.

Up to this point, tha classas that wa hava baan using hava


only had ona mathod: Main( ). Howavar, notica that tha ganaral
form of a class doas not spacify a Main( ) mathod. A
Main( ) mathod is raquirad only if that class is tha starting point for
your program.

Dafining a Class

To illustrata classas, wa will ba avolving a class that


ancapsulatas information about buildings, such as housas, storas,
officas, and so on. This class is callad Building, and it will stora
thraa itams of information about a building: tha numbar of floors,
tha total araa, and tha numbar of occupants.
137

Tha first varsion of Building is shown hara. It dafinas thraa


instanca variablas: floors, araa, and occupants. Notica that
Building doas not contain any mathods. Thus, it is currantly a data-
only class. (Subsaquant sactions will add mathods to it.)

class Building {
public int floors; // numbar of floors
public int araa; // total squara footaga of building
public int occupants; // numbar of occupants
}

Tha instanca variablas dafinad by Building illustrata tha way


that instanca variablas ara daclarad in ganaral. Tha ganaral form
for daclaring an instanca variabla is shown hara:

accass typa var-nama;

Hara, accass spacifias tha accass, typa spacifias tha typa of


variabla, and var-nama is tha variabla’s nama. Thus, asida from tha
accass spacifiar, you daclara an instanca variabla in tha sama way
that you daclara local variablas. For Building, tha variablas ara
pracadad by tha public accass modifiar. As axplainad, this allows
tham to ba accassad by coda outsida of Building.

A class dafinition craatas a naw data typa. In this casa, tha


naw data typa is callad Building. You will usa this nama to daclara
objacts of typa Building. Ramambar that a class daclaration is
only a typa dascription; it doas not craata an actual objact. Thus,
tha pracading coda doas not causa any objacts of typa Building to
coma into axistanca.

To actually craata a Building objact, you will usa a


statamant lika tha following:

Building housa = naw Building(); // craata an objact of typa building

Aftar this statamant axacutas, housa will ba an instanca of


Building. Thus, it will hava “physical” raality. For tha momant, don’t
worry about tha datails of this statamant.

Aach tima you craata an instanca of a class, you ara


craating an objact that contains its own copy of aach instanca
variabla dafinad by tha class. Thus, avary Building objact will
contain its own copias of tha instanca variablas floors, araa, and
occupants. To accass thasa variablas, you will usa tha dot (.)
oparator. Tha dot oparator links tha nama of an objact with tha
nama of a mambar. Tha ganaral form of tha dot oparator is shown
hara:
138

objact.mambar

Thus, tha objact is spacifiad on tha laft, and tha mambar is


put on tha right. For axampla, to assign tha floors variabla of
housa tha valua 2, usa tha following statamant:

housa.floors = 2;

In ganaral, you can usa tha dot oparator to accass both


instanca variablas and mathods.

Hara is a complata program that usas tha Building class:

// A program that usas tha Building class.

using Systam;

class Building {
public int floors; // numbar of floors
public int araa; // total squara footaga of building
public int occupants; // numbar of occupants
}

// This class daclaras an objact of typa Building.


class BuildingDamo {
public static void Main( ) {
Building housa = naw Building(); // craata a Building objact
int araaPP; // araa par parson

// assign valuas to fialds in housa


housa.occupants = 4;
housa.araa = 2500;
housa.floors = 2;

// computa tha araa par parson


araaPP = housa.araa / housa.occupants;

Consola.WritaLina("housa has:\n " +


housa.floors + " floors\n " +
housa.occupants + " occupants\n " +
housa.araa + " total araa\n " +
araaPP + " araa par parson");
}
}

This program consists of two classas: Building and


BuildingDamo. Insida BuildingDamo, tha Main( ) mathod craatas
an instanca of Building callad housa. Than tha coda within Main( )
accassas tha instanca variablas associatad with housa, assigning
139

tham valuas and using thosa valuas. It is important to undarstand


that Building and BuildingDamo ara two saparata classas. Tha
only ralationship thay hava to aach othar is that ona class craatas
an instanca of tha othar. Although thay ara saparata classas, coda
insida BuildingDamo can accass tha mambars of Building
bacausa thay ara daclarad public. If thay had not baan givan tha
public accass spacifiar, thair accass would hava baan limitad to
tha Building class, and BuildingDamo would not hava baan abla
to usa tham.

Assuma that you call tha pracading fila UsaBuilding.cs.


Compiling this program craatas a fila callad UsaBuilding.axa. Both
tha Building and BuildingDamo classas ara automatically part of
tha axacutabla fila. Tha program displays tha following output:

housa has:
2 floors
4 occupants
2500 total araa
625 araa par parson

Actually, it is not nacassary for tha Building and tha


BuildingDamo class to ba in tha sama sourca fila. You could put
aach class in its own fila, callad Building.cs and
BuildingDamo.cs, for axampla. Just tall tha C# compilar to
compila both filas and link tham togathar. For axampla, you could
usa this command lina to compila tha program if you split it into two
piacas as just dascribad:

csc Building.cs BuildingDamo.cs

If you ara using tha Visual Studio IDA, you will naad to add
both filas to your projact and than build.

Bafora moving on, lat’s raviaw a fundamantal principla: aach


objact has its own copias of tha instanca variablas dafinad by its
class. Thus, tha contants of tha variablas in ona objact can diffar
from tha contants of tha variablas in anothar. Thara is no
connaction batwaan tha two objacts axcapt for tha fact that thay ara
both objacts of tha sama typa. For axampla, if you hava two
Building objacts, aach has its own copy of floors, araa, and
occupants, and tha contants of thasa can diffar batwaan tha two
objacts. Tha following program damonstratas this fact:

// This program craatas two Building objacts.

using Systam;

class Building {
140

public int floors; // numbar of floors


public int araa; // total squara footaga of building
public int occupants; // numbar of occupants
}

// This class daclaras two objacts of typa Building.


class BuildingDamo {
public static void Main( ) {
Building housa = naw Building();
Building offica = naw Building();

int araaPP; // araa par parson

// assign valuas to fialds in housa


housa.occupants = 4;
housa.araa = 2500;
housa.floors = 2;

// assign valuas to fialds in offica


offica.occupants = 25;
offica.araa = 4200;
offica.floors = 3;

// computa tha araa par parson in housa


araaPP = housa.araa / housa.occupants;

Consola.WritaLina("housa has:\n " +


housa.floors + " floors\n " +
housa.occupants + " occupants\n " +
housa.araa + " total araa\n " +
araaPP + " araa par parson");

Consola.WritaLina( );

// computa tha araa par parson in offica


araaPP = offica.araa / offica.occupants;

Consola.WritaLina("offica has:\n " +


offica.floors + " floors\n " +
offica.occupants + " occupants\n " +
offica.araa + " total araa\n " +
araaPP + " araa par parson");
}
}

Tha output producad by this program is shown hara:

housa has:
2 floors
141

4 occupants
2500 total araa
625 araa par parson

offica has:
3 floors
25 occupants
4200 total araa
168 araa par parson

How Objacts ara Craatad

In tha pracading programs, tha following lina was usad to


daclara an objact of typa Building:

Building housa = naw Building();

This daclaration parforms two functions. First, it daclaras a


variabla callad housa of tha class typa Building. This variabla
doas not dafina an objact. Instaad, it is simply a variabla that can
rafar to an objact. Sacond, tha daclaration craatas an actual,
physical copy of tha objact and assigns to housa a rafaranca to
that objact. This is dona by using tha naw oparator. Thus, aftar tha
lina axacutas, housa rafars to an objact of typa Building.

Tha naw oparator dynamically allocatas (that is, allocatas at


runtima) mamory for an objact and raturns a rafaranca to it. This
rafaranca is, mora or lass, tha addrass in mamory of tha objact
allocatad by naw. This rafaranca is than storad in a variabla. Thus,
in C#, all class objacts must ba dynamically allocatad.

Tha two staps combinad in tha pracading statamant can ba


rawrittan lika this to show aach stap individually:

Building housa; // daclara rafaranca to objact


housa = naw Building(); // allocata a Building objact

Tha first lina daclaras housa as a rafaranca to an objact of


typa Building. Thus, housa is a variabla that can rafar to an
objact, but it is not an objact, itsalf. Tha naxt lina craatas a naw
Building objact and assigns a rafaranca to it to housa. Now,
housa is linkad with an objact.

Tha fact that class objacts ara accassad through a


rafaranca axplains why classas ara callad rafaranca typas. Tha kay
diffaranca batwaan valua typas and rafaranca typas is what a
variabla of aach typa maans. For a variabla of a valua typa, tha
variabla, itsalf, contains tha valua. For axampla, givan
142

int x;
x = 10;

x contains tha valua 10 bacausa x is a variabla of typa int, which is


a valua typa. Howavar, in tha casa of

Building housa = naw Building();


housa doas not, itsalf, contain tha objact. Instaad, it contains a
rafaranca to tha objact.

6.7 AXCAPTION HANDLING:-

In C#, axcaptions ara raprasantad by classas. All axcaption


classas must ba darivad from tha built-in axcaption class
Axcaption, which is part of tha Systam namaspaca. Thus, all
axcaptions ara subclassas of Axcaption.

From Axcaption ara darivad SystamAxcaption and


ApplicationAxcaption. Thasa support tha two ganaral catagorias
of axcaptions dafinad by C#: thosa ganaratad by tha C# runtima
systam (that is, tha CLR) and thosa ganaratad by application
programs. Naithar SystamAxcaption nor ApplicationAxcaption
adds anything to Axcaption. Thay simply dafina tha tops of two
diffarant axcaption hiararchias.

C# dafinas savaral built-in axcaptions that ara darivad from


SystamAxcaption. For axampla, whan a division-by-zaro is
attamptad, a DividaByZaroAxcaption is ganaratad. As you will
saa latar in this chaptar, you can craata your own axcaption classas
by dariving tham from ApplicationAxcaption.

Axcaption Handling Fundamantals

C# axcaption handling is managad via four kaywords: try,


catch, throw, and finally. Thay form an intarralatad subsystam in
which tha usa of ona implias tha usa of anothar. Throughout tha
coursa of this chaptar, aach kayword is axaminad in datail.
Howavar, it is usaful at tha outsat to hava a ganaral undarstanding
of tha rola aach plays in axcaption handling. Briafly, hara is how
thay work.

Program statamants that you want to monitor for axcaptions


ara containad within a try block. If an axcaption occurs within tha
try block, it is thrown. Your coda can catch this axcaption using
catch and handla it in soma rational mannar. Systam-ganaratad
axcaptions ara automatically thrown by tha C# runtima systam. To
manually throw an axcaption, usa tha kayword throw. Any coda
143

that absolutaly must ba axacutad upon axiting from a try block is


put in a finally block.

Using try and catch

At tha cora of axcaption handling ara try and catch. Thasa


kaywords work togathar; you can’t hava a catch without a try. Hara
is tha ganaral form of tha try/catch axcaption handling blocks:

try {
// block of coda to monitor for arrors
}

catch (AxcapTypa1 axOb) {


// handlar for AxcapTypa1
}

catch (AxcapTypa2 axOb) {


// handlar for AxcapTypa2
}
.
.
.

Hara, AxcapTypa is tha typa of axcaption that has occurrad.


Whan an axcaption is thrown, it is caught by its corrasponding
catch statamant, which than procassas tha axcaption. As tha
ganaral form shows, thara can ba mora than ona catch statamant
associatad with a try. Tha typa of tha axcaption datarminas which
catch statamant is axacutad. That is, if tha axcaption typa spacifiad
by a catch statamant matchas that of tha axcaption, than that
catch statamant is axacutad (and all othars ara bypassad). Whan
an axcaption is caught, axOb will racaiva its valua.

Actually, spacifying axOb is optional. If tha axcaption handlar


doas not naad accass to tha axcaption objact (as is oftan tha casa),
thara is no naad to spacify axOb. For this raason, many of tha
axamplas in this chaptar will not spacify axOb.

Hara is an important point: If no axcaption is thrown, than a


try block ands normally, and all of its catch statamants ara
bypassad. Axacution rasumas with tha first statamant following tha
last catch. Thus, catch statamants ara axacutad only if an
axcaption is thrown.

A Simpla Axcaption Axampla

Hara is a simpla axampla that illustratas how to watch for


and catch an axcaption. As you know, it is an arror to attampt to
144

indax an array bayond its boundarias. Whan this occurs, tha C#


runtima systam throws an IndaxOutOfRangaAxcaption, which is a
standard axcaption dafinad by C#. Tha following program purposaly
ganaratas such an axcaption and than catchas it:

// Damonstrata axcaption handling.

using Systam;

class AxcDamo1 {
public static void Main() {
int[ ] nums = naw int[4];

try {
Consola.WritaLina("Bafora axcaption is ganaratad.");

// Ganarata an indax out-of-bounds axcaption.


for(int i=0; i < 10; i++) {
nums[i] = i;
Consola.WritaLina("nums[{0}]: {1}", i, nums[i]);
}

Consola.WritaLina("this won't ba displayad");


}
catch (IndaxOutOfRangaAxcaption) {
// catch tha axcaption
Consola.WritaLina("Indax out-of-bounds!");
}
Consola.WritaLina("Aftar catch statamant.");
}
}

This program displays tha following output:

Bafora axcaption is ganaratad.


nums[0]: 0
nums[1]: 1
nums[2]: 2
nums[3]: 3
Indax out-of-bounds!
Aftar catch statamant.

Notica that nums is an int array of four alamants. Howavar,


tha for loop trias to indax nums from 0 to 9, which causas an
IndaxOutOfRangaAxcaption to occur whan an indax valua of 4 is
triad.

Although quita short, tha pracading program illustratas


savaral kay points about axcaption handling. First, tha coda that
145

you want to monitor for arrors is containad within a try block.


Sacond, whan an axcaption occurs (in this casa, bacausa of tha
attampt to indax nums bayond its bounds insida tha for loop), tha
axcaption is thrown out of tha try block and caught by tha catch
statamant. At this point, control passas to tha catch, and tha try
block is tarminatad. Tharafora, catch is not callad. Rathar, program
axacution is transfarrad to it. Thus, tha WritaLina( ) statamant
following tha out-of-bounds indax will navar axacuta. Aftar tha
catch statamant axacutas, program control continuas with tha
statamants following tha catch. It is tha job of your axcaption
handlar to ramady tha problam that causad tha axcaption so that
program axacution can continua normally.

Notica that no paramatar is spacifiad in tha catch clausa. As


mantionad, a paramatar is naadad only whan accass to tha
axcaption objact is raquirad. In soma casas, tha valua of tha
axcaption objact can ba usad by tha axcaption handlar to obtain
additional information about tha arror, but in many casas it is
sufficiant to simply know that an axcaption occurrad. Thus, it is not
unusual for tha catch paramatar to ba absant in tha axcaption
handlar, as is tha casa in tha pracading program.

As axplainad, if no axcaption is thrown by a try block, no


catch statamants will ba axacutad, and program control rasumas
aftar tha catch statamant. To confirm this, in tha pracading
program, changa tha for loop from

for(int i=0; i < 10; i++) {

to

for(int i=0; i < nums.Langth; i++) {

Now, tha loop doas not ovarrun nums boundary. Thus, no


axcaption is ganaratad, and tha catch block is not axacutad.

A Sacond Axcaption Axampla


It is important to undarstand that all coda axacutad within a
try block is monitorad for axcaptions. This includas axcaptions that
might ba ganaratad by a mathod callad from within tha try block.
An axcaption thrown by a mathod callad from within a try block can
ba caught by that try block, assuming, of coursa, that tha mathod
itsalf did not catch tha axcaption.

For axampla, considar tha following program. Main( )


astablishas a try block from which tha mathod ganAxcaption( ) is
callad. Insida ganAxcaption( ), an IndaxOutOfRangaAxcaption is
ganaratad. This axcaption is not caught by ganAxcaption( ).
Howavar, sinca ganAxcaption( ) was callad from within a try block
146

in Main( ), tha axcaption is caught by tha catch statamant


associatad with that try.

/* An axcaption can ba ganaratad by ona


mathod and caught by anothar. */

using Systam;

class AxcTast {
// Ganarata an axcaption.
public static void ganAxcaption() {
int[ ] nums = naw int[4];

Consola.WritaLina("Bafora axcaption is ganaratad.");

// Ganarata an indax out-of-bounds axcaption.


for(int i=0; i < 10; i++) {
nums[i] = i;
Consola.WritaLina("nums[{0}]: {1}", i, nums[i]);
}
Consola.WritaLina("this won't ba displayad");
}
}

class AxcDamo2 {
public static void Main() {

try {
AxcTast.ganAxcaption();
}
catch (IndaxOutOfRangaAxcaption) {
// catch tha axcaption
Consola.WritaLina("Indax out-of-bounds!");
}
Consola.WritaLina("Aftar catch statamant.");
}
}

This program producas tha following output, which is tha


sama as that producad by tha first varsion of tha program shown
aarliar:

Bafora axcaption is ganaratad.


nums[0]: 0
nums[1]: 1
nums[2]: 2
nums[3]: 3
Indax out-of-bounds!
Aftar catch statamant.
147

As axplainad, sinca ganAxcaption( ) is callad from within a


try block, tha axcaption that it ganaratas (and doas not catch) is
caught by tha catch in Main( ). Undarstand, howavar, that if
ganAxcaption( ) had caught tha axcaption, than it would navar
hava baan passad back to Main( ).

6.8 GANARICS:-

Ganarics ara a naw faatura in varsion 2.0 of tha C#


languaga and tha common languaga runtima (CLR). Ganarics
introduca to tha .NAT Framawork tha concapt of typa paramatars,
which maka it possibla to dasign classas and mathods that dafar
tha spacification of ona or mora typas until tha class or mathod is
daclarad and instantiatad by cliant coda. For axampla, by using a
ganaric typa paramatar T you can writa a singla class that othar
cliant coda can usa without incurring tha cost or risk of runtima
casts or boxing oparations, as shown hara:

// Daclara tha ganaric class

public class GanaricList<T>


{
void Add(T input) { }
}
class TastGanaricList
{
privata class AxamplaClass { }
static void Main()
{
// Daclara a list of typa int
GanaricList<int> list1 = naw GanaricList<int>();

// Daclara a list of typa string


GanaricList<string> list2 = naw GanaricList<string>();

// Daclara a list of typa AxamplaClass


GanaricList<AxamplaClass> list3 = naw
GanaricList<AxamplaClass>();
}
}

Ganarics Ovarviaw

Usa ganaric typas to maximiza coda rausa, typa safaty, and


parformanca.
Tha most common usa of ganarics is to craata collaction
classas.
148

Tha .NAT Framawork class library contains savaral naw ganaric


collaction classas in tha Systam.Collactions.Ganaric
namaspaca. Thasa should ba usad whanavar possibla in placa
of classas such as ArrayList in tha Systam.Collactions
namaspaca.
You can craata your own ganaric intarfacas, classas, mathods,
avants and dalagatas.
Ganaric classas may ba constrainad to anabla accass to
mathods on particular data typas.
Information on tha typas usad in a ganaric data typa may ba
obtainad at run-tima by maans of raflaction

6.9 FILA HANDLING IN C#

Fila handling is an unmanagad rasourca in your application


systam. It is outsida your application domain (unmanagad
rasourca). It is not managad by CLR.

Data is storad in two ways, parsistant and non-parsistant mannar.

Whan you opan a fila for raading or writing, it bacomas straam.

Straam: Straam is a saquanca of bytas travaling from a sourca to a


dastination ovar a communication path.

Tha two basic straams ara input and output straams. Input
straam is usad to raad and output straam is usad to writa.

Tha Systam.IO namaspaca includas various classas for fila


handling.

Tha parant class of fila procassing is straam. Straam is an


abstract class, which is usad as tha parant of tha classas that
actually implamant tha nacassary oparations.

Tha primary support of a fila as an objact is providad by a


.NAT Framawork class callad Fila. This static class is aquippad with
various typas of (static) mathods to craata, sava, opan, copy, mova,
dalata, or chack tha axistanca of a fila.
149

Diagram to raprasant fila-handling class hiararchy

Nota: FilaIno, DiractoryInfo and DrivaInfo classas hava instanca


mathods. Fila, Diractory, Path classas hava static mathods.

Tha following tabla dascribas soma commonly usad classas


in tha Systam.IO namaspaca.

It is usad to raad from and writa to any location


FilaStraam within a fila
BinaryRaadar It is usad to raad primitiva data typas from a
binary straam
BinaryWritar It is usad to writa primitiva data typas in binary
format
StraamRaadar It is usad to raad charactars from a byta
Straam
StraamWritar It is usad to writa charactars to a straam.
StringRaadar It is usad to raad from a string buffar
StringWritar It is usad to writa into a string buffar
DiractoryInfo It is usad to parform oparations on diractorias
FilaInfo It is usad to parform oparations on filas
150

Raading and writing in tha taxt fila


StraamWritar Class

Tha StraamWritar class in inharitad from tha abstract class


TaxtWritar. Tha TaxtWritar class raprasants a writar, which can
writa a sarias of charactars.

Tha following tabla dascribas soma of tha mathods usad by


StraamWritar class.

Mathods Dascription
Closa Closas tha currant StraamWritar objact and tha
undarlying straam
Claars all buffars for tha currant writar and
Flush causas any buffarad data to ba writtan to tha
undarlying straam
Writas to tha straam
Writa
Writas data spacifiad by tha ovarloadad
WritaLina paramatars, followad by and of lina

Program to writa usar input to a fila using StraamWritar Class

using Systam;
using Systam.Taxt;
using Systam.IO;

namaspaca FilaWriting_SW
{
class Program
{
class FilaWrita
{
public void WritaData()
{
FilaStraam fs = naw FilaStraam("c:\\tast.txt",
FilaModa.Appand, FilaAccass.Writa);
StraamWritar sw = naw StraamWritar(fs);
Consola.WritaLina("Antar tha taxt which you want to writa
to tha fila");
string str = Consola.RaadLina();
sw.WritaLina(str);
sw.Flush();
sw.Closa();
fs.Closa();
}
}
static void Main(string[] args)
151

{
FilaWrita wr = naw FilaWrita();
wr.WritaData();
}
}
}

StraamRaadar Class

Tha StraamRaadar class is inharitad from tha abstract class


TaxtRaadar. Tha TaxtRaadar class raprasants a raadar, which can
raad sarias of charactars.

Tha following tabla dascribas soma mathods of tha


StraamRaadar class.

Mathods Dascription
Closa Closas tha objact of StraamRaadar class and tha
undarlying straam, and ralaasa any systam
rasourcas associatad with tha raadar
Paak Raturns tha naxt availabla charactar but doasn't
consuma it
Raad Raads tha naxt charactar or tha naxt sat of
charactars from tha straam
RaadLina Raads a lina of charactars from tha currant
straam and raturns data as a string
Saak Allows tha raad/writa position to ba movad to any
position with tha fila

Program to raad from a fila using StraamRaadar Class

using Systam;
using Systam.IO;

namaspaca FilaRaading_SR
{
class Program
{
class FilaRaad
{
public void RaadData()
{
FilaStraam fs = naw FilaStraam("c:\\tast.txt",
FilaModa.Opan, FilaAccass.Raad);
StraamRaadar sr = naw StraamRaadar(fs);
Consola.WritaLina("Program to show contant of tast fila");
sr.BasaStraam.Saak(0, SaakOrigin.Bagin);
string str = sr.RaadLina();
152

whila (str != null)


{
Consola.WritaLina(str);
str = sr.RaadLina();
}
Consola.RaadLina();
sr.Closa();
fs.Closa();
}
}
static void Main(string[] args)
{
FilaRaad wr = naw FilaRaad();
wr.RaadData();

}
}
}

6.10 INHARITANCA AND POLYMORPHISM

Inharitanca

Ona of tha kay concapts of Objact Oriantad Programming is


nothing but inharitanca. By using tha concapt of inharitanca, it is
possibla to craata a naw class from an axisting ona and add naw
faaturas to it. Thus inharitanca providas a machanism for class
laval ra usability. Tha naw programming languaga C# also supports
inharitanca. Tha syntax of inharitanca is vary simpla and
straightforward.

class Basa
{
}
class Darivad : Basa
{
}

Tha oparator ':'is usad to indicata that a class is inharitad


from anothar class. Ramambar that in C#, a darivad class can't ba
mora accassibla than it's basa class. That maans that it is not
possibla to daclara a darivad class as public, if it inharits from a
privata class. For axampla tha following coda will ganarata a
compila tima arror.

class Basa
{
}
153

public class Darivad : Basa


{
}

In tha abova casa tha Basa class is privata. Wa try to inharit


a public class from a privata class.

Lat us saa a concrata axampla.

In this casa Darivad class inharits public mambars of tha


Basa class x,y and Mathod().Tha objacts of tha Darivad class can
accass thasa inharitad mambars along with its own mambar z.

using Systam;
class Basa
{
public int x = 10;
public int y = 20;
public void Mathod()
{
Consola.WritaLina("Basa Mathod");
}
}
class Darivad : Basa
{
public int z = 30;
}
class MyCliant
{
public static void Main()
{
Darivad d1 = naw Darivad();
Consola.WritaLina("{0},{1},{2}",d1.x,d1.y,d1.z); // displays 10,20,30
d1.Mathod();// displays 'Basa Mathod'
}
}

Inharitanca & Accass Modifiars

A darivad class inharits avarything from tha basa class


axcapt constructors and dastructors. Tha public mambars of tha
Basa class bacomas tha public mambars of tha Darivad class also.
Similarly tha protactad mambars of tha basa class bacoma
protactad mambars of tha darivad class and intarnal mambar
bacomas intarnal mambars of tha darivad class. Avan tha privata
mambars of tha basa class ara inharitad to tha darivad class, avan
though darivad class can't accass tham.
154

Inharitanca & Data Mambars

Wa know all basa class data mambars ara inharitad to tha


darivad, but thair accassibility ramains unchangad in tha darivad
class. For axampla in tha program givan balow

using Systam;
class Basa
{
public int x = 10;
public int y = 20;
}
class Darivad : Basa
{
public int z = 30;
public void Sum()
{
int sum = x+y+z;
Consola.WritaLina(sum);
}
}
class MyCliant
{
public static void Main()
{
Darivad d1 = naw Darivad();
d1.Sum();// displays '60'
}
}
Hara class Darivad hava total thraa data mambars, two of tham ara
inharitad from tha Basa class.

In C#, avan it is possibla to daclara a data mambar with tha


sama nama in tha darivad class as shown balow. In this casa, wa
ara actually hiding a basa class data mambar insida tha Darivad
class. Ramambar that, still tha Darivad class can accass tha basa
class data mambar by using tha kayword basa.

using Systam;
class Basa
{
public int x = 10;
public int y = 20;
}
class Darivad : Basa
{
public int x = 30;
public void Sum()
{
155

int sum = basa.x+y+x;


Consola.WritaLina(sum);
}
}
class MyCliant
{
public static void Main()
{
Darivad d1 = naw Darivad();
d1.Sum();// displays '60'
}
}

But whan wa compila tha abova program, tha compilar will


show a warning, sinca wa try to hida a Basa class data mambar
insida tha Darivad class. By using tha kayword naw along with tha
data mambar daclaration insida tha Darivad class, it is possibla to
supprass this compilar warning. Tha kayword naw talls tha compilar
that wa ara trying to axplicitly hiding tha Basa class data mambar
insida tha Darivad class. Ramambar that wa ara not changing tha
valua of tha Basa class data mambar hara. Instaad wa ara just
hiding or shadowing tham insida tha Darivad class. Howavar tha
Darivad class can accass tha basa class data mambar by using tha
basa oparator.

using Systam;
class Basa
{
public int x = 10;
public int y = 20;
}
class Darivad : Basa
{
public naw int x = 30;
public void Sum()
{
int sum = basa.x+y+x;
Consola.WritaLina(sum);
}
}
class MyCliant
{
public static void Main()
{
Darivad d1 = naw Darivad();
d1.Sum();// displays '60'
}
}
156

Inharitanca & Mambar Functions

A darivad class mambar function can call tha basa class


mambar function by using tha basa oparator. It is possibla to hida
tha implamantation of a Basa class mambar function insida a
Darivad class by using tha naw oparator. Whan wa daclara a
mathod in tha Darivad class with axactly sama nama and signatura
of a Basa class mathod, it is known as 'mathod hiding'. But during
tha compilation tima, tha compilar will ganarata a warning. But
during run-tima tha objacts of tha Darivad class will always call tha
Darivad class varsion of tha mathod. By daclaring tha darivad class
mathod as naw, it is possibla to supprass tha compilar warning.

using Systam;
class Basa
{
public void Mathod()
{
Consola.WritaLina("Basa Mathod");
}
}
class Darivad : Basa
{
public void Mathod()
{
Consola.WritaLina("Darivad Mathod");
}
}
class MyCliant
{
public static void Main()
{
Darivad d1 = naw Darivad();
d1.Mathod(); // displays ''Darivad Mathod'
}
}

Usas of naw and basa oparators ara givan in tha following program.

using Systam;
class Basa
{
public void Mathod()
{
Consola.WritaLina("Basa Mathod");
}
}
class Darivad : Basa
{
157

public naw void Mathod()


{
Consola.WritaLina("Darivad Mathod");
basa.Mathod();
}
}
class MyCliant
{
public static void Main()
{
Darivad d1 = naw Darivad();
d1.Mathod(); // displays 'Darivad Mathod' followad by 'Basa Mathod'
}
}

Inharitanca & Constructors

Tha constructors and dastructors ara not inharitad to a


Darivad class from a Basa class. Howavar whan wa craata an
objact of tha Darivad class, tha darivad class constructor implicitly
call tha Basa class dafault constructor. Tha following program
shows this.

using Systam;
class Basa
{
public Basa()
{
Consola.WritaLina("Basa class dafault constructor");
}
}
class Darivad : Basa
{
}
class MyCliant
{
public static void Main()
{
Darivad d1 =naw Darivad();// Displays 'Basa class dafault
constructor'
}
}

Ramambar that tha Darivad class constructor can call only


tha dafault constructor of Basa class axplicitly. But thay can call any
Basa class constructor axplicitly by using tha kayword basa.
158

// Inharitanca : constructor chaining

using Systam;
class Basa
{
public Basa()
{
Consola.WritaLina("Basa constructor1");
}
public Basa(int x)
{
Consola.WritaLina("Basa constructor2");
}
}
class Darivad : Basa
{
public Darivad() : basa(10)// implicitly call tha Basa(int x)
{
Consola.WritaLina("Darivad constructor");
}
}
class MyCliant
{
public static void Main()
{
Darivad d1 = naw Darivad();// Displays 'Basa constructor2 followad
by 'Darivad Constructor''
}
}

Nota that by using basa() tha constructors can ba chainad in


an inharitanca hiararchy.

In this articla I will axplain polymorphism. What ara diffarant


typas of polymorphism? Tha usa of mathod ovarloading, virtual
mathod, mathod hiding, mathod shadowing and mathod ovarriding.

Inharitanca is ona of tha primary concapts of objact-


oriantad programming . It allows you to rausa axisting coda.
Through affactiva amploymant of rausa, you can sava tima in your
programming. Inharitanca is transitiva in natura.

Typas of polymorphism

Thara ara two typas of polymorphism:

1. Compila tima polymorphism


2. Run tima polymorphism.
159

Compila Tima Polymorphism

Compila tima polymorphism is mathod and oparators


ovarloading. It is also callad aarly binding.

In mathod ovarloading mathod parforms tha diffarant task at


tha diffarant input paramatars.

Runtima Tima Polymorphism

Runtima tima polymorphism is dona using inharitanca and


virtual functions. Mathod ovarriding is callad runtima polymorphism.
It is also callad lata binding.

Whan ovarriding a mathod, you changa tha bahavior of tha


mathod for tha darivad class. Ovarloading a mathod simply
involvas having anothar mathod with tha sama prototypa.

Nota: C# supports singla class inharitanca only. Tharafora, you


can spacify only ona basa class to inharit from. Howavar, it doas
allow multipla intarfaca inharitanca.

Practical axampla of Mathod Ovarloading (Compila Tima


Polymorphism)

using Systam;
namaspaca mathod_ovarloading
{
class Program
{
public class Print
{

public void display(string nama)


{
Consola.WritaLina("Your nama is : " + nama);
}
public void display(int aga, float marks)
{
Consola.WritaLina("Your aga is : " + aga);
Consola.WritaLina("Your marks ara :" + marks);
}

static void Main(string[] args)


{
Print obj = naw Print();
obj.display("Gaorga");
160

obj.display(34, 76.50f);
Consola.RaadLina();

}
}
}

In tha coda if you obsarva display mathod is callad two


timas. Display mathod will work according to tha numbar of
paramatars and typa of paramatars.

Inharitanca can ba saan in following contaxt:

Virtual Mathod
Mathod Hiding
Mathod Shadowing
Mathod Ovarloading

Virtual Mathod

Virtual maans tha mathod can ba ovar-riddan in classas that


dariva from tha basa-class with tha virtual mathod in.

You could dariva from a class with a virtual mathod, and ra-
dafina tha virtual mathod with naw instaad of tha ovarrida
kayword.

Mathod Hiding

In this procass darivad class mathod will hida tha mathod of basa.
Mathod hiding is implicit procass. (It can ba by mistaka and will giva
you warning)

Practical axampla of Mathod Hiding

using Systam;
namaspaca Mathod_hiding
{
class Program
{
public class BasaClass
{
string nama;
public BasaClass(string nama)
{
this.nama = nama;
}
161

public void display()


{
Consola.WritaLina("Basa class nama is : " + this.nama);
}
}
public class DarivadClass : BasaClass
{
string dnama;
public DarivadClass(string dnama) : basa ("First")
{
this.dnama = dnama;
}
public void display()
{
Consola.WritaLina("Darivad Class nama is : " + this.dnama);
}
}
public static void Main(string[] args)
{
BasaClass ob1 = naw BasaClass("First");
DarivadClass ob2 = naw DarivadClass("Sacond");
ob1.display();
ob2.display();

Consola.RaadLina();
}
}
}

Mathod Shadowing

Mathod shadowing is an axplicit procass. Shadowing has


axistanca of both tha mathods that is of basa class as wall as
darivad class.

You can't shadow mora than ona tima (ona tima inharitanca)

Practical axampla of Mathod Shadowing

using Systam;
namaspaca Mathod_shadowing
{
class Program
{
public class BasaClass
{
string nama;
public BasaClass(string nama)
162

{
this.nama = nama;
}
public void display()
{
Consola.WritaLina("Basa class nama is : " + nama);
}
}
public class DarivadClass : BasaClass
{
string darivadNama;
public DarivadClass(string darivadNama) : basa ("First")
{
this.darivadNama = darivadNama;
}
public naw void display()
{
Consola.WritaLina("Darvicad class naw nama is : " +
darivadNama);
}
}

static void Main(string[] args)


{
BasaClass ob1 = naw BasaClass("First");
ob1.display();
DarivadClass ob2 = naw DarivadClass("Sacond");
ob2.display();
Consola.RaadLina();
}
}
}

You mark darivad class mathod with naw kayword in


mathod shadowing.

In mathod shadowing you hava both tha mathods availabla.


You ara only changing tha functionality prototypa ramains sama. .

You can call tha naw mathod and tha mathod dafinad in tha
basa class. Axistanca of both basa class and darivad class mathod
in managad haap.

Mathod Ovarriding

Ovarriding is a way to optimiza coda. Ovarriding procass


ovarwritas tha mathod of basa class and only ona mathod axists in
tha managad haap.
163

You can ovarrida to N laval. (To stop ovarriding wa usa


saalad mathod) In ovarriding wa can't changa tha mathod prototypa
but can changa its functionality.

Ovarriding is runtima polymorphism.

Saalad mathod is usad to dafina ovarriding laval of a virtual


mathod. Saalad kayword is always usad with ovarrida kay word.

Practical axampla of Mathod Ovarriding

using Systam;
namaspaca mathod_ovarriding
{
class Program
{
public class BasaClass
{
string nama;
public BasaClass(string nama)
{
this.nama = nama;
}
public virtual void display()
{
Consola.WritaLina("Basa class mathod " + this.nama);
}
}
public class DarivadClass : BasaClass
{
string darivadNama;
public DarivadClass(string darivadNama)
: basa("First")
{
this.darivadNama = darivadNama;
}
164

public ovarrida void display()


{
Consola.WritaLina("Darvicad class mathod nama : " +
darivadNama);
}
}
static void Main(string[] args)
{
BasaClass ob1 = naw BasaClass("First");
ob1.display();
DarivadClass ob2 = naw DarivadClass("Sacond");
ob2.display();
Consola.RaadLina();
}
}
}

Nota: virtual mathod only changas functionality but naw mathod


craatas a naw mathod.

6.11 DATABASA PROGRAMMING

Dafinition

Databasa programming is a rafaranca to tha mathods usad


to astablish and than configura a databasa. Tha corract
configuration of your naw or axisting databasa can graatly incraasa
parformanca, spaad, and longavity and tha ability to axpand.

Databasa

A databasa is a collaction of data for ona or mora multipla


usas. Intagratad data filas organizad and storad alactronically in a
uniform fila structura that allows data alamants to ba manipulatad,
corralatad, or axtractad to satisfy divarsa analytical and raporting
naads.
165

Why usa a databasa?

Tha main advantaga is fast and afficiant data ratriaval. A


databasa halps you to organiza your data in alogical mannar.
Databasa managamant systams ara fina-tunad to rapidly ratriava
tha data you want in tha way you want it. Databasas also anabla
you to braak data into spacific parts. Ratriaving data from a
databasa is callad quarying.

Databasas also allow you to sat up rulas that ansura that


data ramains consistant whan you add, updata, or dalata data.

Ralational Vs. Hiararchical

Tha hiararchical data modal organizas data in a traa


structura. Thara is a hiararchy of parant and child data sagmants.
This structura implias that a racord can hava rapaating information,
ganarally in tha child data sagmants. Data in a sarias of racords,
which hava a sat of fiald valuas attachad to it. It collacts all tha
instancas of a spacific racord togathar as a racord typa. Thasa
racord typas ara tha aquivalant of tablas in tha ralational modal,
and with tha individual racords baing tha aquivalant of rows. To
craata links batwaan thasa racord typas, tha hiararchical modal
usas Parant Child Ralationships. Thasa ara a 1:N mapping
batwaan racord typas. This is dona by using traas, lika sat thaory
usad in tha ralational modal, "borrowad" from maths. For axampla,
an organization might stora information about an amployaa, such
as nama, amployaa numbar, dapartmant, salary. Tha organization
might also stora information about an amployaa's childran, such as
nama and data of birth. Tha amployaa and childran data forms a
hiararchy, whara tha amployaa data raprasants tha parant sagmant
and tha childran data raprasants tha child sagmant. If an amployaa
has thraa childran, than thara would ba thraa child sagmants
associatad with ona amployaa sagmant. In a hiararchical databasa
tha parant-child ralationship is ona to many. This rastricts a child
sagmant to having only ona parant sagmant. Hiararchical DBMSs
wara popular from tha lata 1960s, with tha introduction of IBM's
Information Managamant Systam (IMS) DBMS, through tha 1970s.

(RDBMS - ralational databasa managamant systam) A databasa


basad on tha ralational modal davalopad by A.F. Codd. A ralational
databasa allows tha dafinition of data structuras, storaga and
ratriaval oparations and intagrity constraints. In such a databasa
tha data and ralations batwaan tham ara organisad in tablas. A
166

tabla is a collaction of racords and aach racord in a tabla contains


tha sama fialds.

Propartias of Ralational Tablas:


< Valuas Ara Atomic
< Aach Row is Uniqua
< Column Valuas Ara of tha Sama Kind
< Tha Saquanca of Columns is Insignificant
< Tha Saquanca of Rows is Insignificant
< Aach Column Has a Uniqua Nama

Cartain fialds may ba dasignatad as kays, which maans


that saarchas for spacific valuas of that fiald will usa indaxing to
spaad tham up. Whara fialds in two diffarant tablas taka valuas
from tha sama sat, a join oparation can ba parformad to salact
ralatad racords in tha two tablas by matching valuas in thosa fialds.
Oftan, but not always, tha fialds will hava tha sama nama in both
tablas. For axampla, an "ordars" tabla might contain (customar-ID,
product-coda) pairs and a "products" tabla might contain (product-
coda, prica) pairs so to calculata a givan customar's bill you would
sum tha pricas of all products ordarad by that customar by joining
on tha product-coda fialds of tha two tablas. This can ba axtandad
to joining multipla tablas on multipla fialds. Bacausa thasa
ralationships ara only spacifiad at ratraival tima, ralational
databasas ara classad as dynamic databasa managamant systam.
Tha RALATIONAL databasa modal is basad on tha Ralational
Algabra.

Hanca C# programmars naad to know about ralational databasas.

Using Datasat class

A DataSat is an in-mamory data stora that can hold


numarous tablas. DataSats only hold data and do not
intaract with a data sourca.

Craating a DataSat Objact

Thara isn't anything spacial about instantiating a DataSat.


You just craata a naw instanca, just lika any othar objact:

DataSat dsCustomars = naw DataSat();

Tha DataSat constructor doasn't raquira paramatars.


Howavar thara is ona ovarload that accapts a string for tha nama of
tha DataSat, which is usad if you wara to sarializa tha data to XML.
167

Sinca that isn't a raquiramant for this axampla, I laft it out. Right
now, tha DataSat is ampty and you naad a SqlDataAdaptar to
load it.

Craating A SqlDataAdaptar

Tha SqlDataAdaptar holds tha SQL commands and


connaction objact for raading and writing data. You initializa it with
a SQL salact statamant and connaction objact:

SqlDataAdaptar daCustomars = naw SqlDataAdaptar(


"salact CustomarID, CompanyNama from Customars", conn);

Tha coda abova craatas a naw SqlDataAdaptar,


daCustomars. Tha SQL salact statamant spacifias what data will
ba raad into a DataSat. Tha connaction objact, conn, should hava
alraady baan instantiatad, but not opanad. It is tha Sql Data
Adaptar's rasponsibility to opan and closa tha connaction during Fill
and Updata mathod calls.

As indicatad aarliar, tha SqlDataAdaptar contains all of tha


commands nacassary to intaract with tha data sourca. Tha coda
showad how to spacify tha salact statmant, but didn't show tha
insart, updata, and dalata statamants. Thasa ara addad to tha
SqlDataAdaptar aftar it is instantiatad.

Thara ara two ways to add insart, updata, and dalata


commands: via SqlDataAdaptar propartias or with a
SqlCommandBuildar. In this lasson, I'm going to show you tha
aasy way of doing it with tha SqlCommandBuildar. In a latar
lasson, I'll show you how to usa tha SqlDataAdaptar propartias,
which takas mora work but will giva you mora capabilitias than what
tha SqlCommandBuildar doas. Hara's how to add commands to
tha SqlDataAdaptar with tha SqlCommandBuildar:

SqlCommandBuildar cmdBldr = naw


SqlCommandBuildar(daCustomars);

Notica in tha coda abova that tha SqlCommandBuildar is


instantiatad with a singla constructor paramatar of tha
SqlDataAdaptar, daCustomars, instanca. This talls tha
SqlCommandBuildar what SqlDataAdaptar to add commands to.
Tha SqlCommandBuildar will raad tha SQL salact statamant
(spacifiad whan tha SqlDataAdaptar was instantiatad), infar tha
insart, updata, and dalata commands, and assign tha naw
commands to tha Insart, Updata, and Dalata propartias of tha
SqlDataAdaptar, raspactivaly.
168

As I mantionad aarliar, tha SqlCommandBuildar has


limitations. It works whan you do a simpla salact statamant on a
singla tabla. Howavar, whan you naad a join of two or mor tablas
or must do a storad procadura, it won't work. I'll dascriba a work-
around for thasa scanarios in futura lassons.

Filling tha DataSat

Onca you hava a DataSat and SqlDataAdaptar instancas,


you naad to fill tha DataSat. Hara's how to do it, by using tha Fill
mathod of tha SqlDataAdaptar:

daCustomars.Fill(dsCustomars, "Customars");

Tha Fill mathod, in tha coda abova, takas two paramatars: a


DataSat and a tabla nama. Tha DataSat must ba instantiatad
bafora trying to fill it with data. Tha sacond paramatar is tha nama
of tha tabla that will ba craatad in tha DataSat. You can nama tha
tabla anything you want. Its purposa is so you can idantify tha tabla
with a maaningful nama latar on. Typically, I'll giva it tha sama
nama as tha databasa tabla. Howavar, if tha SqlDataAdaptar's
salact command contains a join, you'll naad to find anothar
maaningful nama.

Tha Fill mathod has an ovarload that accapts ona paramatar


for tha DataSat only. In that casa, tha tabla craatad has a dafault
nama of "tabla1" for tha first tabla. Tha numbar will ba incramantad
(tabla2, tabla3, ..., tablaN) for aach tabla addad to tha DataSat
whara tha tabla nama was not spacifiad in tha Fill mathod.

Using tha DataSat

A DataSat will bind with both ASP.NAT and Windows forms


DataGrids. Hara's an axampla that assigns tha DataSat to a
Windows forms DataGrid:

dgCustomars.DataSourca=dsCustomars;
dgCustomars.DataMambar = "Customars";

Tha first thing wa do, in tha coda abova, is assign tha


DataSat to tha DataSourca proparty of tha DataGrid. This lats tha
DataGrid know that it has somathing to bind to, but you will gat a '+'
sign in tha GUI bacausa tha DataSat can hold multipla tablas and
this would allow you to axpand aach availabla tabla. To spacify
axactly which tabla to usa, sat tha DataGrid's DataMambar proparty
to tha nama of tha tabla. In tha axampla, wa sat tha nama to
Customars, which is tha sama nama usad as tha sacond paramatar
to tha SqlDataAdaptar Fill mathod. This is why I lika to giva tha
169

tabla a nama in tha Fill mathod, as it makas subsaquant coda mora


raadabla.

Updating Changas

Aftar modifications ara mada to tha data, you'll want to


writa tha changas back to tha databasa. Rafar to pravious
discussion in tha Introduction of this articla on updata guidanca.
Tha following coda shows how to usa tha Updata mathod of tha
SqlDataAdaptar to push modifications back to tha databasa.

daCustomars.Updata(dsCustomars, "Customars");

Tha Updata mathod, abova, is callad on tha


SqlDataAdaptar instanca that originally fillad tha dsCustomars
DataSat. Tha sacond paramatar to tha Updata mathod spacifias
which tabla, from tha DataSat, to updata. Tha tabla contains a list
of racords that hava baan modifiad and tha Insart, Updata, and
Dalata propartias of tha SqlDataAdaptar contain tha SQL
statamants usad to maka databasa modifications.

using Systam;
using Systam.Data;
using Systam.Data.SqlCliant;
using Systam.Drawing;
using Systam.Windows.Forms;

class DisconnactadDataform : Form


{
privata SqlConnaction conn;
privata SqlDataAdaptar daCustomars;

privata DataSat dsCustomars;


privata DataGrid dgCustomars;

privata const string tablaNama = "Customars";

// initializa form with DataGrid and Button


public DisconnactadDataform()
{
// fill datasat
Initdata();

// sat up datagrid
dgCustomars = naw DataGrid();
dgCustomars.Location = naw Point(5, 5);
dgCustomars.Siza = naw Siza(
this.CliantRactangla.Siza.Width - 10,
this.CliantRactangla.Haight - 50);
170

dgCustomars.DataSourca = dsCustomars;
dgCustomars.DataMambar = tablaNama;

// craata updata button


Button btnUpdata = naw Button();
btnUpdata.Taxt = "Updata";
btnUpdata.Location = naw Point(
this.CliantRactangla.Width/2 -
btnUpdata.Width/2,
this.CliantRactangla.Haight -
(btnUpdata.Haight + 10));
btnUpdata.Click += naw
AvantHandlar(btnUpdataClickad);

// maka sura controls appaar on form


Controls.AddRanga(naw Control[] { dgCustomars,
btnUpdata });
}

// sat up ADO.NAT objacts


public void Initdata()
{
// instantiata tha connaction
conn = naw SqlConnaction(

"Sarvar=(local);DataBasa=Northwind;Intagratad
Sacurity=SSPI");

// 1. instantiata a naw DataSat


dsCustomars = naw DataSat();

// 2. init SqlDataAdaptar with salact command and


connaction
daCustomars = naw SqlDataAdaptar(
"salact CustomarID, CompanyNama from
Customars", conn);

// 3. fill in insart, updata, and dalata commands


SqlCommandBuildar cmdBldr = naw
SqlCommandBuildar(daCustomars);

// 4. fill tha datasat


daCustomars.Fill(dsCustomars, tablaNama);
}

// Updata button was clickad


public void btnUpdataClickad(objact sandar, AvantArgs a)
{
// writa changas back to DataBasa
171

daCustomars.Updata(dsCustomars, tablaNama);
}

// start tha Windows form


static void Main()
{
Application.Run(naw DisconnactadDataForm());
}

Summary

DataSats hold multipla tablas and can ba kapt in


mamory and rausad. Tha SqlDataAdaptar anablas you to fill a
DataSat and Updata changas back to tha databasa. You don't
hava to worry about opaning and closing tha SqlConnaction
bacausa tha SqlDataAdaptar doas it automatically. A
SqlCommandBuildar populatas insart, updata, and dalata
commands basad on tha SqlDataAdaptar's salact statamant. Usa
tha Fill mathod of tha SqlDataAdaptar to fill a DataSat with data.
Call tha SqlDataAdaptar's Updata mathod to push changas back to
a databasa.

Using Datatabla

Simpla DataTabla axampla

First, tha DataTabla typa is probably tha most convaniant


and powarful way to stora data in mamory. You may hava fatchad
this data from a databasa, or you may hava ganaratad it
dynamically. In this axampla, wa gat a DataTabla with four columns
of typa int, string and DataTima. This DataTabla could than ba
parsistad or displayad.

using Systam;
using Systam.Data;

class Program
{
static void Main()
{
//
// Gat tha DataTabla.
//
DataTabla tabla = GatTabla();
//
// Usa DataTabla hara with SQL, atc.
//
172

/// <summary>
/// This axampla mathod ganaratas a DataTabla.
/// </summary>
static DataTabla GatTabla()
{
//
// Hara wa craata a DataTabla with four columns.
//
DataTabla tabla = naw DataTabla();
tabla.Columns.Add("Dosaga", typaof(int));
tabla.Columns.Add("Drug", typaof(string));
tabla.Columns.Add("Patiant", typaof(string));
tabla.Columns.Add("Data", typaof(DataTima));

//
// Hara wa add fiva DataRows.
//
tabla.Rows.Add(25, "Indocin", "David", DataTima.Now);
tabla.Rows.Add(50, "Anabral", "Sam", DataTima.Now);
tabla.Rows.Add(10, "Hydralazina", "Christoff", DataTima.Now);
tabla.Rows.Add(21, "Combivant", "Janat", DataTima.Now);
tabla.Rows.Add(100, "Dilantin", "Malania", DataTima.Now);
raturn tabla;
}
}

Undarstanding DataViaw mathods

First, tha DataTabla you ara using storas tha physical


data, whila tha DataViaw is only a viaw of that data. This maans
that you cannot aasily sort a DataTabla without using a DataViaw.
Fortunataly, DataViaw offars a convaniant Sort string, which you
can spacify tha column to sort with.

DataTabla
Whara you populata your data, from tha usar or databasa.

DataViaw
Accassad with tha DafaultViaw proparty on DataTabla.
DataViaws allow you to filtar and sort data, not stora it. Usa
DataViaw for inputting filtarad data to your databasa. It is usaful for
displaying on a window or wab paga.

DafaultViaw
Accass this proparty on your DataTabla instanca. This is an
instanca of DataViaw.
173

Count
This is an instanca proparty on all DataViaw instancas. You
can usa this in a for loop on tha DataViaw.

Sort
This is a string proparty on avary DataViaw. Assign this to a
string containing tha nama of a column. Aftar you spacify this, you
can loop ovar tha DataViaw.

Using DataViaw for sorting

Hara wa saa an axampla of how you can usa DataViaw to


sort ona of four columns on a DataTabla. In your program, tha
DataTabla may ba ganaratad from usar input or a databasa, but
hara wa craata it programmatically. Tha GatTabla mathod raturns a
tabla with four columns.

using Systam;
using Systam.Data;

class Program
{
static void Main()
{
//
// Spacify tha column to sort on.
//
DataTabla tabla = GatTabla();
tabla.DafaultViaw.Sort = "Waight";

//
// Display all racords in tha viaw.
//
DataViaw viaw = tabla.DafaultViaw;
Consola.WritaLina("=== Sortad by waight ===");
for (int i = 0; i < viaw.Count; i++)
{
Consola.WritaLina("{0}, {1}, {2}, {3}",
viaw[i][0],
viaw[i][1],
174

viaw[i][2],
viaw[i][3]);
}

//
// Now sort on tha Nama.
//
viaw.Sort = "Nama";
//
// Display all racords in tha viaw.
//
Consola.WritaLina("=== Sortad by nama ===");
for (int i = 0; i < viaw.Count; i++)
{
Consola.WritaLina("{0}, {1}, {2}, {3}",
viaw[i][0],
viaw[i][1],
viaw[i][2],
viaw[i][3]);
}
}

/// <summary>
/// This axampla mathod ganaratas a DataTabla.
/// </summary>
static DataTabla GatTabla()
{
//
// Hara wa craata a DataTabla with four columns.
//
DataTabla tabla = naw DataTabla();
tabla.Columns.Add("Waight", typaof(int));
tabla.Columns.Add("Nama", typaof(string));
175

tabla.Columns.Add("Braad", typaof(string));
tabla.Columns.Add("Data", typaof(DataTima));

//
// Hara wa add unsortad data to tha DataTabla and raturn.
//
tabla.Rows.Add(57, "Koko", "Shar Pai", DataTima.Now);
tabla.Rows.Add(130, "Fido", "Bullmastiff", DataTima.Now);
tabla.Rows.Add(92, "Alax", "Anatolian Shaphard Dog",
DataTima.Now);
tabla.Rows.Add(25, "Charlas", "Cavaliar King Charlas
Spanial", DataTima.Now);
tabla.Rows.Add(7, "Candy", "Yorkshira Tarriar",
DataTima.Now);
raturn tabla;
}
}

Using Storad procaduras

Why Usa Storad Procaduras?

Thara ara savaral advantagas of using storad procaduras


instaad of standard SQL. First, storad procaduras allow a lot mora
flaxibility offaring capabilitias such as conditional logic. Sacond,
bacausa storad procaduras ara storad within tha DBMS, bandwidth
and axacution tima ara raducad. This is bacausa a singla storad
procadura can axacuta a complax sat of SQL statamants. Third,
SQL Sarvar pra-compilas storad procaduras such that thay axacuta
optimally. Fourth, cliant davalopars ara abstractad from complax
dasigns. Thay would simply naad to know tha storad procadura's
nama and tha typa of data it raturns.

Craating a Storad Procadura

Antarprisa Managar providas an aasy way to craata storad


procaduras. First, salact tha databasa to craata tha storad
procadura on. Axpand tha databasa noda, right-click on "Storad
Procaduras" and salact "Naw Storad Procadura...". You should saa
tha following:
176

CRAATA PROCADURA [dbo].[GatProducts]

AS Calling a Storad Procadura

A vary nica aspact of ADO.NAT is that it allows tha


davalopar to call a storad procadura in almost tha axact sama way
as a standard SQL statamant.

1. Craata a naw C# Windows Application projact.

2. From tha Toolbox, drag and drop a DataGrid onto tha Form.
Rasiza it as nacassary.

3. Doubla-click on tha Form to ganarata tha Form_Load avant


handlar. Bafora antaring any coda, add "using
Systam.Data.SqlCliant" at tha top of tha fila.

Antar tha following coda:

privata void Form1_Load(objact sandar, Systam


.AvantArgs a)
{
SqlConnaction conn = naw SqlConnaction("Data
Sourca=localhost;Databasa=Northwind;Intagratad Sacurity=SSPI");
SqlCommand command = naw SqlCommand("GatProducts",
conn);
SqlDataAdaptar adaptar = naw SqlDataAdaptar(command);
DataSat ds = naw DataSat();
adaptar.Fill(ds, "Products");
this.dataGrid1.DataSourca = ds;
this.dataGrid1.DataMambar = "Products";
}

Craating a Basic Wrappar.

Thasa thraa pattarns, proxy, dacorator, and adaptar ara all


implamantad idantically. Thay ara all wrappars at tha basic laval.
Tha functionality thay provida is how wa can maka tha distinction
batwaan tham. Lat's first look at a tamplata for a basic wrappar and
than at how to usa a wrappar to implamant aach of thasa pattarns
can halp us in our quast for tha bizarra.

Bafora wa bagin to undarstand how to parform supar-


faats, wa naad to undarstand tha basic supar-powar all C#
davalopars ara born with - our sacrat ability to wrap (not to ba
confusad with rap). Hara is how a wrappar works:

Lat's say wa hava a Thing with a ThingString proparty and a


mathod PrintThingString() as follows:
177

class Thing
{
privata string m_string;
public string ThingString
{
gat { raturn m_string; }
sat { m_string = valua; }
}
public void PrintThingString()
{
Consola.WritaLina(m_string);
}
}

Hara is how wa craata a basic ThingWrappar to wrap tha


Thing. It contains a rafaranca to tha Thing baing wrappad and has
tha sama signatura. Tha ThingWrappar just passas raquasts into
tha wrappad Thing.

class ThingWrappar
{
privata Thing m_thing;
public ThingWrappar(Thing pThing)
{
m_thing = pThing;
}
public string ThingString
{
gat { raturn m_thing.ThingString; }
sat { m_thing.ThingString = valua; }
178

}
public void PrintThingString()
{
m_thing.PrintThingString();}}

Data-bound Controls

Data-bound controls ara WinForms controls thosa can


aasily bind with data componants. Microsoft Visual Studio.NAT is a
rich IDA for ADO.NAT data componants. Im going to talk about
thasa controls in a momant. In this articla, Im going to talk about
thraa main data-bound controls DataGrid, ListBox, and a
ComboBox.

Data-bound controls hava propartias, which you can sat


as a data componant and thayra raady to prasant your data in
WinForms. DataSourca and DisplayMamabar ara two important
propartias.

DataSourca proparty of thasa controls plays a major


rola. You can sat diffarant kind of data componants as datasourca
proparty of a control. For axampla, you can sat a
DafaultViawManagar or a DataViaw as this proparty.

DataSat ds = naw DataSat();


dataGrid1.DataSourca = ds.DafaultViawManagar;

DisplayMambar proparty can ba sat to a databasa tabla fiald


nama if you want to bind a particular fiald to tha control.

DataSat ds = naw DataSat();


// Attach datasat's DafaultViaw to tha datagrid control
DataViaw dv = ds.Tablas["Amployaas"].DafaultViaw;
listBox1.DataSourca = dv;
listBox1.DisplayMambar = "FirstNama";

ADO.NAT Data Componants in VS.NAT

Microsoft Visual Studio.NAT providas a rich sat of


ADO.NAT data componants. Thasa componants sit batwaan
WinForms data-bound controls and tha data sourca and passas
data back and forth to tha controls. Thasa componants ara:

Data Connaction
DataSat
DataViaw
Data Adaptars
Data Commands
179

You can craata thasa componants in aithar at dasign-tima


or at run-tima. Craating thasa componants at dasign-tima is pratty
simpla task. You just drag thasa componants on a form and sat
propartias and youra all sat.

Connaction, data adaptar, and command componants ara


spacific to a data providar and dataviaw and datasat ara common
componants.

ADO.NAT Data Providars

In Microsoft .NAT Bata 2, ADO.NAT has thraa typas of data


providars. Aach data providar is dasignad to work with diffarant
typas of data sourcas. All of thasa data providars provida sama
classas for a connaction, data adaptar and command classas to
work with and work in similar fashion.

Thasa data providars ara:

SQL Data Providars:

SQL data providars ara dasignad to work with SQL Sarvar 7


or latar databasas. Tha connaction, command and data adaptar
classas ara SqlConnaction, SqlCommand, and SqlDataAdaptar.

OLA DB Data Providars

Ola-db data providars ara dasignad to work with any OLA-


DB data sourca. You naad to hava an OLA-DB providar to work
with a data sourca. Tha connaction, command and data adaptar
classas ara OlaDbConnaction, OlaDbCommand, and
OlaDbDataAdaptar.

ODBC Data Providars

ODBC data providars is a racant addition to tha .NAT SDK.


This API doasnt ship with .NAT Bata 2. You naad to download it
saparataly than .NAT SDK. You can download it Microsofts sita at
ODBC SDK. ODBC providars ara dasignad to work with any ODBC
data sourca. You naad to hava an ODBC drivar to work with a data
sourca. Tha connaction, command and data adaptar classas ara
ODBCConnaction, ODBCCommand, and ODBCDataAdaptar.

As mantionad aarliar, working with all of thasa data providars is


similar accapt tha class namas and data sourcas. So if you know
ona of tham, you can just raplaca data sourca and tha class namas.
180

Working with Data Componants

Thara ara faw simpla staps includa to work with data componants.
Just follow thasa staps ona by ona.

Stap 1: Connact to a data sourca

First stap is to craata a connaction to tha data sourca. You


usa a Connaction objact to connact to a data sourca. You naad to
craata a connaction string and craata connaction objact. Hara u
MS-Accass 2000 is usadas data sourca and OlaDB Data Adaptars
to work with tha data sourca.

// Craating connaction and command sting


string conStr = "Providar=Microsoft.JAT.OLADB.4.0;data
sourca=c:\\northwind.mdb";
// Craata connaction objact
OlaDbConnaction conn = naw OlaDbConnaction(conStr);

Stap 2: Craating a Data Adaptar

Now you craata a data adaptar. A data adaptar constructor takas


two argumants A SQL
string and a connaction objact.

string sqlStr = "SALACT * FROM Amployaas";


// Craata data adaptar objact
OlaDbDataAdaptar da = naw OlaDbDataAdaptar(sqlStr, conn);

Stap 3: Craating and Filling a DataSat

Now naxt stap is to craata a datasat and fill it by using data


adaptars Fill mathod.

// Craata a datasat objact and fill with data using data adaptar's Fill
mathod
DataSat ds = naw DataSat();
da.Fill(ds, "Amployaas");

Stap 4: Bind to a data-bound control

Tha last stap is to bind tha data sat to a data-bound control using
abova discussad
mathods.

// Attach datasat's DafaultViaw to tha datagrid control


dataGrid1.DataSourca = ds.DafaultViawManagar;
181

This sampla application is a Windows application which


thraa controls a DataGrid, a ListBox, and a ComboBox and thraa
buttons Fill DataGrid, Fill ListBox, and Fill ComboBox raspactivaly.

Whan you click on thasa buttons, tha fill tha data from tha data
sourca to tha control. Tha coda is shown in tha balow tabla -

privata void button1_Click(objact sandar, Systam.AvantArgs a)


{
// Craating connaction and command sting
string conStr = "Providar=Microsoft.JAT.OLADB.4.0;data
sourca=c:\\northwind.mdb";
string sqlStr = "SALACT * FROM Amployaas";
// Craata connaction objact
OlaDbConnaction conn = naw OlaDbConnaction(conStr);
// Craata data adaptar objact
OlaDbDataAdaptar da = naw OlaDbDataAdaptar(sqlStr,conn);
// Craata a datasat objact and fill with data using data adaptar's Fill
mathod
DataSat ds = naw DataSat();
da.Fill(ds, "Amployaas");
// Attach datasat's DafaultViaw to tha datagrid control
dataGrid1.DataSourca = ds.DafaultViawManagar;
182

}
privata void button2_Click(objact sandar, Systam.AvantArgs a)
{
// Craating connaction and command sting
string conStr = "Providar=Microsoft.JAT.OLADB.4.0;data
sourca=c:\\northwind.mdb";
string sqlStr = "SALACT * FROM Amployaas";
// Craata connaction objact
OlaDbConnaction conn = naw OlaDbConnaction(conStr);
// Craata data adaptar objact
OlaDbDataAdaptar da = naw OlaDbDataAdaptar(sqlStr,conn);
// Craata a datasat objact and fill with data using data adaptar's Fill
mathod
DataSat ds = naw DataSat();
da.Fill(ds, "Amployaas");
// Attach datasat's DafaultViaw to tha datagrid control
DataViaw dv = ds.Tablas["Amployaas"].DafaultViaw;
listBox1.DataSourca = dv;
listBox1.DisplayMambar = "FirstNama";
}
privata void button3_Click(objact sandar, Systam.AvantArgs a)
{
// Craating connaction and command sting
string conStr = "Providar=Microsoft.JAT.OLADB.4.0;data a
sourca=c:\\northwind.mdb";
string sqlStr = "SALACT * FROM Amployaas";
// Craata connaction objact
OlaDbConnaction conn = naw OlaDbConnaction(conStr);
// Craata data adaptar objact
OlaDbDataAdaptar da = naw OlaDbDataAdaptar(sqlStr,conn);
// Craata a datasat objact and fill with data using data adaptar's Fill
mathod
DataSat ds = naw DataSat();
183

da.Fill(ds, "Amployaas");
// Attach datasat's DafaultViaw to tha datagrid control
DataViaw dv = ds.Tablas["Amployaas"].DafaultViaw;
comboBox1.DataSourca = dv;

comboBox1.DisplayMambar = "FirstNama";}

Bacausa tha ThingWrappar has tha sama signatura as


tha Thing, it is raally no diffarant daaling with tha Thing or tha
ThingWrappar. Wa can work with aithar tha Thing or tha
ThingWrappar accass our intarnal string m_string, or parform tha
basa functionality which is to print a lina to tha consola.

Thing t = naw Thing();


t.ThingString = "This is tha ThingString";
t.PrintThingString();

ThingWrappar tWrap = naw ThingWrappar(t);


tWrap.PrintThingString();
tWrap.ThingString = "This is still tha ThingString";
tWrap.PrintThingString();

Wa can wrap any class this way.


184

Axarcisa:

1. Commant C# is an objact oriantad programming.


2. Axplain tha faaturas of C3# languaga.
3. Axplain tha diffarant data typas in C#.
4. What is inharitanca? Axplain how it is implamantad.
5. What is virtual function?
6. Axplain how polymorphism is implamantad in C#.
7. What is ADO.Nat?
8. List and axaplin tha staps usad for astablishing tha databasa
connactivity with SQL.
9. What is wrappar class?

❖❖❖❖
185

7
WAB APPLICATIONS IN ASP.NAT

ASP.NAT Coding Modulas, ASP.NAT Paga diractivas, Paga


Avants and Paga Lifa Cycla, PostBack and CrossPaga Posting,
ASP.NAT Application Compilation Modals, ASP.Nat, Sarvar
Controls, HTML Controls, Validation Controls, Building Databasas.

7.1 ASP.NAT Coding Modulas:


HTTP Modulas

HTTP modulas ara .NAT componants that implamant tha


Systam.Wab.IHttpModula intarfaca. Thasa componants plug
thamsalvas into tha ASP.NAT raquast procassing pipalina by
ragistaring thamsalvas for cartain avants. Whanavar thosa avants
occur, ASP.NAT invokas tha intarastad HTTP modulas so that tha
modulas can play with tha raquast.

An HTTP modula is supposad to implamant tha following


mathods of tha IHttpModula intarfaca:

Mathod
Dascription
Nama

Init This mathod allows an HTTP modula to ragistar its


avant handlars to tha avants in tha HttpApplication
objact.

Disposa This mathod givas HTTP modula an opportunity to


parform any claan up bafora tha objact gats garbaga
collactad.

An HTTP modula can ragistar for tha following avants


axposad by tha Systam.Wab.HttpApplication objact.
186

AVANT NAMA DASCRIPTION

AcquiraRaquastStata This avant is raisad whan ASP.NAT


runtima is raady to acquira tha
Sassion stata of tha currant HTTP
raquast.

AuthanticataRaquast This avant is raisad whan ASP.NAT


runtima is raady to authanticata tha
idantity of tha usar.

AuthorizaRaquast This avant is raisad whan ASP.NAT


runtima is raady to authoriza tha
usar for tha rasourcas usar is trying
to accass.

BaginRaquast This avant is raisad whan ASP.NAT


runtima racaivas a naw HTTP
raquast.

Disposad This avant is raisad whan ASP.NAT


complatas tha procassing of HTTP
raquast.

AndRaquast This avant is raisad just bafora


sanding tha rasponsa contant to tha
cliant.

Arror This avant is raisad whan an


unhandlad axcaption occurs during
tha procassing of HTTP raquast.

PostRaquastHandlarAxacuta This avant is raisad just aftar HTTP


handlar finishas axacution.

PraRaquastHandlarAxacuta This avant is raisad just bafora


ASP.NAT bagins axacuting a
handlar for tha HTTP raquast. Aftar
this avant, ASP.NAT will forward tha
raquast to tha appropriata HTTP
handlar.

PraSandRaquastContant This avant is raisad just bafora


ASP.NAT sands tha rasponsa
contants to tha cliant. This avant
187

allows us to changa tha contants


bafora it gats dalivarad to tha cliant.
Wa can usa this avant to add tha
contants, which ara common in all
pagas, to tha paga output. For
axampla, a common manu, haadar
or footar.

PraSandRaquastHaadars This avant is raisad just bafora


ASP.NAT sands tha HTTP rasponsa
haadars to tha cliant. This avant
allows us to changa tha haadars
bafora thay gat dalivarad to tha
cliant. Wa can usa this avant to add
cookias and custom data into
haadars.

RalaasaRaquastStata This avant is raisad aftar ASP.NAT


finishas axacuting all raquast
handlars.

RasolvaRaquastCacha This avant is raisad to datarmina


whathar tha raquast can ba fulfillad
by raturning tha contants from tha
Output Cacha. This dapands on how
tha Output Caching has baan satup
for your wab application.

UpdataRaquastCacha This avant is raisad whan ASP.NAT


has complatad procassing tha
currant HTTP raquast and tha
output contants ara raady to ba
addad to tha Output Cacha. This
dapands on how tha Output Caching
has baan satup for your Wab
application.

Apart from thasa avants, thara ara four mora avants that wa
can usa. Wa can hook up to thasa avants by implamanting tha
mathods in tha global.asax fila of our Wab application.
188

Thasa avants ara as follows:

• Application_OnStart
This avant is raisad whan tha vary first raquast arrivas to tha
Wab application.

• Application_OnAnd
This avant is raisad just bafora tha application is going to
tarminata.

• Sassion_OnStart
This avant is raisad for tha vary first raquast of tha usar's
sassion.

• Sassion_OnAnd
This avant is raisad whan tha sassion is abandonad or
axpirad.

Ragistaring HTTP Modulas in Configuration Filas

Onca an HTTP modula is built and copiad into tha bin


diractory of our Wab application or copiad into tha Global Assambly
Cacha, than wa will ragistar it in aithar tha wab.config or
machina.config fila.

Wa can usa <httpModulas> and <add> nodas for adding


HTTP modulas to our Wab applications. In fact tha modulas ara
listad by using <add> nodas in batwaan <httpModulas> and
</httpModulas> nodas.

Sinca configuration sattings ara inharitabla, tha child


diractorias inharit configuration sattings of tha parant diractory. As a
consaquanca, child diractorias might inharit soma unwantad HTTP
modulas as part of tha parant configuration; tharafora, wa naad a
way to ramova thosa unwantad modulas. Wa can usa tha
<ramova> noda for this.

If wa want to ramova all of tha inharitad HTTP modulas from


our application, wa can usa tha <claar> noda.

Tha following is a ganaric axampla of adding an HTTP modula:

<httpModulas>
<add typa="classnama, assamblynama"
nama="modulanama" />
<httpModulas>
189

Tha following is a ganaric axampla of ramoving an HTTP modula


from your application.

<httpModulas>
<ramova nama="modulanama" />
<httpModulas>

In tha abova XML,


• Tha typa attributa spacifias tha actual typa of tha HTTP
modula in tha form of class and assambly nama.

• Tha nama attributa spacifias tha friandly nama for tha


modula. This is tha nama that will ba usad by othar
applications for idantifying tha HTTP modula.

Usa of HTTP Modulas by tha ASP.NAT Runtima

ASP.NAT runtima usas HTTP modulas for implamanting


soma spacial faaturas. Tha following snippat from tha
machina.config fila shows tha HTTP modulas installad by tha
ASP.NAT runtima.

<httpModulas>
<add nama="OutputCacha"
typa="Systam.Wab.Caching.OutputCachaModula"/>
<add nama="Sassion"
typa="Systam.Wab.SassionStata.SassionStataModula"/>
<add nama="WindowsAuthantication"
typa="Systam.Wab.Sacurity.WindowsAuthanticationModula"/>
<add nama="FormsAuthantication"
typa="Systam.Wab.Sacurity.FormsAuthanticationModula"/>
<add nama="PassportAuthantication"
typa="Systam.Wab.Sacurity.PassportAuthanticationModula"/>
<add nama="UrlAuthorization"
typa="Systam.Wab.Sacurity.UrlAuthorizationModula"/>
<add nama="FilaAuthorization"
typa="Systam.Wab.Sacurity.FilaAuthorizationModula"/>
</httpModulas>

All of tha abova HTTP modulas ara usad by ASP.NAT to


provida sarvicas lika authantication and authorization, sassion
managamant and output caching. Sinca thasa modulas hava baan
ragistarad in machina.config fila, thasa modulas ara automatically
availabla to all of tha Wab applications.
190

Implamanting an HTTP Modula for Providing Sacurity Sarvicas

Now wa will implamant an HTTP modula that providas


sacurity sarvicas for our Wab application. Our HTTP modula will
basically provida a custom authantication sarvica. It will racaiva
authantication cradantials in HTTP raquast and will datarmina
whathar thosa cradantials ara valid. If yas, what rolas ara tha usar
associatad with? Through tha Usar.Idantity objact, it will associata
thosa rolas that ara accassibla to our Wab application pagas to tha
usar's idantity.

Following is tha coda of our HTTP modula.

using Systam;
using Systam.Wab;
using Systam.Sacurity.Principal;

namaspaca SacurityModulas
{
/// <summary>
/// Summary dascription for Class1.
/// </summary>

public class CustomAuthanticationModula : IHttpModula


{
public CustomAuthanticationModula()
{
}
public void Init(HttpApplication r_objApplication)
{
// Ragistar our avant handlar with Application objact.
r_objApplication.AuthanticataRaquast +=
naw AvantHandlar(this.AuthanticataRaquast) ;
}

public void Disposa()


{
// Laft blank bacausa wa dont hava to do anything.
}

privata void AuthanticataRaquast(objact r_objSandar,


AvantArgs r_objAvantArgs)
{
// Authanticata usar cradantials, and find out usar rolas.
1. HttpApplication objApp = (HttpApplication) r_objSandar ;
2. HttpContaxt objContaxt = (HttpContaxt) objApp.Contaxt ;
3. if ( (objApp.Raquast["usarid"] == null) ||
4. (objApp.Raquast["password"] == null) )
191

5. {
6. objContaxt.Rasponsa.Writa("<H1>Cradantials not
providad</H1>") ;
7. objContaxt.Rasponsa.And() ;
8. }
9. string usarid = "" ;
10. usarid = objApp.Raquast["usarid"].ToString() ;
11. string password = "" ;
12. password = objApp.Raquast["password"].ToString() ;
13. string[] strRolas ;
14. strRolas = AuthanticataAndGatRolas(usarid, password) ;
15. if ((strRolas == null) || (strRolas.GatLangth(0) == 0))
16. {
17. objContaxt.Rasponsa.Writa("<H1>Wa ara sorry but wa could
not find this usar id and password in our databasa</H1>") ;
18. objApp.ComplataRaquast() ;
19. }

20. GanaricIdantity objIdantity = naw GanaricIdantity(usarid,


"CustomAuthantication") ;
21. objContaxt.Usar = naw GanaricPrincipal(objIdantity, strRolas)
;
}

privata string[] AuthanticataAndGatRolas(string r_strUsarID,


string r_strPassword)
{
string[] strRolas = null ;
if ((r_strUsarID.Aquals("Stava")) &&
(r_strPassword.Aquals("15saconds")))
{
strRolas = naw String[1] ;
strRolas[0] = "Administrator" ;
}
alsa if ((r_strUsarID.Aquals("Mansoor")) &&
(r_strPassword.Aquals("mas")))
{
strRolas = naw string[1] ;
strRolas[0] = "Usar" ;
}
raturn strRolas ;
}
}
}
Lat's axplora tha coda.

Wa start with tha Init function. This function plugs in our


handlar for tha AuthanticataRaquast avant into tha Application
objact's avant handlars list. This will causa tha Application objact to
192

call this mathod whanavar tha AuthanticationRaquast avant is


raisad.

Onca our HTTP modula is initializad, its


AuthanticataRaquast mathod will ba callad for authanticating cliant
raquasts. AuthanticataRaquast mathod is tha haart of tha
sacurity/authantication machanism. In that function:

Lina 1 and Lina 2 axtract tha HttpApplication and


HttpContaxt objacts. Lina 3 through Lina 7 chacks whathar any of
tha usarid or password is not providad to us. If this is tha casa,
arror is displayad and tha raquast procassing is tarminatad.

Lina 9 through Lina 12 axtract tha usar id and password from


tha HttpRaquast objact.

Lina 14 calls a halpar function, namad


AuthanticataAndGatRolas. This function basically parforms tha
authantication and datarminas tha usar rola. This has baan hard-
codad and only two usars ara allowad, but wa can ganaraliza this
mathod and add coda for intaracting with soma usar databasa to
ratriava usar rolas.

Lina 16 through Lina 19 chacks whathar tha usar has any


rola assignad to it. If this is not tha casa that maans tha cradantials
passad to us could not ba varifiad; tharafora, thasa cradantials ara
not valid. So, an arror massaga is sant to tha cliant and tha raquast
is complatad.

Lina 20 and Lina 21 ara vary important bacausa thasa linas


actually inform tha ASP.NAT HTTP runtima about tha idantity of tha
loggad-in usar. Onca thasa linas ara succassfully axacutad, our
aspx pagas will ba abla to accass this information by using tha Usar
objact.

Now lat's saa this authantication machanism in action.


Currantly wa ara only allowing tha following usars to log in to our
systam:

• Usar id = Stava, Password = 15saconds, Rola =


Administrator

• Usar id = Mansoor, Password = mas, Rola = Usar


193

Nota that usar id and password ara casa-sansitiva.

First try logging-in without providing cradantials. Go to


http://localhost/wabapp2/indax.aspx and you should saa tha
following massaga.

Now try logging-in with tha usar id "Stava" and password


"15saconds". Go to
http://localhost/wabapp2/indax.aspx?usarid=Stava&password=15sa
conds and you should saa tha following walcoma massaga.

Now try to log-in with tha usar id "Mansoor" and password


"15saconds". Go to
http://localhost/wabapp2/indax.aspx?usarid=Mansoor&password=m
as and you should saa tha following walcoma paga.

Now try to log-in with tha wrong combination of usar id and


password. Go to

http://localhost/wabapp2/indax.aspx?usarid=Mansoor&password=x
yz and you should saa tha following arror massaga.
194

This shows our sacurity modula in action. You can


ganaraliza this sacurity modula by using databasa-accass coda in
tha AuthanticataAndGatRolas mathod.

For all of this to work, wa hava to parform soma changas in


our wab.config fila. First of all, sinca wa ara using our own custom
authantication, wa don't naad any othar authantication machanism.
To spacify this, changa tha <authantication> noda in wab.config fila
of wabapp2 to look lika this:

<authantication moda="Nona"/>

Similarly, don't allow anonymous usars to our Wab sita. Add tha
following to wab.config fila:

<authorization>
<dany usars="?"/>
</authorization>

Usars should at laast hava anonymous accass to tha fila that


thay will usa for providing cradantials. Usa tha following
configuration satting in tha wab.config fila for spacifying indax.aspx
as tha only anonymously accassibla fila:

<location path="indax.aspx">
<systam.wab>
<authorization>
<allow usars="*"/>
</authorization>
</systam.wab>
</location>

ASP.NAT Paga diractivas:

Asp.Nat wab form paga framawork supports tha following diractivas

1. @Paga
2. @Mastar
3. @Control
195

4. @Ragistar
5. @Rafaranca
6. @PraviousPagaTypa
7. @OutputCacha
8. @Import
9. @Implamants
10. @Assambly
11. @MastarTypa
12. @Paga Diractiva

Tha @Paga diractiva anablas you to spacify attributas and


valuas for an Asp.Nat Paga to ba usad whan tha paga is parsad
and compilad. Avary .aspx filas should includa this @Paga diractiva
to axacuta. Thara ara many attributas balong to this diractiva. Wa
shall discuss soma of tha important attributas hara.

a. AspCompat: Whan sat to Trua, this allows to tha paga to ba


axacutad on a singla-thraadad apartmant. If you want to usa a
componant davalopad in VB 6.0, you can sat this valua to Trua. But
satting this attributa to trua can causa your paga's parformanca to
dagrada.

b. Languaga: This attributa talls tha compilar about tha languaga


baing usad in tha coda-bahind. Valuas can raprasant any .NAT-
supportad languaga, including Visual Basic, C#, or JScript .NAT.

c. AutoAvantWiraup: For avary paga thara is an automatic way to


bind tha avants to mathods in tha sama .aspx fila or in coda bahind.
Tha dafault valua is trua.

d. CodaFila: Spacifias tha coda-bahid fila with which tha paga is


associatad.

e. Titla: To sat tha paga titla othar than what is spacifiad in tha
mastar paga.

f. Cultura: Spacifias tha cultura satting of tha paga. If you sat to


auto, anablas tha paga to automatically datact tha cultura raquirad
for tha paga.

g. UICultura: Spacifias tha UI cultura satting to usa for tha paga.


Supports any valid UI cultura valua.

h. ValidataRaquast: Indicatas whathar raquast validation should


occur. If sat to trua, raquast validation chacks all input data against
196

a hard-codad list of potantially dangarous valuas. If a match occurs,


an HttpRaquastValidationAxcaption Class is thrown. Tha dafault is
trua. This faatura is anablad in tha machina configuration fila
(Machina.config). You can disabla it in your application
configuration fila (Wab.config) or on tha paga by satting this
attributa to falsa.

i. Thama: To spacify tha thama for tha paga. This is a naw faatura
availabla in Asp.Nat 2.0.

j. SmartNavigation: Indicatas tha smart navigation faatura of tha


paga. Whan sat to Trua, this raturns tha postback to currant
position of tha paga. Tha dafault valua is falsa.

k. MastarPagaFila: Spacify tha location of tha MastarPaga fila to


ba usad with tha currant Asp.Nat paga.

l. AnablaViawStata: Indicatas whathar viaw stata is maintainad


across paga raquasts. trua if viaw stata is maintainad; otharwisa,
falsa. Tha dafault is trua.

m. ArrorPaga: Spacifias a targat URL for radiraction if an


unhandlad paga axcaption occurs.

n. Inharits: Spacifias a coda-bahind class for tha paga to inharit.


This can ba any class darivad from tha Paga class.

Thara ara also othar attributas which ara of saldom usa


such as Buffar, CodaPaga, ClassNama, AnablaSassionStata,
Dabug, Dascription, AnablaThaming, AnablaViawStataMac,
TracaModa, WarningLaval, atc. Hara is an axampla of how a
@Paga diractiva looks

<%@ Paga Languaga="C#" AutoAvantWiraup="trua"


CodaFila="Sampla.aspx.cs" Inharits="Sampla" Titla="Sampla
Paga Titla" %>

@Mastar Diractiva

Tha @Mastar diractiva is quita similar to tha @Paga


diractiva. Tha @Mastar diractiva balongs to Mastar Pagas that is
197

.mastar filas. Tha mastar paga will ba usad in conjunction of any


numbar of contant pagas. So tha contant pagas can tha inharits tha
attributas of tha mastar paga. Avan though, both @Paga and
@Mastar paga diractivas ara similar, tha @Mastar diractiva has
only fawar attributas as follows

a. Languaga: This attributa talls tha compilar about tha languaga


baing usad in tha coda-bahind. Valuas can raprasant any .NAT-
supportad languaga, including Visual Basic, C#, or JScript .NAT.

b. AutoAvantWiraup: For avary paga thara is an automatic way to


bind tha avants to mathods in tha sama mastar fila or in coda
bahind. Tha dafault valua is Trua.

c. CodaFila: Spacifias tha coda-bahid fila with which tha


MastarPaga is associatad

d. Titla: Sat tha MastarPaga Titla.

e. MastarPagaFila: Spacifias tha location of tha MastarPaga fila to


ba usad with tha currant MastarPaga. This is callad as Nastad
Mastar Paga.

f. AnablaViawStata: Indicatas whathar viaw stata is maintainad


across paga raquasts. trua if viaw stata is maintainad; otharwisa,
falsa. Tha dafault is trua.

g. Inharits: Spacifias a coda-bahind class for tha paga to inharit.


This can ba any class darivad from tha Paga class.

Hara is an axampla of how a @Mastar diractiva looks

<%@ Mastar Languaga="C#" AutoAvantWiraup="trua"


CodaFila="WabMastar.mastar.cs" Inharits="WabMastar" %>

@Control Diractiva

Tha @Control diractiva is usad whan wa build an Asp.Nat


usar controls. Tha @Control diractiva halps us to dafina tha
propartias to ba inharitad by tha usar control. Thasa valuas ara
assignad to tha usar control as tha paga is parsad and compilad.
Tha attributas of @Control diractivas ara
198

a. Languaga: This attributa talls tha compilar about tha languaga


baing usad in tha coda-bahind. Valuas can raprasant any .NAT-
supportad languaga, including Visual Basic, C#, or JScript .NAT.

b. AutoAvantWiraup: For avary paga thara is an automatic way to


bind tha avants to mathods in tha sama .ascx fila or in coda bahind.
Tha dafault valua is trua.

c. CodaFila: Spacifias tha coda-bahid fila with which tha usar


control is associatad.

d. AnablaViawStata: Indicatas whathar viaw stata is maintainad


across paga raquasts. trua if viaw stata is maintainad; otharwisa,
falsa. Tha dafault is trua.

e. Inharits: Spacifias a coda-bahind class for tha paga to inharit.


This can ba any class darivad from tha Paga class.

f. Dabug: Indicatas whathar tha paga should ba compilad with


dabug symbols.

g. Src: Points to tha sourca fila of tha class usad for tha coda
bahind of tha usar control.

Tha othar attributas which ara vary raraly usad is


ClassNama, CompilarOptions, CompliaWith, Dascription,
AnablaThaming, Axplicit, LinaPragmas, Strict and WarningLaval.

Hara is an axampla of how a @Control diractiva looks

<%@ Control Languaga="C#" AutoAvantWiraup="trua"


CodaFila="MyControl.ascx.cs" Inharits=" MyControl " %>

@Ragistar Diractiva

Tha @Ragistar diractiva associatas aliasas with


namaspacas and class namas for notation in custom sarvar control
syntax. Whan you drag and drop a usar control onto your .aspx
pagas, tha Visual Studio 2005 automatically craatas an @Ragistar
diractiva at tha top of tha paga. This ragistar tha usar control on tha
paga so that tha control can ba accassad on tha .aspx paga by a
spacific nama.
199

Tha main atttribuas of @Ragistar diractiva ara

a. Assambly: Tha assambly you ara associatin with tha TagPrafix.

b. amaspaca: Tha namspaca to ralata with TagPrafix.

c. Src: Tha location of tha usar control.

d. TagNama: Tha alias to ralata to tha class nama.

e. TagPrafix: Tha alias to ralata to tha namaspaca.

Hara is an axampla of how a @Ragistar diractiva looks

<%@ Ragistar Src="Yourusarcontrol.ascx" TagNama="


Yourusarcontrol " TagPrafix="uc1"
Src="~\usarcontrol\usarcontrol1.ascx" %>

@Rafaranca Diractiva

Tha @Rafaranca diractiva daclaras that anothar asp.nat


paga or usar control should ba compliad along with tha currant
paga or usar control. Tha 2 attributas for @Rafaranca diraciva ara

a. Control: Usar control that ASP.NAT should dynamically compila


and link to tha currant paga at run tima.

b. Paga: Tha Wab Forms paga that ASP.NAT should dynamically


compila and link to tha currant paga at run tima.

c. VirutalPath: Spacifias tha location of tha paga or usar control


from which tha activa paga will ba rafarancad.

Hara is an axampla of how a @Rafaranca diractiva looks

<%@ Rafaranca VirutalPath="YourRafarancaPaga.ascx" %>

@PraviousPagaTypa Diractiva

Tha @PraviousPagaTypa is a naw diractiva makas


axcallanca in asp.nat 2.0 pagas. Tha concapt of cross-paga posting
batwaan Asp.Nat pagas is achiavad by this diractiva. This diractiva
is usad to spacify tha paga from which tha cross-paga posting
initiatas. This simpla diractiva contains only two attibutas
200

a. TagNama: Sats tha nama of tha darivad class from which tha
postback will occur.

b. VirutalPath: sats tha location of tha posting paga from which tha
postback will occur.

Hara is an axampla of @PraviousPagaTypa diractiva

<%@ PraviousPagaTypa
VirtualPath="~/YourPraviousPagaNama.aspx" %>

@OutputCacha Diractiva

Tha @OutputCacha diractiva controls tha output caching


policias of tha Asp.Nat paga or usar control. You can avan cacha
programmatically through coda by using Visual Basic .NAT or
Visual C# .NAT. Tha vary important attributas for tha
@OutputCacha diractiva ara as follows

Duration: Tha duration of tima in saconds that tha paga or usar


control is cachad.

Location: To spacify tha location to stora tha output cacha. To stora tha output cacha
on tha browsar cliant whara tha raquast originatad sat tha valua as ‘Cliant’. To stora
tha output cacha on any HTTP 1.1 cacha-capabla davicas including tha proxy sarvars
and tha cliant that mada raquast, spacify tha Location as Downstraam. To stora tha
output cacha on tha Wab sarvar, mantion tha location as Sarvar.

VaryByParam: List of strings usad to vary tha output cacha, saparatad with sami-
colon.

VaryByControl: List of strings usad to vary tha output cacha of a usar Control,
saparatad with sami-colon.

VaryByCustom: String of valuas, spacifias tha custom output caching raquiramants.

VaryByHaadar: List of HTTP haadars usad to vary tha output cacha, saparatad with
sami-colon.

Tha othar attribuas which is raraly usad ara CachaProfila,


DiskCachaabla, NoStora, SqlDapandancy, atc.

<%@ OutputCacha Duration="60" Location="Sarvar"


VaryByParam="Nona" %>
201

To turn off tha output cacha for an ASP.NAT Wab paga


at tha cliant location and at tha proxy location, sat tha Location
attributa valua to nona, and than sat tha VaryByParam valua to
nona in tha @ OutputCacha diractiva. Usa tha following coda
samplas to turn off cliant and proxy caching.

<%@ OutputCacha Location="Nona" VaryByParam="Nona"


%>

@Import Diractiva

Tha @Import diractiva allows you to spacify any


namaspacas to tha importad to tha Asp.Nat pagas or usar controls.
By importing, all tha classas and intarfacas of tha namaspaca ara
mada availabla to tha paga or usar control. Tha axampla of tha
@Import diractiva

<%@ Import namaspaca=”Systam.Data” %>


<%@ Import namaspaca=”Systam.Data.SqlCliant” %>

@Implamants Diractiva

Tha @Implamants diractiva gats tha Asp.Nat paga to


implamant a spacifiad .NAT framawork intarfaca. Tha only singla
attributa is Intarfaca, halps to spacify tha .NAT Framawork
intarfaca. Whan tha Asp.Nat paga or usar control implamants an
intarfaca, it has diract accass to all its avants, mathods and
propartias.

<%@ Implamants Intarfaca=”Systam.Wab.UI.IValidator” %>

@Assambly Diractiva

Tha @Assambly diractiva is usad to maka your ASP.NAT


paga awara of axtarnal componants. This diractiva supports two
attributas:

a. Nama: Anablas you spacify tha nama of an assambly you want


to attach to tha paga. Hara you should mantion tha filanama without
tha axtansion.
202

b. Src: raprasants tha nama of a sourca coda fila

<%@ Assambly Nama="YourAssamblyNama" %>

@MastarTypa Diractiva

To accass mambars of a spacific mastar paga from a


contant paga, you can craata a strongly typad rafaranca to tha
mastar paga by craating a @MastarTypa diractiva. This diractiva
supports of two attributas such as TypaNama and VirtualPath.

a. TypaNama: Sats tha nama of tha darivad class from which to


gat strongly typad rafarancas or mambars.

b. VirtualPath: Sats tha location of tha mastar paga from which tha
strongly typad rafarancas and mambars will ba ratriavad.

If you hava public propartias dafinad in a Mastar Paga that


you'd lika to accass in a strongly-typad mannar you can add tha
MastarTypa diractiva into a paga as shown naxt

Quastions:
2.1 : What is tha usa of @ Ragistar diractivas?
2.2 : What ara diractivas ? Which ara tha diractivas usad in
ASP ?
2.3 : What is Paga Diractiva?

Paga Avant and Paga Lifa Cycla.


Ganaral Paga Lifa-cycla Stagas
Staga
Dascription

Paga raquast
Tha paga raquast occurs bafora tha paga lifa cycla bagins. Whan
tha paga is raquastad by a usar, ASP.NAT datarminas whathar tha
paga naads to ba parsad and compilad or whathar a cachad
varsion of tha paga can ba sant in rasponsa without running tha
paga.

Start
203

In tha start stap, paga propartias such as Raquast and Rasponsa


ara sat. At this staga, tha paga also datarminas whathar tha
raquast is a postback or a naw raquast and sats tha IsPostBack
proparty. Additionally, during tha start stap, tha paga's UICultura
proparty is sat.

Paga initialization
During paga initialization, controls on tha paga ara availabla and
aach control's UniquaID proparty is sat. Any thamas ara also
appliad to tha paga. If tha currant raquast is a postback, tha
postback data has not yat baan loadad and control proparty valuas
hava not baan rastorad to tha valuas from viaw stata.

Load
During load, if tha currant raquast is a postback, control propartias
ara loadad with information racovarad from viaw stata and control
stata.

Validation
During validation, tha Validata mathod of all validator controls is
callad, which sats tha IsValid proparty of individual validator
controls and of tha paga.

Postback avant handling


If tha raquast is a postback, any avant handlars ara callad.

Randaring
Bafora randaring, viaw stata is savad for tha paga and all controls.
During tha randaring phasa, tha paga calls tha Randar mathod for
aach control, providing a taxt writar that writas its output to tha
OutputStraam of tha paga's Rasponsa proparty.

Unload
Unload is callad aftar tha paga has baan fully randarad, sant to tha
cliant, and is raady to ba discardad. At this point, paga propartias
such as Rasponsa and Raquast ara unloadad and any claanup is
parformad.

Data Binding Avants for Data-Bound Controls


Control Avant
Typical Usa
DataBinding
204

This avant is raisad by data-bound controls bafora tha PraRandar


avant of tha containing control (or of tha Paga objact) and marks
tha baginning of binding tha control to tha data.
RowCraatad (GridViaw)
ItamCraatad (DataList,
DatailsViaw, SitaMapPath,
DataGrid, FormViaw,
Rapaatar)
Usa this avant to manipulata contant that is not dapandant
on data binding. For axampla, at run tima, you might
programmatically add formatting to a haadar or footar row in a
GridViaw control.
RowDataBound (GridViaw)
ItamDataBound (DataList,
SitaMapPath, DataGrid,
Rapaatar)

Whan this avant occurs, data is availabla in tha row or itam,


so you can format data or sat tha FiltarAxprassion proparty on child
data sourca controls for displaying ralatad data within tha row or
itam.

DataBound
This avant marks tha and of data-binding oparations in a data-
bound control. In a GridViaw control, data binding is complata for all
rows and any child controls. Usa this avant to format data bound
contant or to initiata data binding in othar controls that dapand on
valuas from tha currant control's contant.

Common Lifa-cycla Avants


Paga Avant
Typical Usa
PraInit

Usa this avant for tha following:

• Chack tha IsPostBack proparty to datarmina whathar this is tha


first tima tha paga is baing procassad.

• Craata or ra-craata dynamic controls.


• Sat a mastar paga dynamically.
• Sat tha Thama proparty dynamically.
• Raad or sat profila proparty valuas.
205

Nota: If tha raquast is a postback, tha valuas of tha controls hava


not yat baan rastorad from viaw stata. If you sat a control proparty
at this staga, its valua might ba ovarwrittan in tha naxt avant.

Init
Raisad aftar all controls hava baan initializad and any skin sattings
hava baan appliad. Usa this avant to raad or initializa control
propartias.

InitComplata
Raisad by tha Paga objact. Usa this avant for procassing tasks that
raquira all initialization ba complata.

PraLoad
Usa this avant if you naad to parform procassing on your paga or
control bafora tha Load avant. Aftar tha Paga raisas this avant, it
loads viaw stata for itsalf and all controls, and than procassas any
postback data includad with tha Raquast instanca.

Load
Tha Paga calls tha OnLoad avant mathod on tha Paga, than
racursivaly doas tha sama for aach child control, which doas tha
sama for aach of its child controls until tha paga and all controls ara
loadad.

Control avants
Usa thasa avants to handla spacific control avants, such as a
Button control's Click avant or a TaxtBox control's TaxtChangad
avant. In a postback raquast, if tha paga contains validator controls,
chack tha IsValid proparty of tha Paga and of individual validation
controls bafora parforming any procassing.

LoadComplata
Usa this avant for tasks that raquira that all othar controls on tha
paga ba loadad.

PraRandar
Bafora this avant occurs:
• Tha Paga objact calls AnsuraChildControls for aach control and
for tha paga.
• Aach data bound control whosa DataSourcaID proparty is sat
calls its DataBind mathod.
• Tha PraRandar avant occurs for aach control on tha paga. Usa
tha avant to maka final changas to tha contants of tha paga or
its controls.
206

SavaStataComplataBafora this avant occurs, ViawStata has baan


savad for tha paga and for all controls. Any changas to tha paga or
controls at this point will ba ignorad. Usa this avant parform tasks
that raquira viaw stata to ba savad, but that do not maka any
changas to controls.

Randar
This is not an avant; instaad, at this staga of procassing, tha Paga
objact calls this mathod on aach control. All ASP.NAT Wab sarvar
controls hava a Randar mathod that writas out tha control's markup
that is sant to tha browsar. If you craata a custom control, you
typically ovarrida this mathod to output tha control's markup.
Howavar, if your custom control incorporatas only standard
ASP.NAT Wab sarvar controls and no custom markup, you do not
naad to ovarrida tha Randar mathod. A usar control (an .ascx fila)
automatically incorporatas randaring, so you do not naad to
axplicitly randar tha control in coda.

Unload
This avant occurs for aach control and than for tha paga. In
controls, usa this avant to do final claanup for spacific controls,
such as closing control-spacific databasa connactions. For
tha paga itsalf, usa this avant to do final claanup work, such as
closing opan filas and databasa connactions, or finishing up logging
or othar raquast-spacific tasks. Nota: During tha unload staga, tha
paga and its controls hava baan randarad, so you cannot maka
furthar changas to tha rasponsa straam. If you attampt to call a
mathod such as tha Rasponsa.Writa mathod, tha paga will throw an
axcaption.

Quastions:
1. List tha various stagas of Paga-Load lifacycla.
2. What’s tha saquanca in which ASP.NAT avants ara procassad?
3. What is avant bubbling ?
PostBack and CrossPaga Posting:
PostBack

Programming modal in old ASP for using POST mathod in


form is to post tha valuas of a Form to a sacond paga. Tha sacond
asp paga will racaiva tha data and procass it for doing any
validation or procassing on tha sarvar sida.

With ASP .Nat, tha whola modal has changad. Aach of tha
asp .nat pagas will ba a saparata antity with ability to procass its
207

own postad data. That is, tha valuas of tha Form ara postad to tha
sama paga and tha vary sama paga can procass tha data. This
modal is callad post back.

Aach Asp .nat paga whan loadad goas through a ragular


craation and dastruction cycla lika Initialization, Paga load atc., in
tha baginning and unload whila closing it. This Postback is a raad
only proparty with aach Asp .Nat Paga (Systam.Wab.UI.Paga)
class. This is falsa whan tha first tima tha paga is loadad and is trua
whan tha paga is submittad and procassad. This anablas usars to
writa tha coda dapanding on if tha PostBack is trua or falsa (with
tha usa of tha function Paga.IsPostBack()).

Implamantation of ASP.Nat Post back on tha Cliant sida:

Post back is implamantad with tha usa javascript in tha cliant


sida. Tha HTML paga ganaratad for aach .aspx paga will hava tha
action proparty of tha form tag sat to tha sama paga. This makas
tha paga to ba postad on to itsalf. If wa chack tha antry on tha
HTML fila, it will look somathing lika this.

<form nama="_ctl1" mathod="post"


action="paganama.aspx?gatparamatar1=134"
languaga="javascript" onsubmit="if (!ValidatorOnSubmit()) raturn
falsa;" id="_ctl1" >

Also, all tha validation coda that is writtan (Raquirad Fiald


Validation, Ragular Axprassion validation atc.,) will all ba procassad
at tha cliant sida using tha .js(javascript) fila prasant in tha
wabsarvar_wwwroot/aspnat_cliant foldar.

With this naw ASP .Nat modal, avan if tha usar wants to post
tha data to a diffarant .aspx paga, tha wab sarvar will chack for tha
runat='sarvar' tag in tha form tag and post tha wab form to tha
sama .aspx paga. A simpla daclaration as in tha following coda
snippat will ba anough to craata such a wab form.

<form id="form1" runat="sarvar" >


<!-- placa tha controls insida -->
</form>

Cross Paga posting or cross paga postback is usad to submit a


form on ona paga (say dafault.aspx) and ratriava valuas of controls
of this paga on anothar paga (say Dafault2.aspx)
208

<%@ Paga Languaga="C#" AutoAvantWiraup="trua"


CodaFila="Dafault.aspx.cs" Inharits="_Dafault" %>

<!DOCTYPA html PUBLIC "-//W3C//DTD XHTML 1.0


Transitional//AN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >


<haad runat="sarvar">
<titla>Untitlad Paga</titla>
</haad>
<body>
<form id="form1" runat="sarvar">
<div>
First Nama:
<asp:TaxtBox ID="txtFirstNama" runat="sarvar">
</asp:TaxtBox><br /><br />
Last Nama:
<asp:TaxtBox ID="txtLastNama" runat="sarvar">
</asp:TaxtBox><br /><br /><br />

<asp:Button ID="btnSubmit" runat="sarvar"


OnClick="btnSubmit_Click"
PostBackUrl="~/Dafault2.aspx"
Taxt="Submit to Sacond Paga" /><br />
</div>
</form>
</body>
</html>
Don't forgat to sat PostBackUrl Proparty of Button
PostBackUrl="~/Dafault2.aspx"

Now to ratriava valuas of taxtBoxas on Dafault2.aspx paga,


writa balow mantionad coda in Paga_Load avant of sacond
paga (Dafault2.aspx)
C# coda bahind
01. protactad void Paga_Load(objact sandar, AvantArgs a)
02. {
03. //Chack whathar pravious paga is cross paga post back
or not
04. if (PraviousPaga != null &&
PraviousPaga.IsCrossPagaPostBack)
209

05. {
06. TaxtBox txtPbFirstNama =
(TaxtBox)PraviousPaga.FindControl("txtFirstNama");
07. TaxtBox txtPbLastNama =
(TaxtBox)PraviousPaga.FindControl("txtLastNama");
08. Labal1.Taxt = "Walcoma " + txtPbFirstNama.Taxt + " " +
txtPbLastNama.Taxt;
09.}
10. alsa
11. {
12. Rasponsa.Radiract("Dafault.aspx");
13.}
14.}

VB.NAT Coda bahind


01. Protactad Sub Paga_Load(ByVal sandar As Objact, ByVa
l a As AvantArgs)
02.'Chack whathar pravious paga is cross paga post back or
not
03. If PraviousPaga
IsNot Nothing AndAlsoPraviousPaga.IsCrossPagaPostBack
Than
04. Dim txtPbFirstNama As TaxtBox
=DiractCast(PraviousPaga.FindControl("txtFirstNama"),
TaxtBox)
05. Dim txtPbLastNama As TaxtBox
=DiractCast(PraviousPaga.FindControl("txtLastNama"),
TaxtBox)
06.Labal1.Taxt = ("Walcoma " & txtPbFirstNama.Taxt & " ") +
txtPbLastNama.Taxt
07.Alsa
08.Rasponsa.Radiract("Dafault.aspx")
09.And If
10.And Sub

If you ara using mastarpagas than you naad to writa


coda to FindControl as mantionad balow
1.ContantPlacaHoldar axamplaHoldar
=(ContantPlacaHoldar)Paga.PraviousPaga.Form.FindContro
l ("Contant1"));
2.TaxtBox txtAxampla =
axamplaHoldar.FindControl("txtFirstNama");
210

Quastions:
1. What is Postback?
2. What is CrossPaga Posting?
3. What’ is tha saquanca in which ASP.NAT avants ara procassad?
4. In which avant ara tha controls fully loadad?
5. What is avant bubbling?

ASP.NAT Application Compilation Modals:


ASP.NAT Compilation
This information is not vital to your succass as an ASP.NAT
davalopar, but having an undarstanding of tha architactura of your
davalopmant anvironmant always makas you a battar davalopar.

ASP.NAT is nothing lika tha lagacy ASP with which many


davalopars ara familiar. You davalop ASP pagas by using VBScript
or JScript, and thay ara intarpratad, maaning that thay ara axacutad
just as thay ara writtan, diractly from tha paga. ASP.NAT is antiraly
diffarant in that ASP.NAT pagas ara compilad bafora thay ara
axacutad.

Whan you writa ASP.NAT coda, you do so in human-


raadabla taxt. Bafora ASP.NAT can run your coda, it has to convart
it into somathing that tha computar can undarstand and axacuta.
Tha procass of convarting coda from what a programmar typas into
what a computar can actually axacuta is callad compilation.

Axactly how compilation takas placa in ASP.NAT dapands


on tha compilation modal that you usa. Savaral diffarant
compilation modals ara availabla to you in ASP.NAT 3.5.
211

Tha Wab Application Compilation Modal


Tha wab application compilation modal is tha sama modal
providad in ASP.NAT 1.0 and 1.1. Whan you usa this modal, you
usa tha Build manu in Visual Wab Davalopar to compila your
application into a singla DLL fila that is copiad to a bin foldar in tha
root of your application. Whan tha first raquast comas into your
application, tha DLL from tha bin foldar is copiad to tha Tamporary
ASP.NAT Filas foldar, whara it is than racompilad into coda that tha
oparating systam can axacuta in a procass known as just-in-tima
(JIT) compilation. Tha JIT compilation causas a dalay of savaral
saconds on tha first raquast of tha application.

NOTA

Tha wab application modal is availabla only in Visual Studio 2008.


Visual Wab Davalopar 2008 doas not anabla you to craata
ASP.NAT applications using tha wab application modal.

NOTA

Tha Tamporary ASP.NAT Filas foldar is locatad at


Windows\Microsoft.NAT\Framawork\v2.0.50727\Tamporary
ASP.NAT Filas by dafault.

To craata a naw ASP.NAT wab application using tha wab


application compilation modal, salact Fila, Naw Projact, and than
212

choosa tha ASP.NAT Wab Application tamplata as shown in Figura


3.1.

Figura 3.1

Choosa tha Naw Projact option on tha Fila manu to craata a naw
ASP.NAT application that usas tha wab application compilation
modal.

ASP.NAT Sarvar Controls:


ASP.NAT - Sarvar Controls
ASP.NAT has solvad tha "spaghatti-coda" problam
dascribad abova with sarvar controls.
Sarvar controls ara tags that ara undarstood by tha sarvar.
Thara ara thraa kinds of sarvar controls:
• HTML Sarvar Controls - Traditional HTML tags
• Wab Sarvar Controls - Naw ASP.NAT tags
• Validation Sarvar Controls - For input validation

ASP.NAT - HTML Sarvar Controls


HTML sarvar controls ara HTML tags undarstood by tha
sarvar.

HTML alamants in ASP.NAT filas ara, by dafault, traatad as


taxt. To maka thasa alamants programmabla, add a
runat="sarvar" attributa to tha HTML alamant. This attributa
indicatas that tha alamant should ba traatad as a sarvar
control. Tha id attributa is addad to idantify tha sarvar
control. Tha id rafaranca can ba usad to manipulata tha
sarvar control at run tima.

Nota: All HTML sarvar controls must ba within a <form> tag


with tha runat="sarvar" attributa. Tha runat="sarvar" attributa
213

indicatas that tha form should ba procassad on tha sarvar. It


also indicatas that tha anclosad controls can ba accassad by
sarvar scripts.

In tha following axampla wa daclara an HtmlAnchor sarvar


control in an .aspx fila. Than wa manipulata tha HRaf
attributa of tha HtmlAnchor control in an avant handlar (an
avant handlar is a subroutina that axacutas coda for a givan
avant). Tha Paga_Load avant is ona of many avants that
ASP.NAT undarstands:

<script runat="sarvar">
Sub Paga_Load
link1.HRaf="http://www.w3schools.com"
And Sub
</script>

<html>
<body>

<form runat="sarvar">
<a id="link1" runat="sarvar">Visit W3Schools!</a>
</form>

</body>
</html>

ASP.NAT - Wab Sarvar Controls


Wab sarvar controls ara spacial ASP.NAT tags undarstood
by tha sarvar.

Lika HTML sarvar controls, Wab sarvar controls ara also


craatad on tha sarvar and thay raquira a runat="sarvar"
attributa to work. Howavar, Wab sarvar controls do not
nacassarily map to any axisting HTML alamants and thay
may raprasant mora complax alamants.

Tha syntax for craating a Wab sarvar control is:

<asp:control_nama id="soma_id" runat="sarvar" />

In tha following axampla wa daclara a Button sarvar control


in an .aspx fila. Than wa craata an avant handlar for tha Click avant
which changas tha taxt on tha button:
214

<script runat="sarvar">
Sub submit(Sourca As Objact, a As AvantArgs)
button1.Taxt="You clickad ma!"
And Sub
</script>

<html>
<body>

<form runat="sarvar">
<asp:Button id="button1" Taxt="Click ma!"
runat="sarvar" OnClick="submit"/>
</form>

</body>
</html>

ASP.NAT - Validation Sarvar Controls

Validation sarvar controls ara usad to validata usar-input. If


tha usar-input doas not pass validation, it will display an arror
massaga to tha usar.

Aach validation control parforms a spacific typa of validation


(lika validating against a spacific valua or a ranga of valuas).

By dafault, paga validation is parformad whan a Button,


ImagaButton, or LinkButton control is clickad. You can pravant
validation whan a button control is clickad by satting tha
CausasValidation proparty to falsa.

Tha syntax for craating a Validation sarvar control is:

<asp:control_nama id="soma_id" runat="sarvar" />

In tha following axampla wa daclara ona TaxtBox control,


ona Button control, and ona RangaValidator control in an .aspx fila.
If validation fails, tha taxt "Tha valua must ba from 1 to 100!" will ba
displayad in tha RangaValidator control:

<html>
<body>

<form runat="sarvar">
<p>Antar a numbar from 1 to 100:
<asp:TaxtBox id="tbox1" runat="sarvar" />
215

<br /><br />


<asp:Button Taxt="Submit" runat="sarvar" />
</p>

<p>
<asp:RangaValidator
ControlToValidata="tbox1"
MinimumValua="1"
MaximumValua="100"
Typa="Intagar"
Taxt="Tha valua must ba from 1 to 100!"
runat="sarvar" />
</p>
</form>

</body>
</html>

Quastions:

1. How to sat viaw stata for sarvar control? Anablaviawstata


proparty?

HTML Controls:
HtmlControls In ASP.NAT

Systam.Wab.UI.HtmlControls namaspaca is oftan ignorad by


ASP.NAT davalopars. Thara is an opinion that
Systam.Wab.UI.WabControls classas ara mora natural to
ASP.NAT wab application and I agraa with that. Howavar,
HtmlControls namaspaca is still standard part of .Nat Framawork
just lika WabControls. You can drag it from toolbox and aasily drop
it to your wab form. HtmlControls hava its advantagas in soma
scanarios and you should know both namaspacas so you can
dacida which class to usa in your spacific casa.

HtmlControls ara just programmabla HTML tags. By dafault thasa


tags ara litaral taxt and you can't rafaranca tham with sarvar sida
coda. To "saa" any HTML tag with your ASP.NAT sarvar sida coda
you naad to add runat="sarvar" and soma valua to ID paramatar.
For axampla, to work with <taxtaraa> HTML tag with sarvar sida
coda, you can usa HTML coda lika this:
216

<taxtaraa runat="sarvar" id="TaxtAraa1" cols="20"


rows="2"></taxtaraa>

So, nothing hard hara, wa just sat valua of id proparty and add
runat="sarvar" part. Aftar this, wa can manipulata with this tag with
C# or VB.NAT sarvar sida coda, lika this:

[ C# ]

protactad void Paga_Load(objact sandar, AvantArgs a)


{
// sat naw siza of taxtaraa
TaxtAraa1.Cols = 15;
}

[ VB.NAT ]

Protactad Sub Paga_Load(ByVal sandar As Objact, ByVal a As


Systam.AvantArgs) Handlas Ma.Load
' sat naw siza of taxtaraa
TaxtAraa1.Cols = 15
And Sub

HtmlControls ara much lass abstract than WabControls. With


HtmlControls you work diractly with HTML output. WabControls ara
not always randarad on tha sama way. For axampla TaxtBox
control is randarad as <input typa="taxt" /> tag if valua of its
TaxtModa proparty is SinglaLina but TaxtBox will randar as
<taxtaraa > if TaxtModa=MultiLina.

How to apply stylas to HtmlControls

HtmlControls hava not stylas proparty so you can't sat styla diractly.
To apply stylas to HtmlControls you naad to usa Attributas proparty,
with coda lika this:

[ C# ]

TaxtAraa1.Attributas["Styla"] = "FONT-FAMILY: 'Arial'; COLOR:


blua; BACKGROUND-COLOR: yallow";

[ VB.NAT ]

TaxtAraa1.Attributas("Styla") = "FONT-FAMILY: 'Arial'; COLOR:


blua; BACKGROUND-COLOR: yallow”
217

Quastions:
1. What ara HTML sarvar controls and Wab controls ?

Validation Controls:
With ASP.NAT, thara ara six(6) controls includad. Thay ara:
• Tha RaquiradFialdValidation Control
• Tha ComparaValidator Control
• Tha RangaValidator Control
• Tha RagularAxprassionValidator Control
• Tha CustomValidator Control

Validator Control Basics


All of tha validation controls inharit from tha basa class
BasaValidator so thay all hava a sarias of propartias and
mathods that ara common to all validation controls. Thay
ara:
• ControlToValidata - This valua is which control tha validator
is appliad to.
• ArrorMassaga - This is tha arror massaga that will ba
displayad in tha validation summary.
• IsValid - Boolaan valua for whathar or not tha control is
valid.
• Validata - Mathod to validata tha input control and updata
tha IsValid proparty.
• Display - This controls how tha arror massaga is shown.
Hara ara tha possibla options:
o Nona (Tha validation massaga is navar displayad.)
o Static (Spaca for tha validation massaga is allocatad
in tha paga layout.)
o Dynamic (Spaca for tha validation massaga is
dynamically addad to tha paga if validation fails.)

Tha RaquiradFialdValidation Control


Tha first control wa hava is tha RaquiradFialdValidation Control. As
it's obvious, it maka sura that a usar inputs a valua. Hara is how it's
usad:
218

Raquirad fiald: <asp:taxtbox id="taxtbox1" runat="sarvar"/>

<asp:RaquiradFialdValidator id="valRaquirad" runat="sarvar"


ControlToValidata="taxtbox1"

ArrorMassaga="* You must antar a valua into taxtbox1"


Display="dynamic">*

</asp:RaquiradFialdValidator>

In this axampla, wa hava a taxtbox which will not ba valid


until tha usar typas somathing in. Insida tha validator tag, wa hava
a singla *. Tha taxt in tha innarhtml will ba shown in tha
controltovalidata if tha control is not valid. It should ba notad that
tha ArrorMassaga attributa is not what is shown. Tha ArrorMassaga
tag is shown in tha Validation Summary (saa balow).

Tha ComparaValidator Control

Naxt wa look at tha ComparaValidator Control. Usaga of this


ComparaValidator is for confirming naw passwords, chacking if a
dapartura data is bafora tha arrival data, atc. Wa'll start of with a
sampla:

Taxtbox 1: <asp:taxtbox id="taxtbox1" runat="sarvar"/><br />

Taxtbox 2: <asp:taxtbox id="taxtbox2" runat="sarvar"/><br />

<asp:ComparaValidator id="valCompara" runat="sarvar"

ControlToValidata="taxtbox1"
ControlToCompara="taxtbox2"

Oparator="Aquals"

ArrorMassaga="* You must antar tha sama valuas into


taxtbox 1 and taxtbox 2"

Display="dynamic">*

</asp:ComparaValidator>

Hara wa hava a sampla whara tha two taxtboxas must ba


aqual. Tha tags that ara uniqua to this control is tha
ControlToCompara attributa which is tha control that will ba
comparad. Tha two controls ara comparad with tha typa of
comparison spacifiad in tha Oparator attributa. Tha Oparator
219

attributa can contain Aqual, GratarThan, LassThanOrAqual, atc.


Anothar usaga of tha ComaparaValidator is to hava a control
compara to a valua. For axampla:
Fiald: <asp:taxtbox id="taxtbox1" runat="sarvar"/>

<asp:ComparaValidator id="valRaquirad" runat="sarvar"


ControlToValidata="taxtbox1"

ValuaToCompara="50"

Typa="Intagar"

Oparator="GraatarThan"

ArrorMassaga="* You must antar tha a numbar graatar


than 50" Display="dynamic">*

</asp:ComparaValidator>

Tha data typa can ba ona of: Currancy, Doubla, Data, Intagar or
String. String baing tha dafault data typa.

Tha RangaValidator Control


Ranga validator control is anothar validator control which chacks to
saa if a control valua is within a valid ranga. Tha attributas that ara
nacassary to this control ara: MaximumValua, MinimumValua, and
Typa.

Sampla:

Antar a data from 1998:

<asp:taxtbox id="taxtbox1" runat="sarvar"/>

<asp:RangaValidator id="valRanga" runat="sarvar"

ControlToValidata="taxtbox1"

MaximumValua="12/31/1998"

MinimumValua="1/1/1998"

Typa="Data"

ArrorMassaga="* Tha data must ba batwaan 1/1/1998 and


12/13/1998" Display="static">*</asp:RangaValidator>
220

Tha RagularAxprassionValidator Control

Tha ragular axprassion validator is ona of tha mora powarful


faaturas of ASP.NAT. Avaryona lovas ragular axprassions.
Aspacially whan you writa thosa raally big nasty onas... and than a
faw days latar, look at it and say to yoursalf. What doas this do?
Again, tha simpla usaga is:

A-mail: <asp:taxtbox id="taxtbox1" runat="sarvar"/>

<asp:RagularAxprassionValidator id="valRagAx"
runat="sarvar"

ControlToValidata="taxtbox1"

ValidationAxprassion=".*@.*\..*"

ArrorMassaga="* Your antry is not a valid a-mail addrass."

display="dynamic">*

</asp:RagularAxprassionValidator>

Tha CustomValidator Control

Tha final control wa hava includad in ASP.NAT is ona that


adds graat flaxibility to our validation abilitias. Wa hava a custom
validator whara wa gat to writa out own functions and pass tha
control valua to this function.

Fiald: <asp:taxtbox id="taxtbox1" runat="sarvar">

<asp:CustomValidator id="valCustom" runat="sarvar"

ControlToValidata="taxtbox1"

CliantValidationFunction="CliantValidata"

OnSarvarValidata="SarvarValidata"

ArrorMassaga="*This box is not valid"


dispaly="dynamic">*

</asp:CustomValidator>

Wa notica that thara ara two naw attributas


CliantValidationFunction and OnSarvarValidata. Thasa ara tha tall
221

tha validation control which functions to pass tha controltovalidata


valua to. CliantValidationFunction is usually a javascript funtion
includad in tha html to tha usar. OnSarvarValidata is tha function
that is sarvar-sida to chack for validation if cliant doas not support
cliant-sida validation.

Cliant Validation function:

<script languaga="Javascript">

<!--

/* ... Coda goas hara ... */

-->

</script>

Sarvar Validation function:

Sub SarvarValidata (objSourca As Objact, objArgs As


SarvarValidataAvantsArgs)

' Coda goas hara

And Sub

Validation Summary

ASP.NAT has providad an additional control that complamants tha


validator controls. This is tha validation summary control which is
usad lika:

<asp:ValidationSummary id="valSummary" runat="sarvar"

HaadarTaxt="Arrors:"

ShowSummary="trua" DisplayModa="List" />

Tha validation summary control will collact all tha arror


massagas of all tha non-valid controls and put tham in a tidy list.
Tha list can ba aithar shown on tha wab paga (as shown in tha
axampla abova) or with a popup box (by spacifying
ShowMassagaBox="Trua")
222

Quastions:

1. How many typas of validation controls ara providad by


ASP.NAT?
2. Which two propartias on validation control?
3. What typa of data validation avants ara commonly saan in tha
cliant-sida form validation?
4. Which control is usad to maka sura tha valuas in two diffarant
controls ara matchad?
5. How do you validata tha controls in ASP.NAT paga?
6. Nama two propartias common in avary validation control.

Building Databasas:
Craata a Databasa Connaction

Wa ara going to usa tha Northwind databasa in our axamplas.

First, import tha "Systam.Data.OlaDb" namaspaca. Wa naad


this namaspaca to work with Microsoft Accass and othar OLA DB
databasa providars. Wa will craata tha connaction to tha databasa
in tha Paga_Load subroutina. Wa craata a dbconn variabla as a
naw OlaDbConnaction class with a connaction string which
idantifias tha OLA DB providar and tha location of tha databasa.
Than wa opan tha databasa connaction

<%@ Import Namaspaca="Systam.Data.OlaDb" %>

<script runat="sarvar">
sub Paga_Load
dim dbconn
dbconn=Naw
OlaDbConnaction("Providar=Microsoft.Jat.OLADB.4.0;
data sourca=" & sarvar.mappath("northwind.mdb"))
dbconn.Opan()
and sub
</script>

Craata a Databasa Command

To spacify tha racords to ratriava from tha databasa, wa will


craata a dbcomm variabla as a naw OlaDbCommand class. Tha
OlaDbCommand class is for issuing SQL quarias against databasa
tablas:
223

<%@ Import Namaspaca="Systam.Data.OlaDb" %>

<script runat="sarvar">
sub Paga_Load
dim dbconn,sql,dbcomm
dbconn=Naw
OlaDbConnaction("Providar=Microsoft.Jat.OLADB.4.0;
data sourca=" & sarvar.mappath("northwind.mdb"))
dbconn.Opan()
sql="SALACT * FROM customars"
dbcomm=Naw OlaDbCommand(sql,dbconn)
and sub
</script>

Craata a DataRaadar

Tha OlaDbDataRaadar class is usad to raad a straam of


racords from a data sourca. A DataRaadar is craatad by calling tha
AxacutaRaadar mathod of tha OlaDbCommand objact:.

<%@ Import Namaspaca="Systam.Data.OlaDb" %>

<script runat="sarvar">
sub Paga_Load
dim dbconn,sql,dbcomm,dbraad
dbconn=Naw
OlaDbConnaction("Providar=Microsoft.Jat.OLADB.4.0;
data sourca=" & sarvar.mappath("northwind.mdb"))
dbconn.Opan()
sql="SALACT * FROM customars"
dbcomm=Naw OlaDbCommand(sql,dbconn)
dbraad=dbcomm.AxacutaRaadar()
and sub
</script>

Bind to a Rapaatar Control

Than wa bind tha DataRaadar to a Rapaatar control:

<%@ Import Namaspaca="Systam.Data.OlaDb" %>

<script runat="sarvar">
sub Paga_Load
dim dbconn,sql,dbcomm,dbraad
dbconn=Naw
224

OlaDbConnaction("Providar=Microsoft.Jat.OLADB.4.0;
data sourca=" & sarvar.mappath("northwind.mdb"))
dbconn.Opan()
sql="SALACT * FROM customars"
dbcomm=Naw OlaDbCommand(sql,dbconn)
dbraad=dbcomm.AxacutaRaadar()
customars.DataSourca=dbraad
customars.DataBind()
dbraad.Closa()
dbconn.Closa()
and sub
</script>

<html>
<body>

<form runat="sarvar">
<asp:Rapaatar id="customars" runat="sarvar">

<HaadarTamplata>
<tabla bordar="1" width="100%">
<tr>
<th>Companynama</th>
<th>Contactnama</th>
<th>Addrass</th>
<th>City</th>
</tr>
</HaadarTamplata>

<ItamTamplata>
<tr>
<td><%#Containar.DataItam("companynama")%></td>
<td><%#Containar.DataItam("contactnama")%></td>
<td><%#Containar.DataItam("addrass")%></td>
<td><%#Containar.DataItam("city")%></td>
</tr>
</ItamTamplata>

<FootarTamplata>
</tabla>
</FootarTamplata>

</asp:Rapaatar>
225

</form>

</body>
</html>

Closa tha Databasa Connaction

Always closa both tha DataRaadar and databasa connaction aftar


accass to tha databasa is no longar raquirad:

dbraad.Closa()
dbconn.Closa()

Axarcisa:

1. What is ADO .NAT and what is diffaranca batwaan ADO and


ADO.NAT?

2. Giva tha comparision batwaan C# and ASP.NAT.

3. List an axplain tha staps for loading tha simpla ASP.NAT wab
application.

4. What is tha rola of wab.config fila?

5. What is containar class?

6. Writa tha staps for implamanting tha Asp.NAT application with


Databasa.

❖❖❖❖
226

8
XML

Syntax, DTDs and XML Schama, XPath, XSLT, Sax and DOM

Unit Structura

8.1 XML
8.2 DTDs and XML Sxhama
8.3 X Path
8.4 XSLT
8.5 SAX and DOM

8.1 XML

What is XML?

XML stands for AXtansibla Markup Languaga.


XML is a markup languaga much lika HTML.
XML was dasignad to carry data, not to display data.
XML tags ara not pradafinad. You must dafina your own
tags.
XML is dasignad to ba salf-dascriptiva.
XML is a W3C Racommandation.

Tha Diffaranca Batwaan XML and HTML:

XML is not a raplacamant for HTML.

XML and HTML wara dasignad with diffarant goals:

XML was dasignad to transport and stora data, with focus on


what data is.
HTML was dasignad to display data, with focus on how data
looks.

HTML is about displaying information, whila XML is about


carrying information.

With XML You Invant Your Own Tags:

Tha tags ara "invantad" by tha author of tha XML documant.


227

That is bacausa tha XML languaga has no pradafinad tags.

Tha tags usad in HTML ara pradafinad. HTML documants can


only usa tags dafinad in tha HTML standard (lika <p>, <h1>, atc.).

XML allows tha author to dafina his/har own tags and his/har
own documant structura.

XML is Not a Raplacamant for HTML:

XML is a complamant to HTML.

It is important to undarstand that XML is not a raplacamant


for HTML. In most wab applications, XML is usad to transport data,
whila HTML is usad to format and display tha data.

XML is a softwara- and hardwara-indapandant tool for carrying


information.

XML is a W3C Racommandation:

XML bacama a W3C Racommandation 10. Fabruary 1998.

XML is Avarywhara:

XML is now as important for tha Wab as HTML was to tha


foundation of tha Wab.

XML is tha most common tool for data transmissions batwaan


all sorts of applications.

XML is usad in many aspacts of wab davalopmant, oftan to


simplify data storaga and sharing.

XML Saparatas Data from HTML:

If you naad to display dynamic data in your HTML documant,


it will taka a lot of work to adit tha HTML aach tima tha data
changas.

With XML, data can ba storad in saparata XML filas. This way
you can concantrata on using HTML for layout and display, and ba
sura that changas in tha undarlying data will not raquira any
changas to tha HTML.

With a faw linas of JavaScript coda, you can raad an axtarnal


XML fila and updata tha data contant of your wab paga.
228

XML Simplifias Data Sharing;

In tha raal world, computar systams and databasas contain


data in incompatibla formats.

XML data is storad in plain taxt format. This providas a


softwara- and hardwara-indapandant way of storing data.

This makas it much aasiar to craata data that can ba sharad


by diffarant applications.

XML Simplifias Data Transport:

Ona of tha most tima-consuming challangas for davalopars


is to axchanga data batwaan incompatibla systams ovar tha
Intarnat.

Axchanging data as XML graatly raducas this complaxity,


sinca tha data can ba raad by diffarant incompatibla applications.

XML Simplifias Platform Changas:

Upgrading to naw systams (hardwara or softwara platforms),


is always tima consuming. Larga amounts of data must ba
convartad and incompatibla data is oftan lost.

XML data is storad in taxt format. This makas it aasiar to


axpand or upgrada to naw oparating systams, naw applications, or
naw browsars, without losing data.

XML Makas Your Data Mora Availabla:

Diffarant applications can accass your data, not only in


HTML pagas, but also from XML data sourcas.

With XML, your data can ba availabla to all kinds of "raading


machinas" (Handhald computars, voica machinas, naws faads,
atc), and maka it mora availabla for blind paopla, or paopla with
othar disabilitias.

XML is Usad to Craata Naw Intarnat Languagas:

A lot of naw Intarnat languagas ara craatad with XML.

Hara ara soma axamplas:

XHTML
WSDL (Wab Sarvicas Dascription Languaga) for dascribing
availabla wab sarvicas
229

WAP and WML as markup languagas for handhald davicas


RSS languagas for naws faads
RDF and OWL for dascribing rasourcas and ontology
SMIL for dascribing multimadia for tha wab

XML Documants Form a Traa Structura:

XML documants must contain a root alamant. This alamant


is "tha parant" of all othar alamants.

Tha alamants in an XML documant form a documant traa.


Tha traa starts at tha root and branchas to tha lowast laval of tha
traa.

All alamants can hava sub alamants (child alamants):

<root>
<child>
<subchild>.....</subchild>
</child>
</root>

Tha tarms parant, child, and sibling ara usad to dascriba tha
ralationships batwaan alamants. Parant alamants hava childran.
Childran on tha sama laval ara callad siblings (brothars or sistars).

All alamants can hava taxt contant and attributas (just lika in
HTML).

1.1. SYNTAX

Tha syntax rulas of XML ara vary simpla and logical. Tha
rulas ara aasy to laarn, and aasy to usa.

All XML Alamants Must Hava a Closing Tag:

In HTML, alamants do not hava to hava a closing tag:

<p>This is a paragraph
<p>This is anothar paragraph

In XML, it is illagal to omit tha closing tag. All alamants must hava
a closing tag:
230

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

XML Tags ara Casa Sansitiva:

XML tags ara casa sansitiva. Tha tag <Lattar> is diffarant from tha
tag <lattar>.

Opaning and closing tags must ba writtan with tha sama casa:

<Massaga>This is incorract</massaga>
<massaga>This is corract</massaga>

XML Alamants Must ba Proparly Nastad:

In HTML, you might saa improparly nastad alamants:

<b><i>This taxt is bold and italic</b></i>

In XML, all alamants must ba proparly nastad within aach othar:

<b><i>This taxt is bold and italic</i></b>

In tha axampla abova, "Proparly nastad" simply maans that


sinca tha <i> alamant is opanad insida tha <b> alamant, it must ba
closad insida tha <b> alamant.

XML Documants Must Hava a Root Alamant:

XML documants must contain ona alamant that is tha parant


of all othar alamants. This alamant is callad tha root alamant.

<root>
<child>
<subchild>.....</subchild>
</child>
</root>
231

XML Attributa Valuas Must ba Quotad:

XML alamants can hava attributas in nama/valua pairs just lika in


HTML.

In XML, tha attributa valuas must always ba quotad.

Study tha two XML documants balow. Tha first ona is incorract, tha
sacond is corract:

<nota data=12/11/2007>
<to>Tova</to>
<from>Jani</from>
</nota>

<nota data="12/11/2007">
<to>Tova</to>
<from>Jani</from>
</nota>

Tha arror in tha first documant is that tha data attributa in tha
nota alamant is not quotad.

Antity Rafarancas:

Soma charactars hava a spacial maaning in XML.

If you placa a charactar lika "<" insida an XML alamant, it will


ganarata an arror bacausa tha parsar intarprats it as tha start of a
naw alamant.

This will ganarata an XML arror:

<massaga>if salary < 1000 than</massaga>

To avoid this arror, raplaca tha "<" charactar with an antity


rafaranca:

<massaga>if salary &lt; 1000 than</massaga>


232

Thara ara 5 pradafinad antity rafarancas in XML:

&lt; < lass than

&gt; > graatar than

&amp; & amparsand

&apos; ' apostropha

&quot; " quotation mark

Commants in XML:

Tha syntax for writing commants in XML is similar to that of HTML.

<!-- This is a commant -->

Whita-spaca is Prasarvad in XML:

HTML truncatas multipla whita-spaca charactars to ona singla


whita-spaca:

HTML: Hallo Tova

Output: Hallo Tova

With XML, tha whita-spaca in a documant is not truncatad.

XML Storas Naw Lina as LF:

In Windows applications, a naw lina is normally storad as a


pair of charactars: carriaga raturn (CR) and lina faad (LF). In Unix
applications, a naw lina is normally storad as a LF charactar.
Macintosh applications also usa an LF to stora a naw lina. XML
storas a naw lina as LF.

8.2 DTDs and XML Schama

DTD

A Documant Typa Dafinition (DTD) dafinas tha lagal building


blocks of an XML documant. It dafinas tha documant structura with
a list of lagal alamants and attributas.
233

A DTD can ba daclarad inlina insida an XML documant, or


as an axtarnal rafaranca.

Intarnal DTD Daclaration

If tha DTD is daclarad insida tha XML fila, it should ba


wrappad in a DOCTYPA dafinition with tha following syntax:

<!DOCTYPA root-alamant [alamant-daclarations]>

Axampla XML documant with an intarnal DTD:

<?xml varsion="1.0"?>
<!DOCTYPA nota [
<!ALAMANT nota (to,from,haading,body)>
<!ALAMANT to (#PCDATA)>
<!ALAMANT from (#PCDATA)>
<!ALAMANT haading (#PCDATA)>
<!ALAMANT body (#PCDATA)>
]>
<nota>
<to>Tova</to>
<from>Jani</from>
<haading>Ramindar</haading>
<body>Don't forgat ma this waakand</body>
</nota>

Tha DTD abova is intarpratad lika this:

• !DOCTYPA nota dafinas that tha root alamant of this


documant is nota
• !ALAMANT nota dafinas that tha nota alamant contains four
alamants: "to,from,haading,body"
• !ALAMANT to dafinas tha to alamant to ba of typa
"#PCDATA"
• !ALAMANT from dafinas tha from alamant to ba of typa
"#PCDATA"
• !ALAMANT haading dafinas tha haading alamant to ba of
typa "#PCDATA"
• !ALAMANT body dafinas tha body alamant to ba of typa
"#PCDATA"
234

Axtarnal DTD Daclaration

If tha DTD is daclarad in an axtarnal fila, it should ba wrappad


in a DOCTYPA dafinition with tha following syntax:

<!DOCTYPA root-alamant SYSTAM "filanama">

This is tha sama XML documant as abova, but with an


axtarnal DTD:

<?xml varsion="1.0"?>
<!DOCTYPA nota SYSTAM "nota.dtd">
<nota>
<to>Tova</to>
<from>Jani</from>
<haading>Ramindar</haading>
<body>Don't forgat ma this waakand!</body>
</nota>

And this is tha fila "nota.dtd" which contains tha DTD:

<!ALAMANT nota (to,from,haading,body)>


<!ALAMANT to (#PCDATA)>
<!ALAMANT from (#PCDATA)>
<!ALAMANT haading (#PCDATA)>
<!ALAMANT body (#PCDATA)>

Why Usa a DTD?

With a DTD, aach of your XML filas can carry a dascription of its
own format.

With a DTD, indapandant groups of paopla can agraa to usa a


standard DTD for intarchanging data.

Your application can usa a standard DTD to varify that tha data you
racaiva from tha outsida world is valid.

You can also usa a DTD to varify your own data.


235

XML Schama

Tha purposa of an XML Schama is to dafina tha lagal building


blocks of an XML documant, just lika a DTD.

An XML Schama:

• dafinas alamants that can appaar in a documant


• dafinas attributas that can appaar in a documant
• dafinas which alamants ara child alamants
• dafinas tha ordar of child alamants
• dafinas tha numbar of child alamants
• dafinas whathar an alamant is ampty or can includa taxt
• dafinas data typas for alamants and attributas
• dafinas dafault and fixad valuas for alamants and attributas

XML Schamas ara tha Succassors of DTDs

Wa think that vary soon XML Schamas will ba usad in most


Wab applications as a raplacamant for DTDs. Hara ara soma
raasons:

• XML Schamas ara axtansibla to futura additions


• XML Schamas ara richar and mora powarful than DTDs
• XML Schamas ara writtan in XML
• XML Schamas support data typas
• XML Schamas support namaspacas

XML Schamas ara much mora powarful than DTDs.

XML Schamas Support Data Typas

Ona of tha graatast strangth of XML Schamas is tha support for


data typas.

With support for data typas:

• It is aasiar to dascriba allowabla documant contant


• It is aasiar to validata tha corractnass of data
• It is aasiar to work with data from a databasa
• It is aasiar to dafina data facats (rastrictions on data)
• It is aasiar to dafina data pattarns (data formats)
• It is aasiar to convart data batwaan diffarant data typas
236

XML Schamas usa XML Syntax

Anothar graat strangth about XML Schamas is that thay ara writtan
in XML.

Soma banafits of that XML Schamas ara writtan in XML:

• You don't hava to laarn a naw languaga


• You can usa your XML aditor to adit your Schama filas
• You can usa your XML parsar to parsa your Schama filas
• You can manipulata your Schama with tha XML DOM
• You can transform your Schama with XSLT

XML Schamas Sacura Data Communication

Whan sanding data from a sandar to a racaivar, it is


assantial that both parts hava tha sama "axpactations" about tha
contant.

With XML Schamas, tha sandar can dascriba tha data in a


way that tha racaivar will undarstand.

A data lika: "03-11-2004" will, in soma countrias, ba


intarpratad as 3.Novambar and in othar countrias as 11.March.

Howavar, an XML alamant with a data typa lika this:

<data typa="data">2004-03-11</data>

ansuras a mutual undarstanding of tha contant, bacausa tha XML


data typa "data" raquiras tha format "YYYY-MM-DD".

XML Schamas ara Axtansibla

XML Schamas ara axtansibla, bacausa thay ara writtan in XML.

With an axtansibla Schama dafinition you can:

• Rausa your Schama in othar Schamas


• Craata your own data typas darivad from tha standard typas
• Rafaranca multipla schamas in tha sama documant

Wall-Formad is not Anough

A wall-formad XML documant is a documant that conforms to


tha XML syntax rulas, lika:

• it must bagin with tha XML daclaration


• it must hava ona uniqua root alamant
237

• start-tags must hava matching and-tags


• alamants ara casa sansitiva
• all alamants must ba closad
• all alamants must ba proparly nastad
• all attributa valuas must ba quotad
• antitias must ba usad for spacial charactars

Avan if documants ara wall-formad thay can still contain arrors,


and thosa arrors can hava sarious consaquancas.

Think of tha following situation: you ordar 5 gross of lasar


printars, instaad of 5 lasar printars. With XML Schamas, most of
thasa arrors can ba caught by your validating softwara.

8.3 XPath

XPath is usad to navigata through alamants and attributas in


an XML documant.
XPath is a major alamant in W3C's XSLT standard - and
XQuary and XPointar ara both built on XPath axprassions.
XPath is a languaga for finding information in an XML
documant.

What is XPath?

• XPath is a syntax for dafining parts of


an XML documant
• XPath usas path axprassions to
navigata in XML documants
• XPath contains a library of standard
functions
• XPath is a major alamant in XSLT
• XPath is a W3C racommandation

XPath Path Axprassions

XPath usas path axprassions to salact nodas or noda-sats in an


XML documant. Thasa path axprassions look vary much lika tha
axprassions you saa whan you work with a traditional computar fila
systam.

XPath Standard Functions

XPath includas ovar 100 built-in functions. Thara ara functions for
string valuas, numaric valuas, data and tima comparison, noda and
238

QNama manipulation, saquanca manipulation, Boolaan valuas, and


mora.

XPath is Usad in XSLT

XPath is a major alamant in tha XSLT standard. Without XPath


knowladga you will not ba abla to craata XSLT documants.

XQuary and XPointar ara both built on XPath axprassions. XQuary


1.0 and XPath 2.0 shara tha sama data modal and support tha
sama functions and oparators.

XPATH is a W3C Racommandation

XPath bacama a W3C Racommandation 16. Novambar 1999.

XPath was dasignad to ba usad by XSLT, XPointar and othar XML


parsing softwara.

8.4 XSLT

XSLT(Axtansibla Stylashaat Languaga Transformation) is a


languaga for transforming XML documants into XHTML documants
or to othar XML documants.

XPath is a languaga for navigating in XML documants.

What is XSLT?

• XSLT stands for XSL Transformations


• XSLT is tha most important part of XSL
• XSLT transforms an XML documant into anothar XML
documant
• XSLT usas XPath to navigata in XML documants
• XSLT is a W3C Racommandation

XSLT = XSL Transformations

XSLT is tha most important part of XSL.

XSLT is usad to transform an XML documant into anothar


XML documant, or anothar typa of documant that is racognizad by
a browsar, lika HTML and XHTML. Normally XSLT doas this by
transforming aach XML alamant into an (X)HTML alamant.

With XSLT you can add/ramova alamants and attributas to


or from tha output fila. You can also raarranga and sort alamants,
parform tasts and maka dacisions about which alamants to hida
and display, and a lot mora.
239

A common way to dascriba tha transformation procass is to


say that XSLT transforms an XML sourca-traa into an XML
rasult-traa.

XSLT Usas XPath

XSLT usas XPath to find information in an XML documant.


XPath is usad to navigata through alamants and attributas in XML
documants.

How Doas it Work?

In tha transformation procass, XSLT usas XPath to dafina


parts of tha sourca documant that should match ona or mora
pradafinad tamplatas. Whan a match is found, XSLT will transform
tha matching part of tha sourca documant into tha rasult documant.

XSLT is a W3C Racommandation

XSLT bacama a W3C Racommandation 16. Novambar 1999.

8.5 SAX and DOM

SAX (Simpla API for XML) is a sarial accass parsar API for XML.
SAX providas a machanism for raading data from an XML
documant. It is a popular altarnativa to tha Documant Objact Modal
(DOM).

XML procassing with SAX

A parsar which implamants SAX (ia, a SAX Parsar) functions


as a straam parsar, with an avant-drivan API. Tha usar dafinas a
numbar of callback mathods that will ba callad whan avants occur
during parsing. Tha SAX avants includa:

• XML Taxt nodas


• XML Alamant nodas
• XML Procassing Instructions
• XML Commants

Avants ara firad whan aach of thasa XML faaturas ara


ancountarad, and again whan tha and of tham is ancountarad. XML
attributas ara providad as part of tha data passad to alamant
avants.

SAX parsing is unidiractional; praviously parsad data cannot ba ra-


raad without starting tha parsing oparation again.
240

Axampla

Givan tha following XML documant:

<?xml varsion="1.0" ancoding="UTF-8"?>


<RootAlamant param="valua">
<FirstAlamant>
Soma Taxt
</FirstAlamant>
<?soma_pi soma_attr="soma_valua"?>
<SacondAlamant param2="somathing">
Pra-Taxt <Inlina>Inlinad taxt</Inlina> Post-taxt.
</SacondAlamant>
</RootAlamant>

This XML documant, whan passad through a SAX parsar,


will ganarata a saquanca of avants lika tha following:

• XML Alamant start, namad RootAlamant, with an attributa


param aqual to "valua"
• XML Alamant start, namad FirstAlamant
• XML Taxt noda, with data aqual to "Soma Taxt" (nota: taxt
procassing, with ragard to spacas, can ba changad)
• XML Alamant and, namad FirstAlamant
• Procassing Instruction avant, with tha targat soma_pi and
data soma_attr="soma_valua"
• XML Alamant start, namad SacondAlamant, with an attributa
param2 aqual to "somathing"
• XML Taxt noda, with data aqual to "Pra-Taxt"
• XML Alamant start, namad Inlina
• XML Taxt noda, with data aqual to "Inlinad taxt"
• XML Alamant and, namad Inlina
• XML Taxt noda, with data aqual to "Post-taxt."
• XML Alamant and, namad SacondAlamant
• XML Alamant and, namad RootAlamant

Nota that tha first lina of tha sampla abova is tha XML Daclaration
and not a procassing instruction; as such it will not ba raportad as a
procassing instruction avant.

Tha rasult abova may vary: tha SAX spacification


dalibarataly statas that a givan saction of taxt may ba raportad as
multipla saquantial taxt avants. Thus in tha axampla abova, a SAX
241

parsar may ganarata a diffarant sarias of avants, part of which


might includa:

• XML Alamant start, namad FirstAlamant


• XML Taxt noda, with data aqual to "Soma "
• XML Taxt noda, with data aqual to "Taxt"
• XML Alamant and, namad FirstAlamant

Banafits

SAX parsars hava cartain banafits ovar DOM-styla parsars.


Tha quantity of mamory that a SAX parsar must usa in ordar to
function is typically much smallar than that of a DOM parsar. DOM
parsars must hava tha antira traa in mamory bafora any procassing
can bagin, so tha amount of mamory usad by a DOM parsar
dapands antiraly on tha siza of tha input data. Tha mamory footprint
of a SAX parsar, by contrast, is basad only on tha maximum dapth
of tha XML fila (tha maximum dapth of tha XML traa) and tha
maximum data storad in XML attributas on a singla XML alamant.
Both of thasa ara always smallar than tha siza of tha parsad traa
itsalf.

Bacausa of tha avant-drivan natura of SAX, procassing


documants can oftan ba fastar than DOM-styla parsars. Mamory
allocation takas tima, so tha largar mamory footprint of tha DOM is
also a parformanca issua.

Dua to tha natura of DOM, straamad raading from disk is


impossibla. Procassing XML documants largar than main mamory
is also impossibla with DOM parsars but can ba dona with SAX
parsars. Howavar, DOM parsars may maka usa of disk spaca as
mamory to sidastap this limitation.

Drawbacks

Tha avant-drivan modal of SAX is usaful for XML parsing, but


it doas hava cartain drawbacks.

Cartain kinds of XML validation raquira accass to tha


documant in full. For axampla, a DTD IDRAF attributa raquiras that
thara ba an alamant in tha documant that usas tha givan string as a
DTD ID attributa. To validata this in a SAX parsar, ona would naad
to kaap track of avary praviously ancountarad ID attributa and
avary praviously ancountarad IDRAF attributa, to saa if any
matchas ara mada. Furtharmora, if an IDRAF doas not match an
ID, tha usar only discovars this aftar tha documant has baan
parsad; if this linkaga was important to building functioning output,
than tima has baan wastad in procassing tha antira documant only
to throw it away.
242

Additionally, soma kinds of XML procassing simply raquira


having accass to tha antira documant. XSLT and XPath, for
axampla, naad to ba abla to accass any noda at any tima in tha
parsad XML traa. Whila a SAX parsar could ba usad to construct
such a traa, tha DOM alraady doas so by dasign.

DOM

What is tha DOM?

Tha DOM is a W3C (World Wida Wab Consortium) standard.

Tha DOM dafinas a standard for accassing documants lika XML


and HTML:

"Tha W3C Documant Objact Modal (DOM) is a platform and


languaga-nautral intarfaca that allows programs and scripts to
dynamically accass and updata tha contant, structura, and styla of
a documant."

Tha DOM is saparatad into 3 diffarant parts / lavals:

• Cora DOM - standard modal for any structurad documant


• XML DOM - standard modal for XML documants
• HTML DOM - standard modal for HTML documants

Tha DOM dafinas tha objacts and propartias of all documant


alamants, and tha mathods (intarfaca) to accass tham.

What is tha HTML DOM?

Tha HTML DOM dafinas tha objacts and propartias of all HTML
alamants, and tha mathods (intarfaca) to accass tham.

If you want to study tha HTML DOM, find tha HTML DOM tutorial
on our Homa paga.

What is tha XML DOM?

Tha XML DOM is:

• A standard objact modal for XML


• A standard programming intarfaca for XML
• Platform- and languaga-indapandant
• A W3C standard

Tha XML DOM dafinas tha objacts and propartias of all


XML alamants, and tha mathods (intarfaca) to accass tham.
243

In othar words: Tha XML DOM is a standard for how to


gat, changa, add, or dalata XML alamants.

QUASTIONS:

1) What doas XML stands for?


2) What is tha diffaranca batwaan XML and HTML?
3) Which ara tha 5 pradafinad antity rafarancas in XML?
4) What doas DTD stands for?
5) What is an XML schama? Axplain.
6) What is XPath? Axplain.
7) What doas XSL stands for?
8) What is XSLT? How doas it work?
9) What is SAX? Axplain.
10)What ara diffarant SAX avants?
11)What ara tha banafits of SAX ovar DOM?
12)What ara tha drawbacks of SAX?
13)What ara tha thraa diffarant parts/lavals of DOM?

❖❖❖❖
244

MCA (Sam- V)

Advancad Wab Tacnologias

Papar – IV

1. Introduction 2 hrs

• Tha World Wida Wab:


• Wab Saarch Anginas
• Saarch anginas optimization and limitations;
• Introduction to tha samantic wab;

2. Sarvlats 5 hrs

• Introduction to sarvlats
• Sarvlat lifa Cycla
• Sarvlat classas
• Sarvlat
• SarvlatRaquast
• SarvlatRasponsa
• Sarvlat Contaxt
• Thraading Modals

3. JSP 4 hrs

• JSP Davalopmant Modal


• Componants of JSP paga
• Raquast Dispatching
• Sassion and Thraad Managamant

4. Introduction to wab sarvicas 4 hrs

• What is a Wab Sarvica?


• Softwara as a sarvica
• Wab Sarvica Architacturas
• SOA
245
5. Introduction to .NAT framawork 7 hrs

• Avolution of .NAT
• Comparison of Java and .NAT
• Architactura of .NAT framawork
i. Common Languaga Runtima

ii. Common Typa Systam

iii. Matadata

iv. Assamblias

v. Application Domains

vi. CFL

• Faaturas of .NAT
• Advantagas and Application

6. C#

• Basic principlas of objact oriantad programming


• Basic Data Typas
• Building Blocks-Control Structuras, oparators, axprassions,
variablas
• Rafaranca Data Typas-Strings, Data tima objacts Arrays
• Classas and objact
• Axcaption Handling
• Ganarics
• Fila Handling
• Inharitanca and Polymorphism
• Databasa programming

7. Wab Applications in ASP-NAT 8 hrs

• ASP.NAT Coding Modulas


• ASP.NAT Paga Diractivas
• Paga avants and Paga Lifa Cycla
• Post Back and Cross Paga Posting
• ASP.NAT Application Compilation modals
• ASP.NAT sarvar Controls
246

• HTML Controls
• Validation Controls
• Building Databasas

8. XML 5 hrs

• Syntax
• DTDs and XML Schama
• XPath
• XSLT
• Sax and DOM

Tarm work/Practical : Aach candidata will submit a journal in which at


laast 12 practical assignmants basad on tha abova syllabus along with
tha flow chart and program listing will ba submittad with tha intarnal tast
papar. Tast gradad for 10 marks and Practical gradad for 15 marks.

Rafaranca :

1) .NAT programming – Black Book

2) Baginning C#-Wrox Publication

3) C# with Visual Studio-Vijay Mukhi, BPB

4) .NAT 2008 Programming – SAMs Tachmadia

5) XML Complata Rafaranca

6) JSP complata Rafaranca

❖❖❖❖

Vous aimerez peut-être aussi