Tải bản đầy đủ - 0 (trang)
Chapter 14: Tracing and Debugging ASP.NET Applications

Chapter 14: Tracing and Debugging ASP.NET Applications

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

Overview

Inthischapter,youwilllearnhowto:

Usetracingtolearnhowyourapplicationisrunning.

DebugASP.NETapplications.

UsetheVisualStudio.NETdebugger.

ThisbookhascoveredawidevarietyoftopicsrelatedtoASP.NET

development.Ihopeyoullbeabletoavoidmostproblemswhile

developingyourASP.NETWebapplications.Inevitably,however,there

willbetimeswhenyourcodedoesntdowhatyouexpectitto,oryoullrun

intoerrorsorproblemsthatpreventyourapplicationfromworking.This

finalchapterwilllookatwhattodowhenthathappens.Itsnotintendedto

makeyouanexpertdebugger,butrathertogiveyouanoverviewofthe

toolsavailablefordebugginginASP.NET.

TosaythatclassicASPdidnotofferdevelopersmuchsupportfor

debuggingtheirapplicationswouldbeacolossalunderstatement.

Despitebeingaverysimpleandproductivedevelopmentenvironment,

classicASPleftalottobedesiredintermsofdebugginganderror

messages.

Forexample,inclassicASPyouhadnoconvenientwaytoaccessthe

stateofthecurrentHTTPrequestoroftheothercollections,suchasthe

QueryStringorFormscollections.ASP.NETaddressesthisissuethrough

anewfeaturecalledtracing,whichIlldiscussinthefirstpartofthis

chapter.

Additionally,classicASPerrormessageswereoftencrypticatbest.Ifyou

werelucky,theytoldyouthelineoftheASPpageonwhichtheerror

occurred.Unfortunately,thisinformationcouldbemisleading.Theerror

mighthaveoccurredinafunctioncalledbythatpage,butyouwouldnt

knowthatfromtheerrormessage.ASP.NETprovidesmuchrichererror

reporting,includingastacktraceofthefunctionsthatleduptoanerror



condition,makingitmucheasiertolocatetherootcauseoftheerror.

TheMicrosoft.NETFrameworkSDKshipswithitsowndebugger,so

developerswhoarenotusingMicrosoftVisualStudio.NETcanattachit

totheprocessoftheirASP.NETapplicationandstepthroughtheircode

tofindandfixproblems.Mostoften,however,usingthedebuggerin

VisualStudio.NETcanbethemostefficientwaytodebugyour

application.IlldiscusstheimprovederrorreportingandtheSDK

debuggerinthesecondhalfofthischapter.



Tracing

Asmentioned,oneweaknessofclassicASPwasthelackofaneasyway

togetinformationaboutthecurrentrequest.Youshouldcreatereusable

includefilestowriteoutthecontentsofthevariouscollectionsofthe

requestobject,buttherewasnosimplemethodofmakingthis

informationavailable.ASP.NETprovidesasolutionintheformoftracing,

whichprovidesasubstantialamountofinformationaboutrequeststhat

havebeenexecuted,eitheratthepagelevelortheapplicationlevel,as

wellasawaytogetyourowncustomdebuginformationwithout

exposingittotheusersofyourapplication.



EnablingPage-LevelTraceOutput

ThesimplestwaytoaccesstraceinformationisthroughtheTrace

attributeofthe@Pagedirective.ByaddingtheTraceattributetoany

.aspxpage,youcaninstructASP.NETtoappendthetraceoutputforthat

pagetotherenderedcontentofthepage.Thefollowingexampleshows

howtoenabletracingonasimpleASP.NETpage.



Displaytracinginformation

1. OpenVisualStudioandcreateanewASP.NETWeb

ApplicationprojectcalledChapter_14.RenamethedefaultWeb

PagecreatedbyVisualStudiofromWebPage1.aspxto

SimpleTrace.aspxbyselectingFile,thenSave

WebForm1.aspxAs.

2. Right-clickanywhereonthepage,andselectPropertiesfrom

thecontextmenu.Intheresultingdialogbox(showninthe

illustrationonthefollowingpage),changethePagetitleto

SimpleTraceExample.ChangePageLayoutfromGridLayout

toFlowLayout.(IfyouuseGridLayout,traceoutputand

renderedpageoutputcanendupoverlapping.Using

FlowLayoutpreventsthis.)ClickOK.



3. Addalabeltothepagebydraggingalabelfromthetoolbox

ontotheform.InFlowLayout,thelabelwillmovetotheupper

leftoftheformnomatterwhereyouplaceit.ChangetheText

propertytoTraceisenabledforthispage.

4. ClickinanemptyareaofthepagetoselecttheDOCUMENT

object,locatethetracepropertyinthePropertieswindow,and

setitsvaluetoTrue.

5. SaveSimpleTrace.aspxandtheproject,andthenbuildthe

