Tải bản đầy đủ - 0 (trang)
Appendix A: Migrating from ASP to ASP.NET

Appendix A: Migrating from ASP to ASP.NET

Tải bản đầy đủ - 0trang

Highlights

Inthischapter,youwilllearnhowto:

Recognizeissuescommontothemigrationprocess.

MigrateapagethataccessesdatausingADO.

UseprogrammingpracticeswithclassicASPthatwillmake

migrationeasier.

TheonedisadvantageofmovingfromASPtoASP.NETusingC#isthat

thereisnotaconvenientwaytomigrateapplicationsbitbybitorto

modifytheVBScriptusedbyASPsothatitwillcompileasVisualBasic

C#.NETinASP.NET.Ofcourse,migratingVBScriptASPpagestoC#is

alotharderthanconvertingVBScripttoVisualBasic.NET,butifyour

experienceiswithC++,theC#transitionwillbeworththeeffort.



MigrationOverview

AlmostalltheissuesyouencounterwhenmigratingyourclassicASP

applicationstoASP.NETfallintotwocategories:pagestructurechanges

andlanguagechanges.Thenexttwosectionsdiscussthetypesof

changesineachcategoryandthewaysyouneedtoupdateyourcodeto

workwiththem.



PageStructureChanges

ThepagestructurechangesfromclassicASPtoASP.NETcanbebroken

downintotwoareas:changesinthestructureofcodeblocksand

changestothesyntaxofpagedirectives.



CodeBlocks

AsdiscussedinChapter7,therearesignificantchangesbetweenhow

codewasstructuredinclassicASPandhowitisstructuredinASP.NET.

Thesechanges,whicharedesignedtomakeyourcodemorereadable

andmaintainable,arelikelytobethemostcommonissueinmigration.

InclassicASP,server-sidecodeiswrittenineithercoderenderblocks,

indicatedbythesyntax<%%>,orcodedeclarationblocks,indicatedby

thesyntax.Eithersyntaxcanbeused

anywhereinthepageandcancontaineitherstatementsorprocedures.

OneproblemwithclassicASPwasthatitcanbedifficulttotelltheorder

inwhichitscodewillexecute,whichcancausebugs.Itsalsoalltooeasy

towritespaghetticode,windupwithapagecoveredinrenderblocks,

andmixproceduresandrawstatements.Thiscanmakethecodedifficult

toreadandmaintain,andmixingHTMLandrenderblocksoften

negativelyaffectspageperformance.

InASP.NET,thepurposeofrenderblocksandcodedeclarationblocks

hasbeennarrowedconsiderably.RenderblocksinASP.NETcancontain

onlyexecutablestatements,notprocedures,whereascodedeclaration

blockscancontainonlyglobalvariabledeclarationsandprocedures.



Important Inadditiontotheperformanceandreliabilityimplications

ofmixingcodewithinrenderblocksandHTML,using

renderblocksalsomakesforanunclearseparationof

presentationandprogramlogic.ASP.NETenablesone

teamtoworkonthepresentationlogic(inthe.aspxfiles)

whileanothergroupworksonthegutsoftheapplication

logic(inthe.csfiles).

AnothersignificantdifferencebetweenclassicASPandASP.NETisthat

inclassicASP,multiplecodedeclarationblocks

canbeusedonapage.Eachcodedeclarationblockcoulduseadifferent

languagethroughthelanguageattribute,whichcouldbesettoVBScript

orJScript.ASP.NETonlysupportsasinglelanguageperpage,whichis

VisualBasic.NETbydefault.



Top-to-Bottomvs.Event-DrivenProgramming

ClassicASPpagesusingrenderblocksalwaysexecutedfromtopto

bottom.Codein<%%>renderblockswasexecutedandoutputtothe

responsestreamastheASPinterpreterencounteredit.

ASP.NETcodeiscompiledintoaninstanceofthePageclass,and

executionisevent-based.Ratherthanplacingstart-upcodeinthefirst

renderblockinapage,start-upcodeinASP.NETisplacedinthe

Page_Loadeventhandler,whichisfiredwhentheinstanceofthePage

classthatrepresentsthepageisloadedintomemory.Likewise,a

Page_UnLoadeventisfiredjustbeforethepageisremovedfrom

