|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
c语言的编译器,几乎是所有新平台都有的。因此从这点上看,c语言的程序,比其他任何语言更加容易跨平台。关于Asp.net页面层开辟不管是写页面仍是写控件,我以为都能够用一句话形貌:"Dotherightthingattherighttimeintherightplace."这是07岁尾的一篇工具,仍是有点代价收拾出来与人人共享。本文从两个粒度对Asp.net性命周期做了展现,一是经由过程纪录页面事务的触发按次看哀求的处置流程,一是经由过程Reflector看Page类外部对哀求处置的完成,为了明晰我清算失落了ETW相干的代码保存了一个简化却足能够申明成绩的流程骨架;
本文掩盖以下内容:
- 页面事务的触发按次展现
- 清算失落ETW代码后的,Page类外部对哀求处置的完成
- MSDN关于Asp.net性命周期十分主要的四个表格
- 演示源代码下载
1
<br>usingSystem;
2
<br>usingSystem.Configuration;
3
<br>usingSystem.Data;
4
<br>usingSystem.Web;
5
<br>usingSystem.Web.Security;
6
<br>usingSystem.Web.UI;
7
<br>usingSystem.Web.UI.HtmlControls;
8
<br>usingSystem.Web.UI.WebControls;
9
<br>usingSystem.Web.UI.WebControls.WebParts;
10
<br>
11
<br>publicpartialclass_Default:System.Web.UI.Page
12
<br>
<br>
<br>{
13
<br>protectedvoidPage_PreInit(objectsender,EventArgse)
14
<br>
<br>
<br>{
15
<br>Response.Write("Page_PreInit<br/>");
16
<br>}
17
<br>protectedvoidPage_Init(objectsender,EventArgse)
18
<br>{
19
<br>Response.Write("Page_Init<br/>");
20
<br>
21
<br>}
22
<br>protectedvoidPage_InitComplete(objectsender,EventArgse)
23
<br>{
24
<br>Response.Write("Page_InitComplete<br/>");
25
<br>
26
<br>}
27
<br>protectedvoidPage_PreLoad(objectsender,EventArgse)
28
<br>{
29
<br>Response.Write("Page_PreLoad<br/>");
30
<br>
31
<br>}
32
<br>protectedvoidPage_Load(objectsender,EventArgse)
33
<br>{
34
<br>Response.Write("Page_Load<br/>");
35
<br>
36
<br>}
37
<br>protectedvoidPage_LoadComplete(objectsender,EventArgse)
38
<br>{
39
<br>Response.Write("Page_LoadComplete<br/>");
40
<br>
41
<br>}
42
<br>protectedvoidPage_PreRender(objectsender,EventArgse)
43
<br>{
44
<br>Response.Write("Page_PreRender<br/>");
45
<br>
46
<br>}
47
<br>protectedvoidPage_SaveStateComplete(objectsender,EventArgse)
48
<br>{
49
<br>Response.Write("Page_SaveStateComplete<br/>");
50
<br>
51
<br>}
52
<br>
53
<br>
54
<br>protectedvoidPage_Unload(objectsender,EventArgse)
55
<br>{
56
<br>inti=0;
57
<br>i++;//这行代码是用来设置断点的,为何不必Response.Write?你说呢?
58
<br>
59
<br>}
60
<br>
61
<br>
62
<br>protectedvoidButton1_Click(objectsender,EventArgse)
63
<br>{
64
<br>Label1.Text="ControlEvent";
65
<br>Response.Write("Button事务触发!<br/>");
66
<br>}
67
<br>}
68
<br>
69
<br>
70
<br>
运转了局:
Page_PreInit
Page_Init
Page_InitComplete
Page_PreLoad
Page_Load
Page_LoadComplete
Page_PreRender
Page_SaveStateComplete
点击页面的Button后的输入:
Page_PreInit
Page_Init
Page_InitComplete
Page_PreLoad
Page_Load
Button事务触发!
Page_LoadComplete
Page_PreRender
Page_SaveStateComplete
我们从一个更细的粒度,在Reflector中看Page对哀求处置的代码:
privatevoidPerformPreInit()
{
this.OnPreInit(EventArgs.Empty);
this.InitializeThemes();//看到主题和模板页是甚么时分加载了吧
this.ApplyMasterPage();
this._preInitWorkComplete=true;
}
MSDN上对Asp.net性命周期注释有十分主要的四个表格:
Stage
Description
Pagerequest
Thepagerequestoccursbeforethepagelifecyclebegins.Whenthepageisrequestedbyauser,ASP.NETdetermineswhetherthepageneedstobeparsedandcompiled(thereforebeginningthelifeofapage),orwhetheracachedversionofthepagecanbesentinresponsewithoutrunningthepage.
Start
Inthestartstep,pagepropertiessuchasRequestandResponseareset.Atthisstage,thepagealsodetermineswhethertherequestisapostbackoranewrequestandsetstheIsPostBackproperty.Additionally,duringthestartstep,thepage"sUICulturepropertyisset.
Pageinitialization
Duringpageinitialization,controlsonthepageareavailableandeachcontrol"sUniqueIDpropertyisset.Anythemesarealsoappliedtothepage.Ifthecurrentrequestisapostback,thepostbackdatahasnotyetbeenloadedandcontrolpropertyvalueshavenotbeenrestoredtothevaluesfromviewstate.
Load
Duringload,ifthecurrentrequestisapostback,controlpropertiesareloadedwithinformationrecoveredfromviewstateandcontrolstate.
Validation
Duringvalidation,theValidatemethodofallvalidatorcontrolsiscalled,whichsetstheIsValidpropertyofindividualvalidatorcontrolsandofthepage.
Postbackeventhandling
Iftherequestisapostback,anyeventhandlersarecalled.
Rendering
Beforerendering,viewstateissavedforthepageandallcontrols.Duringtherenderingphase,thepagecallstheRendermethodforeachcontrol,providingatextwriterthatwritesitsoutputtotheOutputStreamofthepage"sResponseproperty.
Unload
Unloadiscalledafterthepagehasbeenfullyrendered,senttotheclient,andisreadytobediscarded.Atthispoint,pagepropertiessuchasResponseandRequestareunloadedandanycleanupisperformed.
Life-cycleEvents
PageEvent
TypicalUse
PreInit
Usethiseventforthefollowing:
- ChecktheIsPostBackpropertytodeterminewhetherthisisthefirsttimethepageisbeingprocessed.
- Createorre-createdynamiccontrols.
- Setamasterpagedynamically.
- SettheThemepropertydynamically.
- Readorsetprofilepropertyvalues.
Note:
Iftherequestisapostback,thevaluesofthecontrolshavenotyetbeenrestoredfromviewstate.Ifyousetacontrolpropertyatthisstage,itsvaluemightbeoverwritteninthenextevent.
Init
Raisedafterallcontrolshavebeeninitializedandanyskinsettingshavebeenapplied.Usethiseventtoreadorinitializecontrolproperties.
InitComplete
RaisedbythePageobject.Usethiseventforprocessingtasksthatrequireallinitializationbecomplete.
PreLoad
UsethiseventifyouneedtoperformprocessingonyourpageorcontrolbeforetheLoadevent.
AfterthePageraisesthisevent,itloadsviewstateforitselfandallcontrols,andthenprocessesanypostbackdataincludedwiththeRequestinstance.
Load
ThePagecallstheOnLoadeventmethodonthePage,thenrecursivelydoesthesameforeachchildcontrol,whichdoesthesameforeachofitschildcontrolsuntilthepageandallcontrolsareloaded.
UsetheOnLoadeventmethodtosetpropertiesincontrolsandestablishdatabaseconnections.
Controlevents
Usetheseeventstohandlespecificcontrolevents,suchasaButtoncontrol"sClickeventoraTextBoxcontrol"sTextChangedevent.
Note:
Inapostbackrequest,ifthepagecontainsvalidatorcontrols,checktheIsValidpropertyofthePageandofindividualvalidationcontrolsbeforeperforminganyprocessing.
LoadComplete
Usethiseventfortasksthatrequirethatallothercontrolsonthepagebeloaded.
PreRender
Beforethiseventoccurs:
- ThePageobjectcallsEnsureChildControlsforeachcontrolandforthepage.
- EachdataboundcontrolwhoseDataSourceIDpropertyissetcallsitsDataBindmethod.Formoreinformation,seeDataBindingEventsforData-BoundControlslaterinthistopic.ThePreRendereventoccursforeachcontrolonthepage.Usetheeventtomakefinalchangestothecontentsofthepageoritscontrols.
SaveStateComplete
Beforethiseventoccurs,ViewStatehasbeensavedforthepageandforallcontrols.Anychangestothepageorcontrolsatthispointwillbeignored.
Usethiseventperformtasksthatrequireviewstatetobesaved,butthatdonotmakeanychangestocontrols.
Render
Thisisnotanevent;instead,atthisstageofprocessing,thePageobjectcallsthismethodoneachcontrol.AllASP.NETWebservercontrolshaveaRendermethodthatwritesoutthecontrol"smarkupthatissenttothebrowser.
Ifyoucreateacustomcontrol,youtypicallyoverridethismethodtooutputthecontrol"smarkup.However,ifyourcustomcontrolincorporatesonlystandardASP.NETWebservercontrolsandnocustommarkup,youdonotneedtooverridetheRendermethod.Formoreinformation,seeDevelopingCustomASP.NETServerControls.
Ausercontrol(an.ascxfile)automaticallyincorporatesrendering,soyoudonotneedtoexplicitlyrenderthecontrolincode.
Unload
Thiseventoccursforeachcontrolandthenforthepage.Incontrols,usethiseventtodofinalcleanupforspecificcontrols,suchasclosingcontrol-specificdatabaseconnections.
Forthepageitself,usethiseventtodofinalcleanupwork,suchasclosingopenfilesanddatabaseconnections,orfinishinguploggingorotherrequest-specifictasks.
Note:
Duringtheunloadstage,thepageanditscontrolshavebeenrendered,soyoucannotmakefurtherchangestotheresponsestream.IfyouattempttocallamethodsuchastheResponse.Writemethod,thepagewillthrowanexception.
DataBindingEventsforData-BoundControls
Tohelpyouunderstandtherelationshipbetweenthepagelifecycleanddatabindingevents,thefollowingtablelistsdata-relatedeventsindata-boundcontrolssuchastheGridView,DetailsView,andFormViewcontrols.
ControlEvent
TypicalUse
DataBinding
Thiseventisraisedbydata-boundcontrolsbeforethePreRendereventofthecontainingcontrol(orofthePageobject)andmarksthebeginningofbindingthecontroltothedata.
Usethiseventtomanuallyopendatabaseconnections,ifrequired.(Thedatasourcecontrolsoftenmakethisunnecessary.)
RowCreated(GridViewonly)orItemCreated(DataList,DetailsView,SiteMapPath,DataGrid,FormView,Repeater,andListViewcontrols)
Usethiseventtomanipulatecontentthatisnotdependentondatabinding.Forexample,atruntime,youmightprogrammaticallyaddformattingtoaheaderorfooterrowinaGridViewcontrol.
RowDataBound(GridViewonly)orItemDataBound(DataList,SiteMapPath,DataGrid,Repeater,andListViewcontrols)
Whenthiseventoccurs,dataisavailableintheroworitem,soyoucanformatdataorsettheFilterExpressionpropertyonchilddatasourcecontrolsfordisplayingrelateddatawithintheroworitem.
DataBound
Thiseventmarkstheendofdata-bindingoperationsinadata-boundcontrol.InaGridViewcontrol,databindingiscompleteforallrowsandanychildcontrols.
Usethiseventtoformatdataboundcontentortoinitiatedatabindinginothercontrolsthatdependonvaluesfromthecurrentcontrol"scontent.(Fordetails,see"Catch-upEventsforAddedControls"earlierinthistopic.)
LoginControlEvents
TheLogincontrolcanusesettingsintheWeb.configfiletomanagemembershipauthenticationautomatically.However,ifyourapplicationrequiresyoutocustomizehowthecontrolworks,orifyouwanttounderstandhowLogincontroleventsrelatetothepagelifecycle,youcanusetheeventslistedinthefollowingtable.
ControlEvent
TypicalUse
LoggingIn
Thiseventisraisedduringapostback,afterthepage"sLoadCompleteeventhasoccurred.Itmarksthebeginningoftheloginprocess.
Usethiseventfortasksthatmustoccurpriortobeginningtheauthenticationprocess.
Authenticate
ThiseventisraisedaftertheLoggingInevent.
UsethiseventtooverrideorenhancethedefaultauthenticationbehaviorofaLogincontrol.
LoggedIn
Thiseventisraisedaftertheusernameandpasswordhavebeenauthenticated.
Usethiseventtoredirecttoanotherpageortodynamicallysetthetextinthecontrol.Thiseventdoesnotoccurifthereisanerrororifauthenticationfails.
LoginError
Thiseventisraisedifauthenticationwasnotsuccessful.
Usethiseventtosettextinthecontrolthatexplainstheproblemortodirecttheusertoadifferentpage.
演示代码下载地点:http://www.ckuyun.com/Files/me-sa/HttpStudy.rar
来自:http://www.ckuyun.com/me-sa/archive/2008/03/17/lifecycle.html
1privatevoidProcessRequestMain(boolincludeStagesBeforeAsyncPoint,boolincludeStagesAfterAsyncPoint)
2{
3try
4{
5HttpContextcontext=this.Context;
6stringstr=null;
7if(includeStagesBeforeAsyncPoint)
8{
9if(this.IsInAspCompatMode)
10{
11AspCompatApplicationStep.OnPageStartSessionObjects();
12}
13if(this.PageAdapter!=null)
14{
15this._requestValueCollection=this.PageAdapter.DeterminePostBackMode();
16}
17else
18{
19this._requestValueCollection=this.DeterminePostBackMode();
20}
21stringcallbackControlID=string.Empty;
22if(this.DetermineIsExportingWebPart())
23{
24if(!RuntimeConfig.GetAppConfig().WebParts.EnableExport)
25{
26thrownewInvalidOperationException(SR.GetString("WebPartExportHandler_DisabledExportHandler"));
27}
28str=this.Request.QueryString["webPart"];
29if(string.IsNullOrEmpty(str))
30{
31thrownewInvalidOperationException(SR.GetString("WebPartExportHandler_InvalidArgument"));
32}
33if(string.Equals(this.Request.QueryString["scope"],"shared",StringComparison.OrdinalIgnoreCase))
34{
35this._pageFlags.Set(4);
36}
37stringstr3=this.Request.QueryString["query"];
38if(str3==null)
39{
40str3=string.Empty;
41}
42this.Request.QueryStringText=str3;
43context.Trace.IsEnabled=false;
44}
45if(this._requestValueCollection!=null)
46{
47if(this._requestValueCollection["__VIEWSTATEENCRYPTED"]!=null)
48{
49this.ContainsEncryptedViewState=true;
50}
51callbackControlID=this._requestValueCollection["__CALLBACKID"];
52if((callbackControlID!=null)&&(this._request.HttpVerb==HttpVerb.POST))
53{
54this._isCallback=true;
55}
56elseif(!this.IsCrossPagePostBack)
57{
58VirtualPathpath=null;
59if(this._requestValueCollection["__PREVIOUSPAGE"]!=null)
60{
61try
62{
63path=VirtualPath.CreateNonRelativeAllowNull(DecryptString(this._requestValueCollection["__PREVIOUSPAGE"]));
64}
65catch(CryptographicException)
66{
67this._pageFlags[8]=true;
68}
69if((path!=null)&&(path!=this.Request.CurrentExecutionFilePathObject))
70{
71this._pageFlags[8]=true;
72this._previousPagePath=path;
73}
74}
75}
76}
77if(this.MaintainScrollPositionOnPostBack)
78{
79this.LoadScrollPosition();
80}
81
82this.PerformPreInit();
83
84this.InitRecursive(null);
85
86this.OnInitComplete(EventArgs.Empty);
87
88if(this.IsPostBack)
89{
90this.LoadAllState();
91
92this.ProcessPostData(this._requestValueCollection,true);
93
94}
95
96
97this.OnPreLoad(EventArgs.Empty);
98
99this.LoadRecursive();
100
101if(this.IsPostBack)
102{
103this.ProcessPostData(this._leftoverPostData,false);
104
105this.RaiseChangedEvents();
106
107this.RaisePostBackEvent(this._requestValueCollection);
108
109}
110
111this.OnLoadComplete(EventArgs.Empty);
112
113if(this.IsPostBack&&this.IsCallback)
114{
115this.PrepareCallback(callbackControlID);
116}
117elseif(!this.IsCrossPagePostBack)
118{
119
120this.PreRenderRecursiveInternal();
121}
122}
123if((this._asyncInfo==null)||this._asyncInfo.CallerIsBlocking)
124{
125this.ExecuteRegisteredAsyncTasks();
126}
127if(includeStagesAfterAsyncPoint)
128{
129if(this.IsCallback)
130{
131this.RenderCallback();
132}
133elseif(!this.IsCrossPagePostBack)
134{
135this.PerformPreRenderComplete();
136
137if(context.TraceIsEnabled)
138{
139this.BuildPageProfileTree(this.EnableViewState);
140this.Trace.Write("aspx.page","BeginSaveState");
141}
142
143this.SaveAllState();
144
145this.OnSaveStateComplete(EventArgs.Empty);
146if(str!=null)
147{
148this.ExportWebPart(str);
149}
150else
151{
152this.RenderControl(this.CreateHtmlTextWriter(this.Response.Output));
153}
154
155this.CheckRemainingAsyncTasks(false);
156}
157}
158}
159catch(ThreadAbortExceptionexception)
160{
161HttpApplication.CancelModuleExceptionexceptionState=exception.ExceptionStateasHttpApplication.CancelModuleException;
162if(((!includeStagesBeforeAsyncPoint||!includeStagesAfterAsyncPoint)||((this._context.Handler!=this)||(this._context.ApplicationInstance==null)))||((exceptionState==null)||exceptionState.Timeout))
163{
164this.CheckRemainingAsyncTasks(true);
165throw;
166}
167this._context.ApplicationInstance.CompleteRequest();
168Thread.ResetAbort();
169}
170catch(ConfigurationException)
171{
172throw;
173}
174catch(Exceptionexception3)
175{
176PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_DURING_REQUEST);
177PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_TOTAL);
178if(!this.HandleError(exception3))
179{
180throw;
181}
182}
183}
184
185
186
187
188如果英语好,口才好,加上女孩子的优势说不定有机会进去做做别的工具) |
|