Tải bản đầy đủ (.pdf) (1,292 trang)

Addison wesley c sharp developers guide to ASP dot NET XML and ADO dot NET mar 2002 ISBN 0672321556

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.8 MB, 1,292 trang )

C#®Developer'sGuidetoASP.NET,XML,
andADO.NET
By
JeffreyP.McManus,ChrisKinsman

Publisher

:AddisonWesley

PubDate

:March29,2002

ISBN

:0-672-32155-6

Pages

:608

Slots

:1


Copyright
AbouttheAuthors
AbouttheContributor
AbouttheTechnicalEditor
Acknowledgments


Chapter1.
Introduction:TheNeedforASP.NET
ProblemswithASPToday
IntroducingASP.NET
Chapter2.
PageFramework
ASP.NET'sControlModel
SeparatingPresentationfromCodeUsingCodeBehind
ProgrammingHTMLControls
AttributesofthePageObject
CreatingUserInterfaceswithWebControls
ServerControlsandPageObjectReference
Chapter3.
DebuggingASP.NETApplications




TracingYourWebApplication'sActivity
DebuggingASP.NETApplications
CreatingCustomPerformanceMonitors
WritingtotheWindowsEventLog
Reference
Chapter4.
StateManagementandCaching
StateManagement:What'stheBigDeal?
Caching
ClassReference
Chapter5.
ConfigurationandDeployment

UnderstandingConfigurationFiles
GlobalandLocalConfigurationFiles
StructureofConfigurationFiles
AccessingConfigurationFilesProgrammatically
EditingWebConfigurationFilesinVisualStudio.NET
InitializingWebApplicationsUsingGlobal.asax
UsingXCOPYforDeployment
ManagingtheGlobalAssemblyCache
Chapter6.
WebServices
HistoricalInfluences
NetworkDataRepresentation
WhatIsaWebService?
WhyWebServices?
ASP.NETWebServices
ConsumingWebServices
ClassReference
Chapter7.
Security
IdentityandPrincipal
WindowsAuthentication
FormsAuthentication
PassportAuthentication
FileAuthorization
URLAuthorization
CustomRoleswithFormsAuthentication
PullingItAllTogether
Impersonation



ClassReference
Chapter8.
HttpHandlersandHttpModules
AnOverviewofASP.NETRequestHandling
HttpModules
HttpHandlers
DynamicHandlerAssignment
ClassReference
Chapter9.
BuildingUserControlsandServerControls
WorkingwithUserControlsinWebFormsApplications
CreatingServerControls
Chapter10.
UsingXML
WhatIsXML?
AccessingXMLDataUsing.NETFrameworkClasses
DefiningandValidatingXMLwithSchemas
ProcessingXMLDocumentsUsingStyleSheets
ClassReference
Chapter11.
CreatingDatabaseApplicationswithADO.NET
WhyaNewObjectLibraryforDataAccess?
NewFeaturesinADO.NET
ConnectingtoaDatabase
RunningQueries
UsingDataAdapterstoRetrieveandManipulateData
CreatingWebFormsforDataEntry
HandlingErrors
ADO.NETFrameworkReference
Index



C#®Developer'sGuidetoASP.NET,XML,
andADO.NET
By
JeffreyP.McManus,ChrisKinsman

Publisher

:AddisonWesley

PubDate

:March29,2002

ISBN

:0-672-32155-6

Pages

:608

Slots

:1

ThebookeveryInternetapplicationdeveloperworkingwithMicrosoftdevelopmenttoolsneedsto
retooltheirknowledgeofthenew.NETtechniquesusedtobuildWindowsapplications.
Unbiased,in-depthcommentaryontheefficacyofthevarioustechnologiesthatcomprise

.NETastheypertaintoInternetdatabasedevelopers.
Technicalknow-howwithoutcrushingthereaderwithpointlessdetail.
ImplementationdetailsthatreplaceandextendtheexistingActiveServerPages(ASP),
XML,andActiveXDataObject(ADO)functionalitycurrentlysupportedbyMicrosoft.
Topicscoveredinthisbookinclude:the.NETFoundationClassesthataremostusedby
developers--ASP.NET,XML,andADO.NET,anddetailsabouttheconstructionofWebServices
andhowtheyprogrammaticallycommunicatewitheachother.