memoryandcanbeusedtorunanyclean-upcodethatisnecessary.



PageDirectives

InclassicASP,theprimarydirectiveusedinpageswasthe@Language

directive,whichspecifiedthelanguagetobeusedforrenderblocks.

Otherlesscommonlyuseddirectivesincluded@Codepage,@

EnableSessionState,@LCID,and@Transaction.

InASP.NET,thesedirectivesareattributesofthe@Pagedirective,

whichshouldappearatthetopofeachASP.NETWebFormpage.See



Chapter7forafulldiscussionofthe@Pagedirectiveanditsattributes.

Onenewattributeofthe@Pagedirectivethatisimportanttodiscussin

relationtoclassicASPistheAspCompatattribute.Bydefault,ASP.NET

runsasamulti-threadedapartment(MTA)process.Thismeansthat

single-threadedapartment(STA)components,suchasthosewrittenin

VisualBasic6.0,arenotcompatiblewithASP.NET.Thisincludesthe

ADOcomponents,whichareinstalledtorunasSTAcomponentsby

default.(Youcanmodifythisbyrunningabatchfilethatchangesthe

registrysettingsforADO,butthatisbeyondthescopeofthisdiscussion.)

SettingtheAspCompatattributetotrueforcesASP.NETtoruninSTA

mode,makingitpossibletouseSTAcomponentsinASP.NETpages.

Important SettingAspCompattotrueshouldbeconsideredashorttermsolutionwhenmigratingfromASPtoASP.NET,

becausethissettingcanhaveasignificantnegative

impactontheperformanceofyourapplication.Forbest

performance,youshouldrewritecomponentswrittenin

earlierversionsofVisualBasicusingVisualBasic.NET,

andmigrateexistingADOcodetouseADO.NET.



LanguageChanges

InadditiontochangestothestructureofpagesinASP.NET,thereare

somesignificantchangeswhenmovingcodefromVBScripttoC#that

willrequiremodificationstoyourcode.Theseincludethefollowing:

SetandLetarenotneededorsupported.Objectreferencescan

besetbysimpleassignment:

Object1=Object2;

ParenthesesarerequiredforcallingallmethodsinC#,including

methodsthatdonothaveparameters:

Response.Write("Hello,World!");

Allstatementsareterminatedwithsemicolons.



Blocksthatareassociatedwithcontrolstructureslikeifandwhile

statementsaredelimitedbycurlybraces({and})ratherthan

words,suchasEndiforEndWhile.

TheVariantdatatypedoesnotexistinC#.NET.The

replacementisObject.

Defaultpropertiesarenotsupported.Allpropertiesmustbe

calledexplicitly:

MyString=TextBox1.Text;

PropertydeclarationsyntaxisdifferentinC#.InsteadofProperty

Set,PropertyGet,andPropertyLet,C#.NETusesthefollowing

syntax(keepinmindthatvalueisaspecialkeywordthatcontains

thevaluesubmittedtothesetportionofthepublicvariable

statement):



publicstringMyPropertgereturnMyInternalVariables

Important Thepropertyjustshownactsasasimpleshellfor

MyInternalVariable.Youcanuseanycodewhilesettingor

gettingtheproperty.Inthisexample,Ionlyset

MyInternalVariableinthesetterifitisdifferentfromthe

currentvalue.Propertiescanbeusedtoexposevalues

thatdontreallyexistasexplicitfieldsintheclass.For

instance,youmightcreateanInvoiceclassthatexposes

anInvoiceTotalpropertythatcannotbeset,andwhen

readactuallytotalstheamountsineachinvoiceline.You

canalsousepropertiestoexposeobjectsthatmighttake

sometimetocreate.Bydoingso,youcanpostponethe

expensivecreationuntiltheobjectisfirstrequested,

allowingJust-In-Timeinitialization.

Bydefault,parametersarepassedtoproceduresinC#byvalue.

Parameterscanbepassedbyreferenceusingtherefkeyword.

YoucanchangethevalueofReferenceparametersinthe

proceduretowhichtheyrepassedandthenretrievetheirvalue

outsidetheprocedure:



publicvoidMySub(refstringMyValueMyValue="Hello!"}



MigratingaDataAccessPagetoASP.NET

