ASP.Net Unisususuususuudddususueueueueyyst-1 Ꮢ.ꪜ.pdf

khodiyarpoojabhandar 5 views 28 slides Sep 23, 2025
Slide 1
Slide 1 of 28
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28

About This Presentation

Good


Slide Content

Jump2Learn
www.jump2learn.com PUBLICATIO
N
N
DEVELORINGWEBAPPLICATIONS
WITH
ASP.NET
Jump2LearnTheOnlineLearningPlace
LS
Ms.TwinklePanchal
|
Ms.KrishnaKhandwala
|
Mr.ChiragPrajapati

Unit1
Introductionto
ASP.NET

Unit-1Introductionta
ASP.NET
1.1WhatisASP.NET:
ASP.NETmeans"ActiveServerPages"whichisfrontendlanguage&itisestablished&
supportedbyMicrosoft.
ASP.NETisawebapplicationwhichallowstheprogrammertobuilddynamicwebsites,
Webapplications&webservices.ASP.NETallowstodevelopwebapplicationsusingafull
featuredprogramminglanguagesuchasCt,VB.NET,Jscriptor
JH
ASP.NETisawebdevelopmentplatform,whichprovidestheeasiest&mostaccessible
waytobuild,deploy&rundistributedwebapplicationswhichcantargetforanydeviceas
wellasbrowser.Inshort,ASP.NETisusedtoproduceinteractive,data-drivenweb
applicationsovertheinternet.
ASP.NETworksontopoftheHTTPprotocol,andusestheHTTPcommandsandpoliciesto
setabrowser-to-servertwo-sidedcommunicationandcooperation.
ASP.NETapplicationsarecompiledcodes,writtenusingtheextensibleandreusable
componentsorobjectspresentin.Netframework.Thesecodescanusetheentire
hierarchyofclassesin.Netframework.
ASP.NETconsistofalargenumberofcontrolssuchastextboxes,buttons,labels&many
moreforassembling,configuring&manipulatingcodetocreateHTMLpages.
AnASP.NETwebapplicationismadeofpages.WhenauserrequestsanASP.NETpage,the
IISgivestheprocessingofthepagetotheASP.NETruntimesystem.
TheASP.NETruntimetransformsthe.aspxpageintoaninstanceofaclass,whichinherits
fromthebaseclasspageoftheNetframework.Therefore,eachASP.NETpageisan
objectandallitscomponentsi.e.,theserver-sidecontrolsarealsoobjects.
1.2.NETFramework2.0:
NETisSoftwarePlatform.Itisalanguageneutralenvironmentfordeveloping
applications.Italsoprovidesanexecutionenvironmentandintegrationwithvarious
programminglanguagesforbuilding,deployingandrunningweb-basedandstandalone
enterpriseapplications.Allaspectstomanagetheprogramexecutionlikememory
allocationfordatastorageandinstructions,grantinganddenyingpermissiontothe
application,managingexecutionofapplicationandreallocationofmemoryforresources
whicharenotneededismanagedeasilyinASP.NET.Itconsistsofclasslibrariesand
reusablecomponents.
Theblockdiagramof.NETframeworkisasfollows:

Unit-1IntroductiontoASP.NET
VB C+ CH JScript J#
CommonLanguageSpecification
ASP.NET
Windows ADO.NET&
WebFormsWebServleesForms XML
BaseClassLibrary
CommonLanguageRuntlme
OperatingSystem
Figure1:.NETFramework
1.2.1ProgramingLanguages:
Netframeworkisdesignedforcrosslanguagecompatiblitywhichmeansitsupports
variousprograminglanguageslikeVisualBasic(VB),VisualBasic.Net(VB.Net),CH,JHetc.
Soprogrammers/developerscanchooseanyfavouriteprograminglanguagetobuildweb
application.
1.2.2CommonLanguageSpecification(CLS):
CLSisthecollectionofrulesandconstraintsthateverylanguagecompatibleto.NETmust
follow.Itisoneofthecorecomponentsofthe.NetFrameworkwhichhelpstobuild
communicationbetweendifferentcomponentswrittenindifferentprogramminglanguage
andreusethecommonlogics.MicrosofthasdefinedthreelevelofCLScompatibilityas
follow:
CompliantProducer:Thecomponentdevelopedinthistypeoflanguagecanbe
usedbyanyotherlanguage.
Consumer:Inthiscategory,thelanguagecanuseclassesproducedinanyother
language.
Extender:Inthiscategory,languagescannotuseclassesasinCONSUMERcategory
butcanalsoextendclassesusinginheritance.

