Tải bản đầy đủ (.pdf) (926 trang)

Asp net website programming, c sharp

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.91 MB, 926 trang )


ASP.NETWebsiteProgramming,C#Edition:
Problem,Design,Solution
MarcoBellinaso
KevinHoffman

WroxPressLtd.®
Copyright©2002WroxPress
Allrightsreserved.Nopartofthisbookmaybereproduced,storedina
retrievalsystemortransmittedinanyformorbyanymeans,withoutthe
priorwrittenpermissionofthepublisher,exceptinthecaseofbrief
quotationsembodiedincriticalarticlesorreviews.
Theauthorandpublisherhavemadeeveryeffortinthepreparationof


thisbooktoensuretheaccuracyoftheinformation.However,the
informationcontainedinthisbookissoldwithoutwarranty,eitherexpress
orimplied.Neithertheauthors,WroxPress,noritsdealersordistributors
willbeheldliableforanydamagescausedorallegedtobecausedeither
directlyorindirectlybythisbook.
FirstPrintedinMarch2002
LatestReprint:November2002
PublishedbyWroxPressLtd,
ArdenHouse,1102WarwickRoad,AcocksGreen,
Birmingham,B276BH,UK
PrintedintheUnitedStates
ISBN0764543776
TrademarkAcknowledgements
Wroxhasendeavoredtoprovidetrademarkinformationaboutallthe
companiesandproductsmentionedinthisbookbytheappropriateuseof
capitals.However,Wroxcannotguaranteetheaccuracyofthis


information.
Credits
Authors
MarcoBellinaso
KevinHoffman
CommissioningEditor
DanKent
TechnicalEditors
DianneArrow
DavidBarnes
Index
AndrewCriddle


ManagingEditor
VivEmery
ProjectManager
HelenCuthill
ProductionCoordinator
AbbieForletta
Cover
ChrisMorris
TechnicalReviewers
DonLee
DanMaharry
ChristopheNasarre
MatthewRabinowitz
MarcHSimkin
ProofReader
DevLunsford

AbouttheAuthors
MarcoBellinaso
MarcoBellinasoisafreelancesoftwaredeveloper.Helivesinasmall
townclosetoVenice,Italy.HehasbeenworkingwithVB,C/C++,ASP
andotherMicrosofttoolsforseveralyears,specializinginUserInterface,
API,ActiveX/COMdesignandprogramming.Heisnowspendingallhis
timeonthe.NETFramework,usingC#andVB.NET.
Heisparticularlyinterestedine-commercedesignandimplementation
solutionswithSQLServer,ASP.NET,andwebservices.Heisateam
memberatwww.vb2themax.com,forwhichhewritesarticlesand
commercialsoftware,suchasadd-insforMSVisualStudioandother
utilitiesforVBand.NETdevelopers.
Marcorecentlyco-authored"BeginningC#"fromWroxPress,andisalso
acontributingeditorfortwoleadingItalianprogrammingmagazines:


ComputerProgrammingandVisualBasicJournal(Italianlicenseefor
VisualStudioMagazine).Reachhimat
Acknowledgments
Writingthisbookhasbeenarealpleasuretome.Itgavemethe
opportunitytoworkwithASP.NETonagoodproject,andtoimprovemy
knowledgeofthetechnologyalongtheway.Soitsurelyhasbeenworth
theeffort!Andofcourse,everyonelikestobepublishedwritingabout
whattheyliketodoandhowtodoit.:-)
IowemanythankstoWroxPressforgivingmetheopportunitytowrite
thebook:thisisthemostEnglishI'veeverwritten,soIguesstheeditors
andreviewershadsomeextraworkwithme,althoughtheyweresokind
astoneverconfessit.SomeofthesepeopleareDanielKent,David
Barnes,andDianneArrow.
Otherpeoplecontributedtothisproject,inawayoranother,noworinthe