Copyright
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsare
claimedastrademarks.Wherethosedesignationsappearinthisbook,andAddison-Wesleywere
awareofatrademarkclaim,thedesignationshavebeenprintedininitialcapitallettersorinall
capitals.
Theauthorandpublisherhavetakencareinthepreparationofthisbook,butmakenoexpressed
orimpliedwarrantyofanykindandassumenoresponsibilityforerrorsoromissions.Noliabilityis
assumedforincidentalorconsequentialdamagesinconnectionwithorarisingoutoftheuseof
theinformationorprogramscontainedherein.
Thepublisheroffersdiscountsonthisbookwhenorderedinquantityforspecialsales.
Formoreinformation,pleasecontact:
PearsonEducationCorporateSalesDivision201W.103rdStreet
Indianapolis,IN46290
(800)428-5331

VisitAWontheWeb:www.awl.com/cseng/
Copyright©2002byPearsonEducation
Allrightsreserved.Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,or
transmitted,inanyformorbyanymeans,electronic,mechanical,photocopying,recording,or

otherwise,withoutthepriorconsentofthepublisher.PrintedintheUnitedStatesofAmerica.
PublishedsimultaneouslyinCanada.
05040302DOC4321
FirstprintingApril2002
Credits


AssociatePublisherLindaEngelman


AcquisitionsEditorSondraScott




DevelopmentEditorsAngelaAllen
LaurieMcGuire


ManagingEditorCharlotteClapp
ProjectEditorCarolBowers


CopyEditor
BarbaraHacha


Indexer
TimTate



Proofreader
JessicaMcCarty
Contributor
AnjaniChittajallu
TechnicalEditorJoelMueller


TeamCoordinatorLynneWilliams


MediaDeveloperDanScherf


InteriorDesignerGaryAdair



CoverDesignerGaryAdair


PageLayout
AyannaLacey
Dedication
ForCeleste
JeffreyP.McManusThisbookisdedicatedtomydad,whosupportedandencouragedmein
everythingIdid.
ChrisKinsman



AbouttheAuthors
JeffreyP.McManusisadeveloperandspeakerspecializinginMicrosofttools.Asadeveloper,
hehasspecializedinonlineapplicationdevelopmentusingInternetandclient/server
technologies.Heistheauthoroffourbooksondatabaseandcomponenttechnologies,including
thebestsellingDatabaseAccesswithVisualBasic6(SamsPublishing).Jeffreyregularlyspeaks
attheVBITS/VSLive,EuropeanDevWeek,andVBConnectionsconferences.
ChrisKinsmanisadeveloperandspeakerspecializinginMicrosofttools.Asadeveloper,hehas
beenresponsibleforseveralhigh-trafficsitesbasedentirelyonMicrosofttools,includingserving
asVicePresidentofTechnologyatDevX.com.Inaddition,Chrisspent10yearsconsultingwith
Fortune500companiesthroughouttheworldtosolvetheirneedsbyutilizingavarietyofMicrosoft
VisualStudioandBackOfficetechnologies.ChrisregularlyspeaksattheVBITS/VSLive,Web
Builder,andSQL2TheMaxconferences.


AbouttheContributor
AnjaniChittajalluobtainedamastersdegreefromIndianInstituteofTechnology(I.I.T-Madras)
withamajorinControlSystemsEngineering.Shespecializesindesigninganddeveloping
enterprisesystemswithMicrosoftTechnology.AnjanicurrentlyholdsMCSDcertification.Shecan
bereachedat


AbouttheTechnicalEditor
JoelMuellerisaseniorsoftwareengineeratDeLaniTechnologies(www.delani.com),aleading
Webdevelopmentsoftwarecompany,wherehehasbeenspearheadingthecompany'sMicrosoft
.NETdevelopmenteffortsinceJuly2000.PriortotheadventofASP.NET,Joeldidextensivework
withMicrosoftActiveServerPagesandMacromediaColdFusion.Hehaswrittenforseveralbooks
andarticlesonthetopicsofMacromediaColdFusionandXML.Joel'scurrentinterestsincludethe
.NETframework,C#,andsleeping.