Unit-1IntroductiontoASP.NET
1.2.3WebForms:
InASP.NET,webformsarecalledwebpageswhichhelptodevelopwebapplications.Itis
consistoftwoparts:
1.TemplatewhichcontainsHTMLbasedlayoutinformationforallGUIcontrols.
2.Componentwhichcontainsthelogicbehindthecontrols.
1.2.4WebServices:
Awebserviceisaweb-basedfunctionalitythatrunsonWebServer.Itisaccessedusing
theprotocolsofthewebtobeusedbythewebapplications.Theyarethesmallunitof
codewhichisdesigntohandlelimitedsetoftask.Theyareindependentofoperating
systemandprogramminglanguage.
1.2.5WindowForms:
WindowsFormscontainthegraphicalrepresentationofanywindowdisplayedinthe
application.ItalsoprovidesintegratedandunifiedwayofdevelopingGraphicalUser
Interface.IthasrichvarietyofwindowscontrolsanduserinterfacesupportlikeTextBox,
Button,CheckBox,etc.
WecandesigntheGUIbydraggingthecontroldirectlyonaformwhichmadeitpossible
todesignthewinformseasilyandquicklyasVisualStudio.NETusesthe'system.Winform
namespacetodrawtheGraphicalUserInterface.
1.2.6
ADO.NET&XML:
ItisthetechnologyusedforworkingwithdataanddatabaseswhichisalsoknownasData
AccessLayer.ItprovidesaccesstodatasourceslikeSQLserver,OLEDB,XMLetc.The
ADO.NETallowsconnectiontodatasourcesforretrieving,manipulating,andupdating
data.
1.2.7BaseClassLibrary(BCL):
.Netframeworkconsistsofclasses,interfacesandvaluetypesthathelpinspeedingupthe
developmentprocessandprovideaccesstothesystemfunctionality.Theclasslibraryisa
collectionofmethods&functionsthatcanbereusabletypesmeanttobeusedby
managedcode.
Itisanobject-orientedlibrarythatisusedincomponent-basedapplication.TheClass
libraryismadeupofahierarchyofnamespacesthatexposeclasses,structure,interfaces,
enumerationsanddelegates.Thenanespacesarelogicallydefinedbytheirfunctionality.
MostofthemethodsaresplitintoeitherSystem.orMicrosoft."namespaces.For

Unit-1IntroductiontoASP.NET
example,TheSystem.Datanamespacecontainsthefunctionalityavailableforaccessing
database.
1.2.8CommonLanguageRuntime(CLR):
Itistheruntimeenvironmentswhichdobothcompileandruntheapplication.Soitisalso
knownastheheartof.NETframework.MSIL(MicrosoftIntermediateLanguage)whichis
languageindependentcode,soCLRusesthiscodefortheexecutionoftheapplication.
TheMSILcodeistranslatedbyIT(Just-inTime)compller.
1.2.9MicrosoftIntermediateLanguage(MSIL):
ItisalsoknownasIntermediateLanguage
(1L)
orCommonIntermediateLanguage(CIL).
A.NETprogramminglanguagedoesnotcompilethecodeintoexecutablecode;insteadit
compilesthecodeintoanintermediatecodecalledMicrosoftIntermediateLanguage
(MSIL)orIntermediateLanguage(L)orCommonIntermediateLanguage(CIL).
ThisILorMSILor
CiILcodeismachineindependentcodewhichisthensendtoCLRwhich
convertsthismachineindependentcodeintonativecodewiththehelpofJIT(Just-inTime
Compiler)avalableinCLR.
1.3CompileCode:
Toservetheuserrequest,ASP.NETmustfirstcompilethecode.ASP.NETCodecanbe
writteninanylanguagesupportedby.NETframework.Whencodeiscompiled,itisfirst
convertedintoMicrosoftIndependentLanguage(MSIL).Thenthisindependentlanguageis
furtherconvertedintoMachineSpecificinstructions
BenefitsofCompiledCode:
1.Atcodecompilationtime,itischeckingforsyntaxerror,typesafetyetc.Duetowhich
manyerrorscanbeeliminatedandthatishowitgivesstabilityincodefromthelaterstage.
2.Compilecodeismuchfasterthanscriptinglanguages.Astheyaresimilartomachine
codewhichmakestheperformanceoftheexecution.
3.Compiledcodeisdifficulttoread.Sothatnoonecanconvertcompiledcodetosource
codeagainandthatishowcodebecomessecure.
4.ASMSILsupportsany.NETlanguage,weareabletouseassemblieswhicharewrittenin
differentlanguage.Forexample,ifyouarewritinganASP.NETWebpageinC4,youcanadd
areferencetoa.dllfilethatwaswritteninVisualBasic.Suchinteroperabilityfunctionalityis
alsoused.