past,andI'dliketomentionatleastafewnames.Firstofallareallybig
thankyougoestoFrancescoBalena,famousspeakerandauthor,and
editorinchiefoftheItalianlicenseeofVBPJ(nowVisualStudio
Magazine).HereviewedandpublishedanarticleaboutVBsubclassing
thatIwrotesomeyearsago,whenIhadnoeditorialexperienceatall.
Sincethatmomenthehascontinuedtohelpmebyadvisinghowto
improvemywritingstyle,pushingmetostartwritinginEnglish,
suggestingthehottesttechnologytostudy,andgivingtheopportunityto
workonsomecoolsoftwareprojectsaspartoftheVB-2-The-Maxteam.
Francesco,allthisisgreatlyappreciated!
TwootherdevelopersIworkwithfortheItalianmagazines,whohelped
meindifferentways,areDinoEspositoandAlbertoFalossi.
Giovanni-Gianni-Articoisthepersonwhoinitiatedmeinthe
programmingart,suggestingtostartwithVBandthentolearnC/C++as
well.ThankyouforansweringmyquestionswhenIwasatthebeginning,
andforstillhelpingmeinsomesituations.
Amentiongoesalsotomyclosestfriends.Theystillremembermeafter
several"sorry,Ican'tcometoday"rebuttals,andhaveputupwithme


whenIwasunderpressureandnotthenicestpersonpossible.
LastbutnotleastIhavetosaythankyoutomyfamily,whoboughtmy
firstcomputerandalotofprogrammingbookswhenIwasinhighschool
andcouldn'tbuyallthatstuffbymyself.Theydidn'toffermuchmoral
supportduringthework-mostlybecausetheydidn'thaveaclueofwhat
Iwasdoing!Ikeptitasecrettoalmosteverybody-Ihopeitwillbeanice
surprise.:-)
KevinHoffman
Kevinhasalwayslovedcomputersandcomputerprogramming.Hefirst
gothookedwhenhereceivedaCommodoreVIC-20fromhisgrandfather,

whohadrepaireditafterfindingitinthetrash.Hethenstartedaprolific
butunprofitablecareerwritingsharewaregamesandutilitiesfor
electronicbulletinboardsystems.
Hestartedworkingasaprogrammerwhilestillincollege,writing
computerinterfacestosolarmeasurementdevicesandvariousother
scientificinstruments.MovingtoOregon,hedideverythingfromtechnical
supporttotuningUnixkernels,andeventuallyworkingasanASP
programmerfor800.COM,apopularon-lineelectronicsretailer.From
therehemovedontoworkingonlarge,enterpriseASPapplications.
Thenhefinallyfound.NET,whichhenowspends100%ofhis
programmingandlearningeffortson.AbigC#fan,whowoulduseitto
doeverythingincludingbrushmyteethifonlyhecouldfigureouthow,
Kevinhasbeenwritingon.NETforWroxsincethemiddleofBeta1.He
planstocontinueuntilwegettiredofhim.He'scurrentlyinHouston,
Texassweatingalotandworkingonwebservicesandotherlarge-scale
.NETapplications.
Acknowledgments
I'dliketodedicatethisbooktotherestofmy"family",withoutwhomI
couldnothaveaccomplishedmanyofthethingsIamproudoftoday.I
wouldliketothankGeraldforallhissupport-abestfriendineverysense
oftheword-andhisdaughterKeelyformakingmelaugh.Iwouldalso
liketothankJen,Jocelyn,andEmilyfortheirsupportandbeingtherefor


me.AndasalwaysIwanttodedicatemyworktomywife,ConniewithouthersupportIwouldneverhavepublishedasingleword.


ASP.NETWebsite
Programming,C#Edition:
Problem,Design,Solution

ISBN:0764543776
byMarco
BellinasoandKevin
Hoffman
WroxPress2002(538pages)
Thisbookshowsyouhowto
buildaninteractivewebsite
fromdesigntodeployment.
Packedwithsolutionstowebsite
programmingproblems,itwill
haveyoubuildingwellengineered,extendableASP.NET
websitesquicklyandeasily.

TableofContents BackCover
TableofContents
ASP.NETWebsiteProgramming,C#
Edition:Problem,Design,Solution
Introduction


Chapter1 - BuildinganASP.NET
Website
Chapter2 - Foundations
FoundationsforStyleand
Chapter3 Navigation
Chapter4 - MaintainingtheSite
Chapter5 - UsersandAuthentication
Chapter6 - NewsManagement
Chapter7 - Advertising
Chapter8 - Polls

Chapter9 - MailingLists
ForumsandOnline
Chapter10 Communities
Chapter11 - DeployingtheSite
Chapter12 - TheEnd
Index


Introduction
byMarcoBellinasoandKevin
Hoffman
WroxPress?2002