Acknowledgments
JeffreyandChriswouldliketoextendaspecialthankyoutoAnjaniChittajallu,whocamethrough
inapinchanddidabang-upjobworkingonthecodeexamplesforthiseditionofthebook.We're
gratefultoyouforyourhelp!


Chapter1.Introduction:TheNeedforASP.NET
INTHISCHAPTER
ProblemswithASPToday
IntroducingASP.NET
BeforedelvingintotheparticularsofdevelopingwithC#,itwillbeusefultooverviewASP.NET.
ThischaptersummarizesASP.NET'sfeatures,includingsomeinsightintohowtheyrepresent
improvementsoverASP.old.


ProblemswithASPToday
WhenActiveServerPages(ASP)wasfirstintroducedalmostfiveyearsago,itwasseenasan
answertotheawkwardtechniquesusedatthattimeforcreatingdynamiccontentontheWeb.At
thetimeCommonGatewayInterfaceprogramsorproprietaryserverplug-inswerethewaythat
mostoftheWeb'sdynamiccontentwascreated.WiththereleaseofASP1.0,Microsoftchanged
allthat.ASP1.0providedaflexiblerobustscriptingarchitecturethatenableddeveloperstorapidly
createdynamicWebapplications.DeveloperscouldwriteinVBScriptorJScriptandMicrosoft
providedanumberofservicestomakedevelopmenteasy.Atthetime,itwasjustwhatdevelopers
needed.AsWebdevelopmentmaturedseveralshortcomingsoftheplatformbecameevident,and
persistuntiltoday.
SeparationofCodeandDesign
AstheWebgrewinpopularityintheearly90s,developersexperiencedthreedistinctwavesof
developmentparadigms.Inthefirstwave,WebdeveloperscreatedstaticHTMLdocumentsand
linkedthemtogether.Thiswastheeraofthe"brochure"Websiteandwasmoreaboutlooksthan
anythingelse.Thesecondwavebroughttheconceptofdynamiccontenttothefore.Developers

startedcreatingregistrationformsandvarioussmallpiecesoffunctionalityandaddingtheminto
existingWebsites.Thethirdwavewaswhenthefirstandsecondwavescametogether.Web
siteswerebeingdesignedfromthegrounduptobeinteractive;theyweretreatedmorelikean
applicationandlesslikeamagazinewithasubscriptioncardinit.Inmostinstancesthistypeof
interactivepagedesigncreatedadevelopmentparadigmthatwentlikeso:
DesignerscreatedpagemockupsinHTML.
Developersaddedcodetothepages.
Whendesignersneededtochangetheirdesign,theycopiedandpastedtheexistingcode
intothenewpage,butcheringitanddestroyingitsfunctionality.
Theseverityofthisproblemtypicallydependedonthesizeofthesite,thesmartsofthe
designers,andthetechniquesthatdevelopersusedtoguardagainstthismangling.
WiththereleaseofVisualStudio6inSeptember1998,itwasclearthatMicrosoftrecognizedthis
burgeoningproblemandattemptedtoresolveitwithanewfeatureinVisualBasic6,Web
Classes.WebClassesmadeanattempttoseparatethedesignofapagefromthecodethat
interactedwithit.ItenabledthisseparationbyusinganHTMLtemplateandprovidingafacilityfor
doingtagreplacementinthetemplate.TherewereanumberofproblemswithWebClasses.
Althoughagreatidea,theysufferedfromtwomainissues.First,theWebClasseswere
implementedentirelyinVisualBasic,whichrequiredtraditionalASPdeveloperstoshifttheir
thinkingpatternsforcreatingapplications.Second,Microsofthadscalabilityissuesrelatedtothe
threadingmodelsofASPandVisualBasic.Becauseofthepreviouslystatedreasonsandmany
othersmallerones,WebClassesneverreallygainedanytractionamongdevelopers.
ScriptingLanguageBased


WhenASP1.0wasfirstreleased,thefactthatalldevelopmentwasdoneusingscripting
languageswasabigplus.Itmeantthatdevelopersdidn'thavetogothroughapainful
restart/compileprocessthattheymighthavebeenaccustomedtowithCGIorISAPIstyle
applications.Asapplicationsgrewlarger,numbersofusersincreasedanddeveloperswereusing
ASPforincreasinglydifficultproblems.Thefactthatallcodewasinterpretedbecameapotential
performancebottleneck.WhenusingVBScripttherewaslimitedsupportforerrorhandling.Many