5 Unit-1IntroductiontoASP.NET
ASP.NET2.0providestwopathsforstructuringthecodofASP.NETpages:CodeBehindand
CodeInline
1.3.1CodeBehind
Inthisway,codeisseparatedfromcontentcompletelyandstoredinaseparatefile.The
ideaofusingthecodebehindistoseparatethebusinesslogictobestoredin.aspxpage
andpresentationlogictobestoredinseparateclassfileeither.aspx.vbor.aspx.cs.By
doingthis,itmakeseasytoworkwithpages.Asifyouareworkinginteamenvironment
wherevisualdesignersworkintheUlifthepageandcodersworkonthebusinesslogic.
ThisrelationshipbetweenyourclassandthewebpageisestablishedbyaPagedirectiveat
thetopofthe.aspxfile:
<%@Pageinherits="Default"%>
Theinheritsattributeidentifiestheclasscreatedinthecode-behindfilefromwhichthis
.aspxfilewillderive.
ForExample:
WebAppicEenl-McrostVesalSeude
FAlE
EEN
TELER PRCECTBRD DEBUG TEAM FORMAT TOOL5 TEST ANALYITE WDDOW
McrosotEdge
ebug
any
U
Detaut
asp.cs
Deatap
Eoedeinderauit.Esg.CSEeritsaiopiicstiond.betault
asp:{ontast=*3adCantent"Cantet?iacencide-TD»Nainantent'rurats'senver"
idfoi
runst="serve
asp:Tertšert="rareirutrinate"server"«jasp:Fertšo
5p:el
isplayruetsevefet-abel'asp:iabe)cor
sp:8uttonDSupeitrurata"serveretSbeitiickSo:tcisce
p
asp:fexttosiDTextboxtrunarserver
iasg:
Testšono
<ingutideButtonl"typewostton'valaesbutton'runate"serve
for
/asp:Content
Figure2:CodebehindPresentationLogic

Unit-1IntroductiontoASP.NET
ET TEuu ROnC URD cEBUGAM Toos TISTMAY wpoW
syston;
ingsyaten.celiutttons.eneric
wsiPgSyste,eb,I
Page.1skosteack)
Subndt.Teat cline
se
ader.1Amernl "deBeninedl
ett
wasd
Subeicita(mject
ender.tAE *)
Figure3:CodebehindBusinessLogic
1.3.2InlineCoding
InlineCodeisembeddeddirectlywithintheASP.NETpagethathasanextensionof.aspx.
ItpermitsthecodetobecomposedalongwiththeHTMLsourcecodeusinga<Script>
tag.Thatmeansthebusinesslogicandthepresentationlogicarecontainedwithinthe
samefile.Whenthepageisdeployed,thesourcecodeisdeployedalongwiththeWeb
Formspage,becauseitisphysicallyinthe.aspxfile.However,youdonotseethecode,
onlytheresultsarerenderedwhenthepageruns.
ForExample:
Defsult.a
Page Title-"HomePageLanguage-"C#MasterPageFile="~/site.MasterAutoEventwireup="true
CodeBehind-"Default.aspx.cs"
Inherits="WebApp1ication-
nle ofInlineCode
protectedvoidbtnsubmit_click(objectsender,EventArgse)
if(this.txtFirstName.Text.Length=-0)
this.FirstNiameValidation.Text"FirstNoneisrequire!";
12
/script
13asp:ContentID-"BodyContent"ContentPlaceHolderID="HainContent"runat-"server
"
14asp:LabeltD»"Lableone"
Text-"First
Nane
width»"145"runat-"server">«/asp:Label»
TextBoxID="txtFirstName"runat-"server"Text"width="145">x/asp:TextBox>
ebr/»
5
br
casp:ButtonzD-"btnsubmit"runat"server"Text"Submit"onClick"btnSubmit_click"/>
<asp:LabelID="FirstNameValidation"Text=width="145"runat="server"
tyle"color:red;font-weight:5e0;"></asp:Labels
</asp:Content
Figure4:InlineCode

