金色的骷髅 发表于 2015-1-18 11:30:52

ASP.NET编程:两个粒度看Asp.net性命周期仓酷云

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=true;
68}
69if((path!=null)&&(path!=this.Request.CurrentExecutionFilePathObject))
70{
71this._pageFlags=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如果英语好,口才好,加上女孩子的优势说不定有机会进去做做别的工具)

再见西城 发表于 2015-1-21 09:11:09

同时也感谢博客园给我们这个平台,也感谢博客园的编辑们做成专题引来这么多高人指点。

乐观 发表于 2015-1-21 16:15:59

可以看作是VC和Java的混合体吧,尽管MS自己讲C#内核中更多的象VC,但实际上我还是认为它和Java更象一些吧。首先它是面向对象的编程语言,而不是一种脚本,所以它具有面向对象编程语言的一切特性。

再现理想 发表于 2015-1-24 14:53:20

对于中小项目来说.net技术是完全可以胜任,但为什么现在大型公司或网站都选择php或java呢?就是因为微软不够开放,没有提供从硬件到应用服务器再到业务应用的整套解决方案。

小妖女 发表于 2015-1-24 21:59:47

逐步缩小出错代码段的范围,最终确定错误代码的位置。

第二个灵魂 发表于 2015-1-25 08:40:55

市场决定一切,我个人从经历上觉得两者至少在很长时间内还是要共存下去,包括C和C++,至少从找工作就看得出来,总不可能大家都像所谓的时尚一样,追捧一门语言并应用它。

爱飞 发表于 2015-2-6 20:11:03

比如封装性、继承性、多态性等等,这就解决了刚才谈到的ASP的那些弱点。封装性使得代码逻辑清晰,易于管理,并且应用到ASP.Net上就可以使业务逻辑和Html页面分离,这样无论页面原型如何改变。

透明 发表于 2015-2-12 22:00:16

弱类型造成潜在的出错可能:尽管弱数据类型的编程语言使用起来回方便一些,但相对于它所造成的出错几率是远远得不偿失的。

蒙在股里 发表于 2015-2-27 10:50:07

提供基于组件、事件驱动的可编程网络表单,大大简化了编程。还可以用ASP.NET建立网络服务。

莫相离 发表于 2015-3-9 01:06:36

它可通过内置的组件实现更强大的功能,如使用A-DO可以轻松地访问数据库。

活着的死人 发表于 2015-3-16 19:11:18

它可通过内置的组件实现更强大的功能,如使用A-DO可以轻松地访问数据库。

谁可相欹 发表于 2015-3-22 23:43:39

HTML:当然这是网页最基本的语言,每一个服务器语言都需要它的支持,要学习,这个肯定是开始,不说了.

简单生活 发表于 2015-3-25 07:18:32

ASP.Net和ASP的最大区别在于编程思维的转换,而不仅仅在于功能的增强。ASP使用VBS/JS这样的脚本语言混合html来编程,而那些脚本语言属于弱类型、面向结构的编程语言,而非面向对象。

精灵巫婆 发表于 2015-3-31 01:56:22

可以通过在现有ASP应用程序中逐渐添加ASP.NET功能,随时增强ASP应用程序的功能。ASP.NET是一个已编译的、基于.NET的环境,可以用任何与.NET兼容的语言(包括VisualBasic.NET、C#和JScript.NET.)创作应用程序。另外,任何ASP.NET应用程序都可以使用整个.NETFramework。开发人员可以方便地获得这些技术的优点,其中包括托管的公共语言运行库环境、类型安全、继承等等。

飘灵儿 发表于 2015-4-3 03:10:22

如今主流的Web服务器软件主要由IIS或Apache组成。IIS支持ASP且只能运行在Windows平台下,Apache支持PHP,CGI,JSP且可运行于多种平台,虽然Apache是世界使用排名第一的Web服务器平台。

山那边是海 发表于 2015-4-5 00:04:38

有一丝可惜的是,这个系列太强了,Java阵营的朋友根本就是哑口无言...争论之火瞬间被浇灭,这不是我想这么早就看到的,但是值了。

分手快乐 发表于 2015-4-5 02:40:57

众所周知,Windows以易用而出名,也因此占据不少的服务器市场。

飘飘悠悠 发表于 2015-4-14 00:09:56

代码的可重用性差:由于是面向结构的编程方式,并且混合html,所以可能页面原型修改一点,整个程序都需要修改,更别提代码重用了。

愤怒的大鸟 发表于 2015-4-29 16:25:22

ASP.net1.1和2.0在程序上的语法也有很大不同,现在2.0属于新出来的,不知道半年后会不会有3.0(说笑一下)。Windows2003系统自动支持ASP和ASP.net环境,不用安装任何程序。Asp.net属于编译语言。ASP的最大不同(ASP属于解释语言)。

若相依 发表于 2015-5-7 13:34:53

asp.net最主要特性包括:◆编程代码更简洁◆网站可实现的功能更强大◆运行效率高◆节省服务器的动作资源
页: [1]
查看完整版本: ASP.NET编程:两个粒度看Asp.net性命周期仓酷云