developerssidesteppedthisissuebymovingcodeintocompiledCOMobjects.Whilethismove
solvedsomeoftheperformanceproblemsitcreatednewonesindeploymentandscalability.
StateManagement
OneofthemostfrustratingaspectsthatnewWebdevelopersfacedearlywasdealingwiththe
statelessnatureofWebdevelopment.WithASP1.0,Microsoftintroducedtheconceptofa
Sessionobject,whichwasdesignedtomakeassociatingstatewithaparticularusereasy.This
additionwasarguablyoneofthemostcompellingfeaturesofASP1.0.Scalabilityandreliability
startedtobecomeimportantasdevelopersbegancreatinglargerapplications.Toaddressthis
need,developersstarteddeployingtheirapplicationstoWebfarms.Webfarmsusemultiple
serversandspreadtherequestforpagesacrossthemsomewhatequally.Thismakesforagreat
scalabilitystory…unlessthedeveloperisusingthatcoolSessionobject.Thisobjectisspecificto
aparticularmachineinaWebfarmandwillnotworkifausergetsbouncedtoanotherserver.So,
anapplicationthatwasdeployedtoaWebfarmcouldnotusetheSessionobject.


IntroducingASP.NET
ASP.NETisMicrosoft'sanswertotheaforementionedproblemsandmanyothersthatwerenot
explicitlystated.ItisafundamentalrewriteofASPthathasbeeninprocessformorethantwo
years.TheASPteamtookacloselookattheproblemsfacingWebdevelopersandcreateda
brandnewplatforminthespiritoftraditionalASPtosolvethoseproblems.HavingusedASP.NET
foraconsiderableamountoftime,wecanconclusivelysaytheyhitahomerunwiththisrelease.
PlatformArchitecture
ASP.oldwasanInternetServerApplicationProgrammingInterface(ISAPI)filterthatwaswritten
specificallytointeractwithInternetInformationServer(IIS).Itwasmonolithicinnatureandrelied
verylittleonexternalservices.
NOTE
Note:IntheIIS5.0timeframe,ASPdiduseMicrosoftTransactionServer(MTS)as
anexternalservice.

ASP.NETisstillanISAPIfilter.However,unlikeASP.old,ASP.NETreliesonalargenumberof

"external"services—the.NETframework.ASP.NETandthe.NETframeworkaresotightly
coupledthatitisdifficulttoconsiderthe.NETframeworkasanexternalservice.However,sinceit
isaccessiblefromapplicationsoutsidethescopeofASP.NET,itshouldbeconsideredan
"external"service.Asitturnsout,thisisahugewinfortheASP.NETdeveloper.Nolongermust
thedeveloperwriteeverythingfromscratch.Instead,the.NETframeworkprovidesalargelibrary
ofprewrittenfunctionality.
The.NETframeworkredistributableconsistsofthreemainparts:theCommonLanguage
Runtime,the.NETframeworkbaseclasses,andASP.NET.
CommonLanguageRuntime
TheCommonLanguageRuntime(CLR)istheexecutionenginefor.NETframeworkapplications.
However,despitethecommonmisconception,itisnotaninterpreter..NETapplicationsarefully
compiledapplicationsthatusetheCLRtoprovideanumberofservicesatexecution.These
servicesinclude:
Codemanagement(loadingandexecution)
Applicationmemoryisolation
Verificationoftypesafety
ConversionofILtonativecode


Accesstometadata
Garbagecollection
Enforcementofcodeaccesssecurity
Exceptionhandling
Interoperability
Automationofobjectlayout
Supportfordebuggingandprofiling
TheCLRisaplatformthatabstractsfunctionalityfromtheoperatingsystem.Inthissense,code
writtentotargettheCLRis"platformindependent"providedthatthereisanimplementationofthe
CLRonthedestinationplatform.
ManagedExecution