8 Unit-1IntroductiontoASP.NET
1.4TheCommonLanguageRuntime
(CLR}:
Itisthecorecomponentof.NETFramework.ItisalsoknownasanexecutionEnvironment.
Itisusedtocompilethe
ILorMSILcodetonativecode.
FollowingdiagramshowstheworkingprocessofCLR.
C# VB.NETJC
NET
Source
Unmanagod
omponsnt
code
Compiler Compiler Compiler
ManagedAssemblylL AssemblyILAssemblyL
codeCode code
CommonLanguageRuntimeiemple
Nativecode
Operatingsyatem
Figure5:CLRExecutionModel
Themainfunctionof
CLRistoconverttheMSILcodetonativecodeandthenexecutethe
program.Themanagedcodeacodethatisdevelopedwithalanguagecompilerthat
targetsthe
CLRiscompiledonlywhenitisneeded,thatmeansitconvertstheappropriate
instructionswheneachfunctiniscalled.Theunmanagedcode
-acodethaatisdeveloped
withoutconsideringtheconventionsandrequirementsofCLR,isexecutedwithminimal
serviceofCLR.TheCLR'sJIT(Just-inTime)compilationconvertsMSILtonativecodeon
demantatapplicationrun.
Duringtheexecutionoftheprogram,theCLRprovidesfunctionalotysuchasmemory,
Debugging,ExceptionHandling,Securityandversioningsupporttoanylanguagesthat
targetit.
Inshort,When.NETprogramsareexecuted,the
CLRactivatestheJITcompiler.TheJIT
CompilerconvertsMSILintonativecodeondemandbasis.Thustheprogramexecutesasa
nativecodetoruntheprogramfast.ThatishowNETframeworkachievestheportability.
ComponentofCLR:
1.ClassLoader:Itloadstheclassesintothesystemmemoryasandwhenneeded.
2.CodeManager:ThecodemanagerinCLRmanagesthecodedevelopedinthe.NET
framework.Themanagedcodeisconvertedtointermediatelanguagebyalanguage-specific

Unit-1IntroductiontoASP.NET
compilerandthentheintermediatelanguage
(1L)isconvertedintothemachinecodebythe
Just-In-Time
(UIT)
compiler.
DaseCussLibrarySuppet
ThreadSupport couMarshae
TypeCrecker
Exceptinaneger
SecurityEngn DebupEngn
Llo
Nathve
Coce Gatage
Collector
CoroiorsManager
ClassLoader
Figure6:CLRComponent
8.GarbageCollection:LifetimeofanobjectismanagedbyCLRwhichperformsautomatic
memorymanagementusinggarbagecollectorinCLR.Anobjectwhichisnolongerrequired
thensuchobjectsareautomaticallyreleasingthememoryspacewithhelpofgarbage
collector.
i.MSILtoNativeCompilers:ItisusedtocompiletheMSILcodeandconvert
itintonativelanguage.
i.DebugEngine:Anapplicationcanbedebuggedduringtheruntimeusing
debugengine.
ii.SecurityEngine:In.NETarchitecture,securityisachievedwiththehelpof
theCodeAccessSecurity(CAS)mechanismwhichpreventuntrustedcode
fromperformingprivilegedactions.Thatmeans,CLRenforcesrestrictions
onmanagedcodethroughtheuseofobjectcalledpermissions.TheCLR
allowsthecodetoperformonlythosetasksforwhichithaspermission.
iv.ExceptionManager:Duringtheexecutionoftheprogram,ifany
exceptionoccursthenitishandledbyexceptionmanager.
v.TypeChecker:Objectswhichareusedinapplicationarealwaysaccessed
incompatibleways,isensuredbythisfeatureofCLR.
vi.ThreadSupport:Supportformanagingtheparallelexecutionofmultiple
threadisprovidedbyCLR.