project.

6. BrowseSimpleTrace.aspxusingMicrosoftInternetExplorer.

Theresultingscreenshouldlooksimilartothefollowing

illustration:



Thetraceoutputincludessuchinformationasthecontentsofthe

cookies,forms,andquerystringcollections.Therefore,page-leveltracing

usingtheTraceattributeofthe@Pagedirectiveshouldberestrictedto

non-productionsystemsbecausetheoutputisvisibletoanyclient

requestingthatpage.Althoughyoucanuseoneoftheconfiguration

optionsdetailedinthenextsectiontoconfigureASP.NETtoprovide

page-leveltraceoutputonlyforrequestsfromthelocalsystem,youre

bestoffstickingtoapplication-leveltracingonpublicly

availableapplications.

Important Tracinghasanimpactonapplicationperformance,and

theinformationthatitprovidescouldpotentiallybeused

bymalicioususerstoattackyourapplication,soforboth

performanceandsecurityreasonsyoushouldusetracing

onlyindevelopmentenvironments;disabletracingbefore

deployinganapplicationtoaproduction(public-facing)

environment.



EnablingApplication-LevelTraceOutput

Inadditiontoprovidingtraceoutputatthepagelevel,ASP.NETcanbe

configuredtologtraceoutputforaspecifiednumberofrequestsforlater

review.Theprimaryadvantagesofthisapproacharethatitallowsyouto

enabletracingforanentiresiteatonce,andthatwhenconfigured

properlyithidestraceoutputfromusersofthepage,makingitsuseon

productionorcustomer-facingsystemslesslikelytoallowmalicious

usersaccesstotoomuchinformation.

Youenableapplication-leveltracingbyaddingtheconfiguration

elementtotheWeb.configfilefortheapplicationandthensettingits

attributestothedesiredvalues.Thefollowingexampledemonstrates

modifyingtheelementtoenableapplication-leveltracingand

tellsASP.NETtologupto40requests.(Loggedrequestsmustbe

clearedmanuallywhentherequestlimithasbeenreached.)AppendixB

detailstheattributesforthesection.



Enableapplication-leveltracinginWeb.config



1. InVisualStudio,opentheChapter_14projectcreatedinthe

previousexample.



2. EdittheWeb.Configfilebydouble-clickingonitintheSolution

Explorer.Then,fromtheEditmenu,selectFindAndReplace,

andthenselectFind.IntheFindWhattextbox,type
thenclickFindNext.Thiswillmoveyourcursortothebeginning

ofthesection.Changetheelementsothatit

lookslikethis:


3. SavethechangestoWeb.config.

Toallowaccesstotheloggedtraceoutput,ASP.NETprovidesan

HttpHandlerthatismappedtoaspecialURLcalledtrace.axd.Appending

trace.axdtothebaseURLfortheapplicationwilldisplaythelistof

currentlyavailabletraces,asshowninthefollowingillustration.Clicking

ViewDetailsforaparticulartracedisplaysitsoutput.ClickingClear

CurrentTraceclearsallcurrententriesfromthetracelogandallows

morerequeststobelogged.



WritingtotheTraceOutput

Atonetimeoranother,mostdeveloperswhohaveevertrieddebugginga

classicASPapplicationhaveresortedtousingResponse.Writefor

outputtingthevalueofvariablestothepage,orforplacingflagswithin



codetodeterminewherethecodeisbreakingbyseeinghowmuchofthe

pagegetsexecutedbeforeexecutionishalted.Whilethiswas(andstill

is)ausefultechniquefordebugging,itisusefulonlyfordevelopment

machinesthatarenotaccessiblebyusersmanyoftheaforementioned

developershavegottencallsfromtheirsupervisorswhentheyforgotto

taketheResponse.Writestatementsoutbeforemigratingapagetoa

productionserver.

Important Thepage-levelsettingfortracefunctionalitywilloverride

thesettinginWeb.config.Soevenifyouhavetracing

enabledinWeb.config,settingthetraceattributeofthe@

PagedirectivetoFalsewillstilldisabletracingforthat

page.Likewise,eveniftracingisdisabledatthe

applicationlevelinWeb.config(oratthemachinelevelin

machine.config),settingthepage-leveltraceattributeto

Truewillstillenabletracingforthatpage.Forthisreason,

ifyouusepage-leveltracingyoushouldalwaysdoublecheckyourpagesbeforepublishingthemtoapublic

servertoensurethatthetraceattributeforeachpagehas

beenremovedorsettoFalse.

ASP.NETstracefunctionalityminimizesthisproblembyallowing

developerstowritetothetraceoutputinsteadofwritingtothepage

output.Assumingthatpage-leveltraceoutputhasnotbeenenabled,this

preventsend-usersfromseeingthetracestatementswrittenbythe

developer.

Important Asnotedearlier,enablingtracingforapageorforan