TheCLRisn'tjustalibraryorframeworkoffunctionsthatanexecutingprogramcancallupon.It
interactswithrunningcodeonanumberoflevels.TheloaderprovidedbytheCLRperforms
validation,securitychecks,andanumberofothertaskseachtimeapieceofcodeisloaded.
MemoryallocationandaccessarealsocontrolledbytheCLR.Whenyouhearabout"Managed
Execution,"thisiswhatfolksarespeakingabout:theinteractionbetweentheCLRandthe
executingcodetoproducereliableapplications.
Cross-LanguageInteroperability
OneofthemostfrustratingthingswithcurrentCOM-orAPI-baseddevelopmentpracticesarethat
interfacesareusuallywrittenwithaparticularlanguageconsumerinmind.Whenwritinga
componenttobeconsumedbyaVisualBasicprogram,adeveloperwilltypicallycreatethe
interfacesinadifferentfashionthanifthecomponentwereintendedtobeconsumedbyaC++
program.Thismeansthattoreachbothaudiences,thedevelopermusteitherusealeast
commondenominatorapproachtodevelopingtheinterfaceormustdevelopaninterfaceforeach
consumer.Thisisclearlynotthemostproductivewaytowritecomponents.Asecondproblem
thatmostdevelopersmerelyacceptasnormaltodayisthatmostcomponentsneedtobewritten
inasinglelanguage.IfyoucreateacomponentinC++thatexposesanemployeeobject,you
can'ttheninheritfromthatobjectinVisualBasictocreateaDeveloperobject.Thismeansthat
typicallyasinglelanguageischosenformostdevelopmentprojectstoenablereuse.
.NETchangesallthis.Cross-languageinteroperabilitywasbuiltinfromthestart.All.NET
languagesmustadheretotheCommonLanguageSpecification(CLS)thatspecifiesthebase
leveloffunctionalitythateachlanguagemustimplementtoplaywellwithothers.TheCLSis
writteninsuchawaythateachlanguagecankeepitsuniqueflavorbutstilloperatecorrectlywith
otherlanguageswithintheCLR.TheCLSincludesanumberofdatatypesthatallconforming


languagesmustsupport.Thisrestrictionworkstoeliminateacommonproblemfordevelopers:
creatinganinterfacethatutilizesdatatypesthatanotherlanguagedoesn'tsupport.Italso
supportsbothBinaryaswellasSourcecodeinheritance,enablingthedevelopertocreatean
EmployeeobjectinC#andinheritfromitinVisualBasic.
Whatthismeanstoyouasadeveloperisthatcodereusehasbecomemuchsimpler.Aslongas

thecodewaswrittenfor.NET,youdon'tneedtoworrywhatlanguageitwaswrittenin.Infact,the
choiceoflanguagebecomesmoreofalifestylechoiceinsteadofacapabilitychoice.All
languagesin.NETaretheoreticallycreatedequal,soyougainnoperformanceorfunctionality
benefitbyusingVisualBasicinsteadofC#.Usethelanguageinwhichyouarethemost
productive.
NewFeaturesinASP.NET
UptothispointallthefeaturesmentionedaregainedduetothehostingofASP.NETontopofthe
.NETframework.However,thesefeaturesarejustthetipoftheiceberg.AsImentioned
previously,ASP.NETisatotalrewrite,withsignificantfeaturesasidefromtheintrinsic.NETones.
WearegoingtogiveyouanoverviewofthenewfeaturesinASP.NETwhileshowinghowthese
featuresaddresstheproblemsofseparationofcodeanddesign,scriptinglanguages,andstate
management.
WebForms
WebformsareMicrosoft'sattempttosolvetheproblemoftheseparationofcodeanddesign.
ASP.NETnowoffersacode-behindmodelreminiscentoftheformsdesignerinVisualBasic.This
meansthatyoucannowplaceyourcodeinaseparatefileandstillinteractwiththepage.This
separationisdonebyprovidinganewevent-drivenmodelontopofpageexecution,aswellas
providinganobjectmodelontopoftheHTMLinthepage.Insteadofatop-to-bottomlinear
executionmodel,eventsareraisedduringtheexecutionofapage.Yourcodesinksthoseevents
andrespondstothembyinteractingwiththeobjectmodelthatsitsontopoftheHTML.
ThisquiteneatlysolvestheissueofdesignersmodifyingtheHTMLandbreakingcode.
Inadditiontothenewexecutionmodel,Microsofthasalsocreatedanewserver-sidecontrol
model.UnlikethelameDesignTimeControlsinVisualInterdev,thesenewmodelsareincredibly
usefulencapsulationsofcommondisplayparadigms.Theydonotintroduceanybrowser
dependenciesandtheyrunontheserver,nottheclient.Inthefewcaseswheretheyemit
browser-dependentcode,theysniffthebrowseranddegradegracefully.MoreinformationonWeb
formscanbefoundinChapter2,"PageFramework."
WebServices
AswemovebeyondthefirstandsecondgenerationsofWebapplications,ithasbecome
apparentthattheparadigmoftheWebcanbeextendedtosolveproblemsthatpredateit.Inthe