10- Unit-1IntroductiontoASP.NEI
vii.COMMarshaller:Itallowscommunicationbetweentheapplicationand
COMObjects.
vii.ClassLibrarySupport:ItprovidesBaseClassLibraryclasseswhen
applicationneedatexecutiontime.
1.5ObjectOrientedConcepts:
ObjectOrientedProgramming(OOP)isaprogrammingmodelwhereprogramsare
organizedaroundobjects,datafieldandmethodswhichinteracttodesignapplications
andcomputerprograms.
1.5.1Class:
Aclassisauser-definedprototypefromwhichobjectsarecreated.
Aclasscontainsfields
&methodsknownasmemberfunctionintosingleunit.
Syntax:
AccessModifier)<Classname>[:BaseClass|Eimplementsinterfacenames]
[Statements
Here,accessmodifiersarePublic,Private,Protectedandinternal.
ForExample:
Publicclassstudent
fields,variables,methods,properties/
1.5.2Fields:
Variablesdeclareinsideaclassarecalledfieldsthatcanbeaccessedbycreatinganobject
oftheclassandbyusingthedotsyntax().
ForExample:
PublicClassstudent
Publicintroll_no=1;
Publicstringname="Yash;
staticvoidMain(stringllargs)

Unit-1IntroductiontoASP.NET
studentmyStudnewstudent()
Console.Writeline{myStud.roll_no);
Console.Writeline(myStud.name);
Anotherway,todeclarefieldsandinitializethemwhilecreatingobjectswhichisvery
usefulwhenmultipleobjectsarecreated.
PublicClassstudent
Publicintroll_no;
Publicstringname;
staticvoidMain(stringllarg)
studentmyStud=newstudent();
myStud.rollno-1;
myStud.name="Yash";
Console.WriteLine(myStud.roll_no;
Console.Writeline(myStud.name);
1.5.3Properties:
Propertiesaresetandretrievedlikefields.Theyaresetofdescriptivedataofanobject
whichareimplementedusingGet&Setprocedureswhichprovidemorecontrolonhow
valuesaresetorreturned.
ForExample:
PublicClassstudent
I
Fields
privateintroll_no;
privatestringname;
properties
publicintRollNo

12 Unit-1Introductlonto
ASP.NET
get
returnroll_no;
Set
roll_no=value;
publicstringStudName
Get
returnname;
Set
name=value;
staticvoidMain(stringlargs)
studentmyStud=newstudent(};
Console.WritelLine(myStud.Roll_Nol;
Console.WriteLine(myStud.StudName);
1.5.4Methods:
Amethodisablockofcodewhichonlyrunswhenitiscalled.Theyareusedtoperform
certainactions,andtheyarealsoknownasfunctionsoftheclass.
ForExample:

Unit-1Introductionto
ASP.NET
13
publicClassstudent
publicintroll_no-1;
publicstringname="Yash
publicvoiddisplay()
Console.Writeline(myStud.rollno);
Console.Writeline(mystud.name);
staticvoidMain(stringl]args)
studentmyStudnewstudent();
myStud.display(l
1.5.5Events:
Eventsallowsobjectstoperformanactionswheneversomespecificactiontakesplace.
Forexample,whenweclickabutton,aclickeventoccursandwecanhandlethatevent
witheventhandler.
1.5.6Objects:
ItisabasicunitofOOPwhichrepresentsrealtimeentity.Theyarecalledinstancesof
classeswhichdefinesthedata&behaviorofalltheinstancesofthattype.
ForExample:
studentmyStud=newstudent()
1.5.7Constructor:
Aconstructorisaspecialmethodusedtoinitializeobjects.Mainadvantageofa
constructoristhatitiscalledwhenanobjectofaclassiscreated.Basically,itisusedto
settheinitialvaluesofthefieldsoftheclass.
ForExample:
publicclassstudent

14
Unit-1IntroductiontoASP.NET
I/fields
publicintroll_no;
publicstringname;
publicstudent()//Constructor
rollno=1;
name="Yash";
staticvoidMain(stringl
args)
studentmyStud=newstudent(};//Thiswillcalltheconstructor
Console.WritelLinefmyStud.rollno;
Console.Writeline(myStud.name);
1.5.8Destructor:
Itisexecutedautomaticallywhenanabjectisdestroyed.TheDestructoriscalledimplicitly
bythe.NETFramework'sGarbagecollectorsothatprogrammerhasnocontrolaswhento
invokethedestructor.
1.5.9Encapsulation:
Wrappingupofdatamember&memberfunctionsintosingleunitiscalledEncapsulation.
Inotherwords,Encapsulationisprotectiveshieldthatpreventsthedatafrombeing
accessedbythecodefromtheoutsideofthatshield.
So,data&membersofaclassarehiddenfromanyotherclasses.Theycanbeaccessed
onlythroughanymemberfunctionorpropertiesofownclassinwhichtheyaredeclared.
ThisconceptiscalledDataHiding.
ForExample:
publicclassstudent
privatestringname;
privateintrollno;

Unit-1IntroductiontoASP.NET
15
/usingpropertytogetandsetthevalueofstudentName
publicstringStudName
get
returnname;
set
name=value;
I/usingpropertytogetandsetthevalueofRolINo
publicintR_No
get
returnroll_no;
set
rollno
=value;
classStudMain
staticvoidMain(string[largs)
students=newstudent();
Icalltosetpropertywithrespectivevaluetosetstandardfield'value'
s.R_No=1;

16 Unit-1IntroductiontoASP.NET
s.StudName="Yash";
/calltogetpropertyvalue
Console.Writeline(s.R_No);
Console.Writeline(s.StudNname);
1.5.10Inheritance:
Itisamechanismbywhichoneclassisallowedtoinheritthemembersofanotherclass.
Thatmeans,Inheritanceistheprocessofforminganewclassfromanexistingclass.
TheclasswhosefeaturesareinheritedisknownasParentclassorSuperclassorBase
class.TheclasswhoisacquiringthemembersofBaseclassisknownasChildclassor
DerivedclassorSubclass.Thesubclasscanadditsownfieldsandmethodsinadditionto
thesuperclassfieldsandmethods.lnheritanceisanimportantconceptofOOPasithelps
inreducingtheoverallcodesizeoftheprogramandsupportreusabilityofcode.To
inherittheclasscolon(:)symbolisused.
Syntax:
classderived-class:base-class
Imethods
andfields
ForExample:
publicclassParentClass
publicParentClass()
Console.Writeline("ParentConstructor.");
publicvoiddisplay()
Console.Writeline("T'maParentClass.");

Unit-1IntroductiontoASP.NET
17
publicclassChildClass:ParentClass
publicChildClass()
Console.Writeline("ChildConstructor.";
publicstaticvoidMain()
ChildClasschild=newChildClass();
child.display0;
1.5.11Abstraction:
Dataabstractionisthepropertybywhichonlyessentialandimportantinformationis
displayedtouserwithoutrepresentingbackgrounddetailswhichincreasetheefficiency.It
focusesonwhattheobjectdoesinsteadofhowitdoesit.Inotherwords,abstraction
providesageneralizedviewofclassesorobjectsbyprovidingrelevantinformation.
AbstractionisachievedwiththehelpofeitherAbstractclassesorinterfaces.The'abstract
keywordisusedforclassesandmethods.
1.5.11.1AbstractClass:
Itissuchaclasswhichcannotbeinstantiated.Thatmeans,itcannotbeusedtocreatean
objectbutitmustbeinheritedfromanotherclass.Abstractclasscanhavebothregular
andabstractmethods.
1.5.11.2AbstractMethod:
Itcanbeusedonlyinabstractclassanditdoesnothavebody.Thatmeansmethodshave
onlydeclarationinabstractclassandderivedclassmusthavetheirdefinition.'Override'
keywordisusedinderivedclasswhiledefiningtheabstractmethod.
ForExample:
abstractclassShape

18 Unit-1IntroductiontoASP.NET
publicabstractintarea();
classSquare:Shape
Ilprivatedatamember
privateintside;
publicSquarelintx=0)
sid
X
publicoverrideintarea()
Console.Write("AreaofSquare:");
return(side
*side);
classProgram
staticvoidMain(stringllargs)
Squares=newSquare(4);
doubleresult=s.area()
Console.Write/"{0",result);
1.5.12Interface:
Aninterfaceissimilartoabstractclasswhichcanonlycontainabstractmethodsand
propertiesbutnotfields.Theycannotbeusedtocreateanobject.Bydefault,membersof
aninterfaceareabstractandpublic.
Similartoabstractclass,allinterfacemethodsmustbeimplementedbytheclasswhichis
implementingit.Nooverridekeywordisrequiredwhileimplementinganinterface.Just
likeaninheritance,interfacescan
beimplementedusingsymbolcolon(:).

Unit-1Introductionto
ASP.NET
ForExample:
interfaceShape
intarea()://interfacemethod(doesnothaveabody)
classSquare
:Shape
publicintside=4;
publicintarea()
Console.Write("AreaofSquare:");
return(sidesidel;
classProgram
staticvoidMain(stringlargs)
SquaresnewSquaref();
doubleresult=s.area();
Console.Write("10",resut);
MultipleinheritanceisnotsupportedbyC#.Soitcanbeachievedusingimplementing
multipleinterfaces.Todoso,separatethemwithcoma().
ForExample:
interfaceinter1
Voidmethod1(};
interfaceinter2

20 Unit-1IntroductiontoASP.NEI
Voidmethod2(};
classDemoClass:interface1,interface2
publicvoidmethod1()
Console.Writeline("FirstInterfaceMethod");
publicvoidmethod2()
Console.WriteLine("SecondInterfaceMethod.");
classProgram
staticvoidMain(stringllargs)
DemoClassmyObj=newDemoClass();
myObj.method1();
myObj.method2();
1.5.13Polymorphism:
Thepolymorphismistheprocessofusinganoperatororfunctionindifferentwaysfor
differentdatainput.Inotherwords,itistheabilitytoredefinemethodsforderived
classes.
Therearebasicallytwotypeofpolymorphism:
1.Compiletimepolymorphism:Itisachievedbymethodoroperatoroverloading.tisalso
knownasstaticbindingorearlybindingasatcompiletimeonlycompilerknowsthatwhat
typeofobjectitisbindingtoandwhatarethemethoditisgoingtocall.
ForExample:
publicclassShape

Unit-1IntroductiontoASP.NET
publicintAreafinta,intb)
returnab;
publicdoubleArealinta,intb,intc)
returna*b*c;
classProgram
staticvoidMain(stringlargs)
ShapesnewShape()
doubleresult=s.Area(4,5);
Console.Write("10}",result);
result=s.Areal4,5,2);
Console.Write("[0}",result);
2.Runtimepolymorphism:Itisachievedbymethodoverriding.Itisalsoknownas
dynamicbindingorlatebinding.Tooverridebaseclassmethods,'virtualkeywordisused
withbaseclassmethodsand'override'keywordisusedwitheachderivedclassmethods
tooverride.
ForExample:
classShape
publicvirtualvoidarea()
Console.write("InShapeclassmethod");

22
Unit-1IntroductiontoASP.NET
classCircle:Shape
publicoverridevoidarea()
Console.Write("InCircleclassmethod");
classTriangle:Shape
publicoverridevoidarea(
Console.Write("lnTriagleclassmethod");
classProgram
staticvoidMain(stringllargs)
Shapesh=newShape(
sh.area();
CirclecnewCirclel);
C.area();
Trianglet
newTriangle();
t.area()
1.6EventDrivenProgramming:
Whensomethingspecifichasoccurredinsignificanceforsystemhardwareorsoftwareis
callanEvent.Inotherwords,Eventisanotificationthatsomethinghasoccurredand
detectedbytheprogram.Asegmentofcodethatisexecutedinresponsetoaneventis
calledaneventhandler.

Unit-1IntroductiontoASP.NET
23
Aneventdrivenprogrammingisaprogrammingapproachinwhichtheflowofthe
programisdeterminedbyaneventlikebuttonclicked,textchangeetc.Thatmeansit
enablesyoutowritecodethatwillexecuteinresponsetoeventsraisedbyparticularuser
action.
ASP.NETworkslikeasfollow:
1.Whenfirsttimepageisexecuted,itwillcreatethepageandthecontrolobjects
alongwiththecodeinitializationisexecutedandpageisprovided.
2.Anyeventcanbetriggeredassomeactionisperformedbytheeuserwhenthe
pageisserved.
3.
IfanyeventgeneratesthepostbackoftheformthanASP.NETrepondsthepage
byrecreatingit.
4Thenitwillraisestheappropriateeventwhichhastriggeredthepostback.
5.Last,modifiedpageisprovidedtoHTMLandservedtotheclient.
1.6.1PageLifeCycle:
WheneveryourequestanASP.NETpage,aparticularsetofeventsisraisedinparticular
sequence.Thissequenceofeventsiscalledthepageexecutionlifecycle.
Code
Behind
Clas
NET Generate
EngineParse
Reques
spx
Generate
Compile
PageClass
Request
2dRequest
nstantiation
nstantiate,
ProcessandResponse
PageClass Provide
Figure7:PageLifeCycle
Whentherequestcomesfromthe.aspxpage,itisgivenforparsingtoasp.netengine.
Thenacombinedpageclassisgeneratedfromthatparsedpageandthecodebehindclass
andthenitiscompiled.Atlast,theinstanceoftheclassiscreatedandprovidedtothe
user.

24
Unit-1IntroductiontoASP.NET
1.6.1.1PageLifeCycleStages:
i.PageRequest
Thisiswhenthepageisfirstrequestedfromtheserver.Whenthepageisrequested,
theserverchecksifitisrequestedforthefirsttime.
Ifso,thenitneedstocompile
thepage,parsetheresponseandsenditacrosstotheuser.Ifitisnotthefirsttime
thepageisrequested,thecacheischeckedtoseeifthepageoutputexists.
Ifso,
thatresponseissenttotheuser.
ii.Start
Inthisphase,2objects,knownastheRequestandResponseobjectareset.
Ifthe
requestisanoldrequestorpostback,theIsPostBackpropertyofthepageissetto
true.TheUICulturepropertyofthepageisalsoset.
ilil.PageInitialization
Inthisphase,controlsonthepageareavailableandeachcontrol'sUniquelD
propertyisset.Amasterpageandthemesarealsoappliedtothepageifapplicable.
Ifthecurrentrequestisapostback,thepostbackdatahasnotbeenloadedand
controlpropertyvalueshavenotbeenrestoredtothevaluesfromviewstate.
iv.Load
Duringthisphase,ifthecurrentrequestisapostback,controlpropertiesaresetto
utilizetheviewstateandcontrolstatevalueslikeifatextboxissupposedtohavea
defaultvalue,thatvalueisloadedduringthepageloadtime.
v.Validation
Inthisphase,whenthevalidationcontrolsarepresentonthepage,thanonits
successfulexecution,IsValidpropertyofthepageissettotrue.
vi.PosthackEventHandling
Inthisphase,controleventhandlersarecalled
iftherequestisapostback.That
meansthiseventistriggeredifthesamepageisbeingloadedagain.Thishappensin
responsetoanearlierevent.Sometimestherecanbeasituationthatauserclickson
asubmitbuttononthepage.Inthiscase,
thesamepageisdisplayedagain.Insucha
case,thePostbackeventhandleriscalled.
vii.Rendering

Unit-1Introductionto
ASP.NET
Beforethisphase,viewstateissavedforthepageandallcontrols.Duringthisstage,
thepagecallstheRender()methodforeachcontrolandwritesitsoutputtothe
OutputStreamobjectofthepage'sResponseproperty.
vili.Unload
Theunloadmethodtakesafterthepageisfullyloadedandisreadytoterminate.At
thispoint,renderedpageissenttotheclientandpagepropertiessuchasResponse
andRequestareunloadedandclean-upisdone.
1.6.1.2PageEvents:
Followingisthesequenceofeventsraisedwheneveryourequestapage:
i.Prelnit
Itisthefirsteventinthepagelifecycle.ItcheckstheIsPostbackpropertyand
determineswhetherthepageisapostback.Thisistheonlyeventwhereprogrammatic
accesstomasterpagesandthemesisallowed.Youcandynamicallysetthevaluesof
masterpagesandthemesinthisevent.Youcanalsocreatecontrolsdynamicallyinthis
event.
.
Init
Thiseventfiresaftereachcontrolhasbeeninitialized,eachcontrol'sUniqueIDisset.You
canusethiseventtoreadandinitializevalueforthecontrols.Thiseventisfiredfirstfor
thebottom-mostcontrolinthehierarchy,andthenfiredupthehierarchyuntilitisfired
forthepageitself.
ii.InitComplete
Thiseventallowstrackingofviewstate.Allthecontrolsturnonview-statetracking
iv.PreLoad
ThePreLoadeventisusedforperformingthepageprocessingonthepagebeforethe
controlisloaded.Wecanprocessanykindofoperationthatneedstoperformbefore
pageload.
v.Load
Thisisthefirstplaceinthepagelifecyclethatallvaluesarerestored.ThePageobjectcalls
theOnLoadmethodandthenrecursivelydoesthesameforeachchildcontroluntilthe
pageandallcontrolsareloaded.TheLoadeventofindividualcontrolsoccursafterthe

26 Unit-1IntroductiontoASP.NET
Loadeventofthepage.Thiseventisusetosetthepropertiesofthecontrolsanditcan
alsobeusedtoestablishdatabaseconnection.
vi.ControlEvents
Theseeventsareusedtohandlespecificcontrolevents,suchasaButtoncontrol'sClick
event.
vii.PreRender
Thiseventoccursjustbeforetheoutputisprovided.Byhandlingthisevent,pagesand
controlscanperformanyupdatesbeforetheoutputisprovided.
vii.PreRenderComplete
AsthePreRendereventisrecursivelyfiredforallchildcontrols,thiseventensuresthe
completionofthepre-renderingphase.
ix.SaveStateComplete
Inthisevent,stateofcontrolonthepageissaved.Personalization,controlstateandview
stateinformationissaved.
x.Unload
Thisisthelastphaseofthepagelifecycle.ItraisestheUnLoadeventforallthecontrols
recursivelyandforthepageitself.Itisusefulforfinalcleanupsuchasclosingdatabase
connectionoranyotherrequestedspecifictasks.

Unit-1IntroductiontoASP.NET
27
Questions:
Q-1.Explain.NETFramework2.0
Q-2.WhatisCompileCode?Listoutitsbenefits.
Q-3.WhatisthedifferencebetweenCodeBehindandInlineCoding?
Q-4.ExplainCLRindetail.
Q-5.ExplainObjectOrientedConcepts.
Q.6ExplainASP.NETPageLifeCycle.
Tags