applicationdoescarrysomeperformanceoverhead.Even

thoughtheASP.NETtracefunctionalityallowsyouto

leavetracingenabledwithouttraceoutputbeingviewed

byend-users,whenperformanceisimportant,itisagood

ideatodisabletracingforanapplicationatboththepage

andapplicationlevel.

ThetraceoutputisexposedtodevelopersviatheTraceContextclass,

whichisavailablefromthePage.Traceproperty(whichcanbereferredto

withinapagesimplyasTrace,sincethePageobjectisassumed).There



aretwomethodsforwritingtothetraceoutput,Trace.Writeand

Trace.Warn.



DeterminingIfTracingIsEnabled

Tokeepdevelopersfromwastingtimeattemptingtowritetothetrace

outputwhentracingisnotenabled,theTraceContextclassexposesa

BooleanpropertycalledIsEnabled,whichcontainsthecurrentstatusof

tracingforthepage.Thisisespeciallyhelpfulifyouareperforming

expensiveprocessingordatabaselookupsasapartofyourtrace

logging.



UsingTrace.Write



TheTrace.WritemethodoftheTraceContextclassisoverloaded,and

youcancallitinoneofthefollowingthreeways:

Trace.Write(stringmessage)Trace.Write(stringcategory,string

messageisastringcontainingthemessagetobewrittentothe

traceoutput.

categoryisastringcontainingadescriptionofthemessage

(variable,statement,orwhateverthedeveloperwantsasa

category).

errorInfoisanexceptionobject,whichallowsexceptionstobe

loggedtothetraceoutput.

ThecategoryanderrorInfoparametersallowdeveloperstosetup

sophisticatedapplication-widetracingbydefiningspecificcategoriesof

loggedinformationandusingthemconsistentlyacrossanapplication.

Thefollowingexampleshowshowtocreateapagethattestsiftracingis

enabledforthepage,andthenwritesasimplemessagetothetrace

output.



Writetracemessages

1. InVisualStudio,opentheChapter_14projectusedinthe



previousexamples.Addanewpagebyright-clickingontheroot

oftheprojectintheSolutionExplorer,selectingAdd,andthen

AddWebForm.Typethenameoftheformas

TraceWrite.aspx.

2. Right-clickanywhereonthepage,andselectPropertiesfrom

thecontextmenu.Intheresultingdialogbox,changePage

LayoutfromGridLayouttoFlowLayout,andthenclickOK.

3. Addalabeltothepage.



4. ChangetoHTMLmodebyclickingtheHTMLbuttononthe

bottomofthedesignwindow.AddTrace=truetothe@Page

directive:

<%@PageLanguage="c#"AutoEventWireup="false"Code



5. ChangetothecodeviewbypressingF7.Scrolldowntothe

Page_Loadeventhandlerandaddthefollowingcode:

if(Trace.IsEnabledLabel1.Text="Writing'Hellofrom

6. SaveTraceWrite.aspx,itscode-behindfile,andtheproject,and

thenbuildtheproject.

7. BrowseTraceWrite.aspxusingInternetExplorer.Theresulting

screenshouldlooksimilartotheillustrationonthenexypage.

(NoticethehellomessageonthefirstlineundertheTrace

Informationheading.)



UsingTrace.Warn

AnothermethodofferedbytheTraceContextclassforwritingtothetrace

outputisTrace.Warn.Theprimarydifferencebetweenthetwomethodsis

thatoutputwrittenwithTrace.Warnappearsinthetraceoutputasred

text,makingitidealforhighlightingimportantentriessuchasexceptions.



UnderstandingtheTraceOutput

Thetraceoutputforapagecontainsagreatdealofinformation.Table

14-1liststhesectionsofthetraceoutputanddescribestheinformation

containedineach.

Table14-1:TraceOutputSections

Section



Description



Displaysrequest-specificinformationsuchas

RequestDetails sessionID,requesttype,requeststatuscode,and

encoding.

Trace

Information



ControlTree



Displaysmessagesrelatingtostagesofpage

processing,aswellasexecutiontimesforthese

stages.

Displaysatreerepresentationofallcontrolsonthe

page,includingLiteralControlsforstaticHTMLtext



withinthesourcefile.Alsodisplaystherendersize

andViewStatesizeofeachcontrol.

Cookies

Collection



Displaysthename,content,andsizeofallcookies

sentaspartoftherequest.



Headers

Collection



DisplaysalistofallHTTPheaderssentasapartof

therequest.



FormCollection



Displaysalistofthenamesandvaluesofallform

fieldssentaspartofaPOSTrequest.



Querystring

Collection



Displaysalistofthenamesandvaluesofall

querystringvaluessentaspartofaGETrequest.



ServerVariables



Displaysalistoftheservervariablesforthe

request.



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

Chapter 14: Tracing and Debugging ASP.NET Applications

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

×