past,businessesexchangedinformationusingElectronicDataInterchange(EDI)overValue
AddedNetworks(VANs).Thisworkedwellenough,butthecostofgainingaccesstoaVANas


wellasthecomplexityofimplementingvariousindustry-specificEDIprotocolsexcludedallbutthe
largestcompaniesfromparticipatingintheexchangeofinformation.
WebservicesareawaytotransferthesametypesofinformationovertheInternet(insteadof
expensiveVANs)usingindustry-standardprotocolssuchasHTTP,XML,andTCP/IP.Web
servicesarenowsoeasytocreatein.NETthatindividualsorbusinessesofanysizeshouldbe
abletoplayinthisspace.Webservicesaren'tlimitedtoreplacingtraditionalEDIprotocols.They
openupmanyopportunitiesthatEDIhasnevermadeinroadsinto.JumpaheadtoChapter6,
"WebServices,"formoreinformation.
DataAccess
WhenASP1.0firstshipped,thedataaccessstoryatMicrosoftwasinastateofflux.Atthetime,
RemoteDataObjects(RDO)wasthetechnologyofchoiceforVisualBasicdevelopers.ActiveX
DataObjects(ADO)wasintroducedwiththeshipmentofVisualBasic5.0inFebruary1997.It
wasintendedtobeanewdataaccessmodelforalltypesofdataandwaspairedwithanother
newtechnology,OLEDB.
WhileADOwasgreatforwhatitwasdesignedfor—connecteddataaccess—itfellshortinthe
disconnectedarena.Featureswereaddedinsuccessiveversionstoallowittoworkina
disconnectedfashion.ADO1.0hadnosupportforXML.ADO1.0couldnotpredictthesuccessof
XMLasadatadescriptionlanguagewhenitwasshipped,andXMLsupportwascobbledonto
laterversions.Neitherofthesefeaturesweredesignedinfromthebeginning.
ADO.NETisanewdataaccesstechnologytakingadvantageofallthethingsMicrosoftlearned
withADO,RDO,OLEDB,ODBC,andotherprecedingdataaccessimplementations.Itwas
designedfromthebeginningtobecoupledverytightlytoXMLandworkeffectivelyina
disconnectedfashion.FormoreinformationseeChapter11,"CreatingDatabaseApplicationswith
ADO.NET."
Deployment
OneoftheperennialargumentsamongASPdeveloperswashowmuchcodetomigrateintoCOM

objects.SomewritersadvocatedallcodelivinginCOMobjectsandASPshouldonlycontaina
single-methodcalltoinvoketheCOMobject.Whilethismighthavebeengreatintheory,it
eliminatedoneofthebiggeststrengthsofASP:thecapabilitytorapidlycreateanapplicationand
makechangeson-the-fly.WithallthelogicandHTMLtiedupinCOMobjects,asimpleHTMLtag
changemeantrecompilingandredeployingtheCOMobjects.Thebiggestprobleminourminds
lieswithusingthisapproach.COMobjectsareDynamicLinkLibraries(DLL)thataredynamically
loadedbyIIS.Whileloadedtheycannotbereplaced.TodeployaCOMobjectthedeveloper
neededtoshutdownIIS,shutdowntheMTSpackagestheCOMobjectlivedin,replaceit,and
thenrestartIIS.Thissummaryisactuallyasimplificationoftheprocess,butyoucanseethe
problemsthistechniquebringstothefore.Eachtimeanewversionisdeployed,theWebserver
mustgodown!ThedowntimethistechniquecausescanbehandledbycreatingWebfarmsand
doingrollingupgrades;however,inalargeWebfarmthismeansasimplechangecantake
literallyhourstodeployasthenewobjectsarerolledout.