Todemonstratesomeofthesechangesandshowyouhowtodealwith

them,letswalkthroughtheprocessofmigratingaclassicASPpagethat

accessesdatainaSQLServerdatabasethroughADOandwritesitto

thepageasanHTMLtable.YouwillmigratetheADOtoADO.NETand

changethelanguagefromVBScripttoC#.Ratherthanrenderingatable

directly,theASP.NETversionusesaDataGridcomponent.Thefollowing

listingshowstheclassicASPpageyoullusetostart.Youwillneedtoset

thepwdattributeintheconnectionstringtotheappropriatepasswordfor

yourVSdotNETMSDEinstance.Youmightalsowanttochangetheuid

attributetothenameofanaccountwithfewerprivilegesthanthesa

account.YoucangetthevaluesofbothoftheseattributesfromyourSQL

Serveradministrator.



GetAuthors.asp



<%@Language=VBScript%>
Thefollowingillustrationshowstheoutputofthispage.



ThepageinthepreviouslistingaccessestheAuthorstableofthePubs

SQLServersampledatabase(inthiscaseintheVSdotNETMSDE

instancethatcanbeinstalledwithVisualStudio.NET),callsarender



functiontowritethedatatothepageasanHTMLtable,andthencallsa

clean-upfunctiontoclosetheconnectiontothedatabaseandsetthe

objectreferencestoNothingtoensurethattheCOMsubsystemknows

theseobjectscanbedestroyed.

Important Onethingthissamplecodehasincommonwithmuchof

thesamplecodeyouwillencounter(andunfortunately,

someproductioncodeaswell)isitsuseofthesaSQL

Serverloginaccountwithablankpassword.(Thisisthe

defaultforSQLServer6.5and7.0installs.Youmust

explicitlychooseablankpasswordtouseablanksa

passwordinSQLServer2000.)Inpractice,thesa

accountshouldalwaysbegivenastrongpassword

becausethisaccounthasfulladministrativerightsonthe

SQLServermachine.Thisincludestheabilitytorun

operatingsystemcommandsthroughanextendedstored

procedure.

Youshouldnever,underanycircumstances,usethesa

accountforaccessingdatafromapage.Allittakesisa

singlebadpagetocompromiseanentireserver,

especiallywhenyourpageprovidessystemadministrator

accesstoSQLServer.

IfyoucannotuseatrustedconnectiontoSQLServer,you

shouldsetuponeormorespecialuseraccountsforeach

Webapplicationwiththeabsoluteminimumrights

necessarytoallowaccesstothatapplicationsdata.This

willreducetheriskofoverbroadrights,whichcancause

datatobecompromised.

Anothersecurityissueinthesampleistheplacingofuser

IDandpasswordinformationdirectlyinthepage.In

practice,ifyouareconnectingtoadatabasewithan

explicitusernameandpassword,connectionstring

informationshouldbestoredsomewheremoresecure.In

orderofincreasingsecurity,optionsincludestoringitas

anappSettinginWeb.config,storingitasanappSettingin

Machine.config(notappropriateinasharedserver



environment),andhard-codingitasaprivatememberof

acompiledcomponent.SeethesectionentitledStoring

DatabaseConnectionStringsSecurelyat

http://msdn.microsoft.com/library/enus/dnnetsec/html/SecNetch12.aspformoreinformation

onthistopic.



Short-TermMigration

Intheshortterm,yourgoalmightbetosimplymoveyourpagesoverto

ASP.NETwhilestillusingmostoftheexistinglogicinthepage.Although

thischoicehasperformanceimplications,itmightmakeyourmigration

easierbylettingyoudoitinstages.Makingthecodeintheprevious

listingworkasanASP.NETpageislargelyamatterofmodifyingitto

complywiththerulesforASP.NETcodeusingVisualBasic.NET.The

conversionfromVBScripttoVisualBasic.NETisbeyondthescopeof

thisbook.



Long-TermMigration

Doingaquick-and-dirtyconversiontoallowyourVBScriptASPpagesto

runasASP.NETpagesusingVisualBasic.NETisastopgapmeasure

thatwillenableyoutogetthepageupandrunningquickly.Amongother

compromises,youwillneedtomodifytheASP.NETdefaulttoallowSTA