Introduction
WelcometoASP.NETWebsiteProgramming.Inthisbookwewillbuildan
interactive,content-basedwebsiteusingexpandable,interchangeable
modules.BytheendofthebookyouwillhavedevelopedyourASP.NET
skillsforproducingeffective,well-engineered,extendablewebsites.
ASP.NETisagreattoolforbuildingwebsites.Itcontainsmanybuilt-in
featuresthatwouldtakethousandsoflinesofcodeinclassicASP.Andit
doesnotrequireadminrightsinordertodeploycompiledcomponentsyourwholesitecanbedeployedinonefolder.
Thisbookwillguideyouthroughthebewilderingfeaturesavailableto
ASP.NETdevelopers,highlightingthemostusefulandexciting.
Thebookconcentratesonwebsitesthatfocusoncontent.Itdoesnot
showhowtoproduceane-commercesystem,althoughalotofthe
advicewillapplytoe-commercesites.Wecouldaddashoppingbasket
moduleusingthesamefoundations,forexample.
ThisbookisdifferenttomostWroxbooks,becausewebuildasingle
workingwebsitethroughoutthebook.However,eachchapterstands

aloneandshowshowtodevelopindividualmodules,whichyoucan
adaptforyourownwebsites.Wealsosuggestaframeworkthatallowsus
tocreatemodulesandslotthemintothewebsitequicklyandeasily.


WhatDoesThisBookCover?
Thechaptersinthisbookfollowaproblem-design-solutionpattern.First
weidentifywhatweneedtoachieve,thenwesketchouthowwewill
achieveit,andfinallywewillbuildthesoftwareinVisualStudio.NET.
Mostchaptersinvolvebuildinga3-tiersystem,withdata,business,and
presentationlayers.Wewillalsoseehowtobuildseparatemodulesso
thattheyintegratewellintothewholesite.
looksatthewebsiteasawhole.Weidentifytheproblemthatitistryingto
solve,anddiscusshowwewillgoaboutsolvingit.Wethencomeupwith
asolution-whichinvolvesbuildingandintegratingthemodulesdetailed
intheotherchapters.
buildsthefoundationsofoursite.Wesetcodingstandardsanddesign
ourfolderandnamespacestructure.Wecreateourinitialdatabasealthoughatthisstagewehavenodatatoputinit.Wealsobuildsite-wide
errorhandlingcodeandbaseclassesforourdataandbusinesslayer
objects.
extendsourfoundationstothepresentationlayer.Wewillbuildbase
classesfortheASP.NETpagesinthesite,acustomerrorpage,andsite
widenavigation,header,andfootercontrols.
presentsafilemanagementmodule,whichwecanusetodownloadand
uploadsourcecodeforthesite,andmakechangesonline.Wewillalso
lookatMicrosoft'sDataManager,whichenablesustomanageSQL
Serverdatabasesthroughourwebsite.
coversuseraccounts.Welookathowtocreateapowerfulrole-based
securitysystem,andintegrateitwithASP.NET'sbuilt-inauthentication
features.

showshowtoprovideregularlychangingnewscontentthrougha
website.Wealsobuildawebservicetoexposenewsheadlinestoother
sitesandapplications,andaWindowsnewstickerthatusesthisweb


service.
looksatadvertising.Wecreateouradvertisingsystembyextendingthe
ASP.NETAdRotatorcontroltoprovidethepowerweneed.Welookat
logginghitsandimpressions,andprovidingreportstoadvertisers.
coversopinionpollsandvoting.Welookathowtoadministerquestions,
logvotes,andcollatethemintousefulreports.
providesthetoolstocreatee-mailnewsletters.Wewilllookathowto
createmessagesinplaintextandHTML,andhowtoadministerlistsand
setupnewones.
looksatforums.Wecreateeverythingyouneedtopostandread
messages,andgiveadministratorsspecialpermissions.Alongtheway,
thereissomepowerfuluseoftheDataListandDataGridcontrols.
WealsolookathowtouseregularexpressionstoprovidelimitedHTML
support,withoutopeningourforumtotheriskofcross-sitescripting.
showshowtodeploythesite.WewilllookatthewaysVisualStudio
.NETallowsustoprovidesource-freedistributableversionsofour
software,andhowtodeployoursitesontohostingservices.
lookstothefuture.We'veonlyjustbegunourlivesasASP.NETwebsite
developersandherewewilllookatwaysinwhichWroxcansupportyour
continueddevelopment.Inparticularthisincludesthebook'sP2Plist,
whereyoucanworktogetherwithfellowreadersandbenefitfromeach
other'sideasandexperience.