Withthecode-behindmodelinherentinASP.NET,thissituationcouldhavebeenexacerbated.
Instead,Microsoftvastlysimplifiedthedeploymentmodel.Comp-onents,nowcalledassemblies,
nolongerrequireregistrationonamachinefordeployment.Assembliesarethe.NETequivalent
ofaCOMobject.Theyareselfdescribingandcontainamanifestwhichcontainsmetadataabout
theassembly.Themetadataincludesthingsliketheversion,theassembliesitdependson,and
potentially,itssecurityidentity.
Deploymentisaseasyascopyingtheassembliesintoa/bindirectoryintheapplicationroot.
ASP.NETwillnoticethatanewversionhasbeencopiedoverandunloadtheoldversionandload
thenewversion!DeploymentbecomesassimpleasanXCOPY/SorarecursiveFTPtoupload
thenewfilestotheWebserver.FormoreinformationseeChapter5,"Configurationand
Deployment."
Configuration
Inthepast,allconfigurationinformationforASPwasstoredaspartoftheIISmetabase.Thiswas
abinaryfileanalogoustotheregistrythatheldallsettingsforIISandASP.Theonlywaystoeffect
changesweretousetheInternetServicesManagerortowritescriptsthatutilizedtheActive

DirectoryServicesInterfaces(ADSI)toautomatethechanges.Thisprocessmadeitverydifficult
tosynchronizethesettingsofmultipleserversinaWebfarm.
ASP.NETintroducesanewparadigmforallsettings.Insteadofbeingstoredintheopaque
metabase,theyarenowstoredasahierarchicalsetofXMLconfigurationfiles.Thesefileslivein
theapplicationrootandsubdirectories.So,nowasadeveloperusesXCOPYtodeploysource
files,thesettingsarealsodeployed!Noneedtowriteabunchofconfigurationscriptsanymore.
FormoreinformationseeChapter5.
StateManagement
StatemanagementhasbeenvastlyimprovedinASP.NET.Now,threeoptionsexistfor
maintainingstateontheserver.TheclassicASP3.0methodofin-memorystateonasingle
serverstillexists.Inaddition,anout-of-processstateserverandadurablestateoptionisstoredin
SQLServer.
TheotherlimitationofstateservicesinASP.oldwastherelianceoncookiesforconnectingauser
backuptotheirstate.ASP.NETintroducesanewoptionforcookielessstatethatperformsURL
mungingtoconnectausertostateinformation.FormoreinformationseeChapter4,"State
ManagementandCaching."
Caching
ThereasonmostdevelopersuseASPistolendadynamicnaturetotheWeb.Thiscouldmean
accessingbackenddatabasesfordataorperhapspullingitinfromnontraditionalbackends.The
problemwiththisdynamiccontentisthatwhileonecaneasilyscaletheWebtierusingascale-out
methodologyofmultipleWebservers,thisscalingisnotaseasilydoneinthedatatier.Scale-out
approachesfordatabasesarejustbeginningtoappear.Untiltheseapproachesareperfected,


howcanWebdevelopersscaleapplications?
Fordatathatchangesinfrequently,cachingisagreatsolution.ASP.NETofferstwoformsof
caching.Outputcachingtakesanentirepageandstorestheexecutedresultsinmemoryforlater
delivery.Datacachingtakesitemsthatwereexpensivetocreate,suchasDataSets,andcaches
themontheserverside.FormoreinformationseeChapter4.
Debugging

DebuggingASPapplicationshasalwaysbeendifficult.Whileremotedebuggingsolutionswere
offeredinpreviousversionsofVisualStudio,preciousfewdeveloperswereabletogetthemto
workconsistently.Consequently,mostdebuggingconsistedofResponse.Writestatementslittered
throughoutcodeorsometypeofloggingmechanismthatthedevelopercreated.
ASP.NETnotonlyimprovesremotedebuggingandmakesitconsistent,italsooffersanewTrace
facilitythatisgreatforhandlingthetypesofthingsthatloggingorResponse.Writewereusedfor
inthepast.FormoreinformationseeChapter3,"DebuggingASP.NETApplications."
Availability
AnybodythatcurrentlyhasasiteontheWebknowsthatavailabilityiskey.Ifyoursiteisdown,a
visitorcanturntoamillionothers.Problemis,theymightnotcomeback!
ASP.NEThasintroducedanumberofprocesscontrolsthatareaimeddirectlyatimproving
availability.NowtheASP.NETprocesscanrestartautomaticallybasedonthingssuchasmemory
utilization,timeup,orevennumberofrequestshandled,whichhelpscopewithsituationswhere
ASPusedtogetjammedup.FormoreinformationseeChapter5.