componentstoworkcorrectlywithASP.NET.Inthelongrun,itsbestto

fullymigrateyourcodetotakeadvantageofthefeaturesofferedby

ASP.NETandADO.NET.Thefollowingstepsshowhowtomigratethe

ASPpagetorununderASP.NETinC#.



MigrateapagetoASP.NET

1. OpenVisualC#.NET.CreateanewprojectcalledAppendix_A.

2. Torenametheinitialdefaultpage,ontheFilemenu,clickSave

WebForm1.aspxAs.Intheresultingdialogbox,type

GetAuthors.aspxasthenewfilename,andclicktheSave

button.

3. MovethemousepointertotheToolbox,anddragaDataGrid



ontotheWebform.ChangetheIDoftheDataGridtoMyGrid.

4. OntheViewmenu,clickCode,orpressF7tomovetothecode

window.

5. Addthefollowinglinetotheusingclauses:

usingSystem.Data.SqlClient;



6. ScrolldowntothePage_Loadeventhandlerandaddthe

followingcode:

privatevoidPage_Load(objectsender,System.EventArgse

7. Savethefileanditscode-behindmodule,andthenbuildthe

project.

Note TouseatrustedconnectiontoconnecttoSQLServer

asshownintheprecedinglisting,youwillneedto

eitherenableWindowsauthenticationand

impersonationorsetuptheASPNETworkerprocess

accountasaSQLServerlogin,asdescribedin

Chapter9.

8. BrowseGetAuthors.aspxusingMicrosoftInternetExplorer.The

outputshouldlooksimilartothefollowingillustration.



9. SwitchtoGetAuthors.aspxbyclickingtheappropriatetabnear

thetopoftheVisualStudio.NETeditingwindow.Ensurethat



youareinDesignmodebyclickingDesignonthetabcontrolat

thebottomoftheDesignwindow.

10. Right-clicktheDataGridandclickAutoFormatontheshortcut

menu.Thescreenthatappearswilllookliketheillustrationon

thenextpage.



11. IntheAutoFormatdialogbox,clickProfessional1intheSelect

ASchemebox,clickOK,andthensavethepage.

12. BrowseGetAuthors.aspxagain,usingInternetExplorer.The

screenthatappearswilllooksimilartothefollowingillustration.



Note Thecodeintheprecedinglistingoffersbetterperformancethan

aquick-and-dirtyconversionoftheVBScriptcodetoVisualC#

.NETbecauseitdoesnotrelyonAspCompattorun.Ittakes

advantageofADO.NETinsteadofusingADOthroughCOM



Interop(whichcarriessomeperformanceoverhead).Thecode

couldbemadeevenmoreefficientbyusinganADO.NET

DataReadertoaccessthedata.Thecodeinthepreceding

listingalsoprovidesgreaterflexibilityformodifyingthelookof

therenderedtable.Youcanmodifythisbyaddingattributesto

theDataGridtag.UsinganASP.NETDataGridalsoprovides

built-insupportforpaging,editing,andfiltering.Fancy

formatting(includingalternatingitemformatting)isalsoeasyto

add,asshowninStep17ofthepreviousprocedure,using

VisualStudio.NETsAutoFormat.SeeChapter9formore

informationonthesefeatures.



BestPracticesforPreparingforASP.NET

Asyoucanseefromthisappendix,migratingfromclassicASPto

ASP.NETdoesnotneedtobeterriblypainful.However,alotdependson

howyourclassicASPcodeiswritteninthefirstplace.Codethatis

writtenwithagreatdealofintermingledHTMLandrenderblockswillbe

moredifficulttomigrate,aswillcodethatdoesnotfollowgoodcoding

practices.Thefollowingareseveralcodingpracticesyoucanputinplace

inyourongoingclassicASPdevelopmenttomakemigratingitto

ASP.NETeasier:

UseByValorByReftoexplicitlystatewhichtypeofparameteris

desiredinproceduresthattakeparameters.Thiswillremindyou

whattypesofparametersareexpectedwhenmovingtoASP.NET

andC#.

Writeallproceduresin

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Appendix A: Migrating from ASP to ASP.NET

Tải bản đầy đủ ngay(0 tr)

×