Introduction

byMarcoBellinasoandKevin
Hoffman
WroxPress?2002


WhoIsThisBookFor?
Thebookisfordeveloperswhohaveareasonableknowledgeof
ASP.NET,andwanttoapplythatknowledgetobuildingwebsites.Youwill
getthemostfromthisbookifyouhavereadadecentamountofWrox's
BeginningASP.NETusingC#,orProfessionalASP.NETandaC#book.
YoushouldbecomfortableusingVisualStudio.NETtocreateASP.NET
projects,andthatyouknowC#.


Introduction
byMarcoBellinasoandKevin
Hoffman
WroxPress?2002


WhatYouNeedToUseThisBook
Torunthesamplesinthisbookyouneedtohavethefollowing:
Windows2000orWindowsXP.
VisualStudio.NET1.0.Wehavetestedthecodeforversion1.0,
althoughmostofthecodeshouldworkinlatepre-release
versions.NearlyeverythingwillalsoworkinVisualC#.NET
Standard.
SQLServer2000-althoughmostofthetechniquesweusecould
applytoanydatabasesystem,includingAccess.
TogetthesiteworkingyoumayalsoneedanASP.NETwebhost.Wewill

givesomeguidanceonchoosingonetowardstheendofthebook.


Introduction
byMarco
BellinasoandKevin
Hoffman?
WroxPress?2002


Conventions
We'veusedanumberofdifferentstylesoftextandlayoutinthisbookto
helpdifferentiatebetweenthedifferentkindsofinformation.Hereare
examplesofthestylesweusedandanexplanationofwhattheymean.
Codehasseveralfonts.Ifit'sawordthatwe'retalkingaboutinthetextforexample,whendiscussingaFor...Nextloop,it'sinthisfont.Ifit'sa
blockofcodethatcanbetypedasaprogramandrun,thenit'salsoina
graybox:
<?xmlversion1.0?>
Sometimeswe'llseecodeinamixtureofstyles,likethis:
<?xmlversion1.0?>
<Invoice>

<name>Widget</name>
$10.00</price>
</part>
</invoice>
Incaseslikethis,thecodewithawhitebackgroundiscodeweare
alreadyfamiliarwith;thelinehighlightedingrayisanewadditiontothe
codesincewelastlookedatit.
Advice,hints,andbackgroundinformationcomesinthistypeoffont.

Importantpiecesofinformationcomeinboxeslikethis.
Bulletsappearindented,witheachnewbulletmarkedasfollows:
ImportantWordsareinaboldtypefont.
Wordsthatappearonthescreen,orinmenusliketheFileor
Window,areinasimilarfonttotheoneyouwouldseeona
Windowsdesktop.
Keysthatyoupressonthekeyboard,suchasCtrlandEnter,are


initalics.


Introduction
byMarco
BellinasoandKevin
Hoffman?
WroxPress?2002


CustomerSupport
Wewanttohearfromyou!Wewanttoknowwhatyouthinkaboutthis
book:whatyouliked,whatyoudidn'tlike,andwhatyouthinkwecando
betternexttime.Pleasesendusyourcomments,eitherbyreturningthe
replycardinthebackofthebook,orbye-mailing
<>.Pleasementionthebooktitleinyourmessage.
Wedolistentothesecomments,andwedotakethemintoaccounton
futurebooks.

HowtoDownloadtheCodefortheWebsite
Itiswellworthgettingthewebsiteworkingonyourownmachinebefore

readingtoomuchofthisbook.Itwillhelpyoufollowthedescriptions,
becauseyouwillbeabletoseehowcodesnippetsrelatetothewhole
application,andexperiencethemodularapproachfirsthand.
Togetthecode,visitwww.wrox.comandnavigatetoASP.NETWebsite
Programming.ClickonDownloadintheCodecolumn,oronDownload
Codeonthebook'sdetailpage.
ThefilesareinZIPformat.WindowsXPrecognizestheseautomatically,
butWindows2000requiresade-compressionprogramsuchasWinZip
orPKUnzip.Thearchivecontainsthewholesite,plusareadme
describinghowtogetitupandrunning.