Chapter2.PageFramework
INTHISCHAPTER
ASP.NET'sControlModel
SeparatingPresentationfromCodeUsingCodeBehind
ProgrammingHTMLControls
AttributesofthePageObject
CreatingUserInterfaceswithWebControls
ServerControlsandPageObjectReference
ProgramminganASP.NETapplicationissignificantlydifferentthanprogramminginASP.old.The
differencecanbelikenedtothechangethatoccurredwhenmovingfromQuickBasic
programmingtoVisualBasicprogramming.
ThechangesinASP.NETcanbebrokendownintothreecategories:thecontrolmodel,theevent
model,andtheseparationofcodefrompresentation.



<html>
<head>
<title>SimplePage.asp</title></head>

<body>
<formname="WebForm1"method="post">


<tableborder=0><aname="idd1e3159"></a><aname="idd1e3166"></a>name="idd1e3173"></a><tr>
<td>Name:</td>
<td><inputtype=textname=txtName></td><td>name=Button1Value="Send"></td></tr>
<tr>
<tdvalign=top>Hobby:</td><td>
<selectname=lbHobbiesMultiple><optionValue="Ski">Ski</option>
<optionValue="Bike">Bike</option><optionValue="Swim">Swim</option>
</select>
</td>
<td> </td>
</tr>
</table>


</form>


</body><aname="idd1e3177"></a><aname="idd1e3184"></a>name="idd1e3191"></a></html>
<html>
<head>
<title>SimplePage2.asp</title><aname="idd1e3271"></a>

name="idd1e3278"></a><aname="idd1e3285"></a><aname="idd1e3292">
</a><aname="idd1e3295"></a></head>

<SCRIPTLANGUAGE="VBScript"RUNAT=SERVER>
functionIsOptionSelected(strControlName,strOption)foriCount=1to
Request(strControlName).Countifrequest(strControlName)(iCount)=strOption
thenresponse.write"SELECTED"
endif
next
endfunction

</SCRIPT>

<body>
<formname="WebForm1"method="post">


<tableborder=0>
<tr>
<td>Name:</td>


<td>%>"></td>
<td><inputtype=submitname=Button1Value="Send"></td></tr>
<tr>
<tdvalign=top>Hobby:</td><aname="idd1e3301"></a>name="idd1e3308"></a><aname="idd1e3315"></a><td>
<selectname=lbHobbiesMultiple>"lbHobbies","Ski"%>Value="Ski">Ski</option>
Value="Bike">Bike</option>


Value="Swim">Swim</option>
</select>
</td>
<td> </td>
</tr>
</table>


</form><aname="idd1e3319"></a><aname="idd1e3326"></a>name="idd1e3333"></a></body><aname="idd1e3337"></a>name="idd1e3344"></a><aname="idd1e3351"></a><aname="idd1e3358">
</a><aname="idd1e3361"></a></html>
<html>
<head>
<title>SimplePage.aspx</title></head>



<body>
<formid="WebForm1"method="post"runat="server">


<tableborder=0><aname="idd1e3528"></a><aname="idd1e3535"></a>name="idd1e3542"></a><tr>
<td>Name:</td>
<td><inputtype=textid=txtNamerunat=server/></td><td>type=submitid=Button1Value="Send"runat=server/></td></tr>
<tr>
<tdvalign=top>Hobby:</td><td>
<selectid=lbHobbiesMultiplerunat=server>Value="Ski">Ski</option><optionValue="Bike">Bike</option>Value="Swim">Swim</option></select>


</td>
<td> </td>
</tr>
</table>


</form>
</body><aname="idd1e3546"></a><aname="idd1e3553"></a>name="idd1e3560"></a></html>
<html>
<head>


×