Errata
We'vemadeeveryefforttomakesurethattherearenoerrorsinthetext
orinthecode.Ifyoudofindanerror,suchasaspellingmistake,faulty
pieceofcode,oranyinaccuracy,wewouldappreciatefeedback.By
sendinginerratayoumaysaveanotherreaderhoursoffrustration,and
helpusprovideevenhigherqualityinformation.
E-mailyourcommentsto<>.Yourinformationwillbe
checkedandifcorrect,postedtotheerratapageforthattitle,andusedin


subsequenteditionsofthebook.
Tofinderrataforthistitle,gotowww.wrox.comandlocateASP.NET
WebsiteProgramming.ClickontheBookErratalink,whichisbelowthe
covergraphiconthebook'sdetailpage.

E-mailSupport
Ifyouwishtodirectlyqueryaprobleminthebookwithanexpertwho
knowsthebookindetailthene-mail<>,withthetitle
ofthebookandthelastfournumbersoftheISBNinthesubjectfieldof

thee-mail.Pleaseincludethefollowingthingsinyoure-mail:
Thetitleofthebook,lastfourdigitsoftheISBN,andpage
numberoftheproblemintheSubjectfield.
Yourname,contactinformation,andtheprobleminthebody
ofthemessage.
Wewon'tsendyoujunkmail.Weneedthedetailstosaveyourtimeand
ours.Whenyousendane-mailmessage,itwillgothroughthefollowing
chainofsupport:
CustomerSupport-Yourmessageisdeliveredtoourcustomer
supportstaff,whoarethefirstpeopletoreadit.Theyhavefiles
onmostfrequentlyaskedquestionsandwillansweranything
generalaboutthebookorthewebsiteimmediately.
Editorial-Deeperqueriesareforwardedtothetechnicaleditor
responsibleforthatbook.Theyhaveexperiencewiththe
programminglanguageorparticularproduct,andareableto
answerdetailedtechnicalquestionsonthesubject.
TheAuthors-Ifeventheeditorcannotansweryourproblem,he
orshewillforwardtherequesttotheauthor.Wedotrytoprotect
theauthorfromanydistractionstotheirwriting,butwearehappy
toforwardspecificrequeststothem.AllWroxauthorshelpwith
thesupportontheirbooks.Theywille-mailthecustomerandthe


editorwiththeirresponse,andagainallreadersshouldbenefit.
TheWroxSupportprocesscanonlyoffersupporttoissuesthatdirectly
relatetothecontentofthebook.Supportforquestionsthatfalloutside
thescopeofnormalbooksupport,isprovidedviathecommunitylistsof
ourforum.

p2p.wrox.com

ForauthorandpeerdiscussionjointheP2Pmailinglists.Ourunique
systemprovidesprogrammertoprogrammer™contactonmailinglists,
forums,andnewsgroups,allinadditiontoourone-to-onee-mailsupport
system.IfyoupostaquerytoP2P,youcanbeconfidentthatthemany
Wroxauthorsandindustryexpertswhouseourmailinglistswillexamine
it.Atp2p.wrox.comyouwillfindanumberofdifferentliststhatwillhelp
you,notonlywhileyoureadthisbook,butalsoasyoudevelopyourown
applications.
Thisbookhasitsownlistcalledaspdotnet_website_programming.
Usingthis,youcantalktootherpeoplewhoaredevelopingwebsites
usingthemethodsandframeworkpresentedhere.Youcanshareideas
andcodefornewandimprovedmodules,gethelpwithprogramming
headaches,andshowoffthesitesyou'vewritten!
Tosubscribetoamailinglistjustfollowthesesteps:
1. Goto />2. Choosetheappropriatecategoryfromtheleftmenubar.
3. Clickonthemailinglistyouwishtojoin.
4. Followtheinstructionstosubscribeandfillinyoure-mail
addressandpassword.
5. Replytotheconfirmatione-mailyoureceive.
6. Usethesubscriptionmanagertojoinmorelistsandsetyouremailpreferences.


WhythisSystemOfferstheBestSupport
Youcanchoosetojointhemailinglistsoryoucanreceivethemasa
weeklydigest.Ifyoudon'thavethetime,orfacility,toreceivethemailing
list,thenyoucansearchouronlinearchives.Junkandspammailsare
deleted,andtheuniqueLyrissystemprotectsyoure-mailaddress.
Queriesaboutjoiningorleavinglists,andanyothergeneralqueries
aboutlists,shouldbesentto<>.



×