ºÝºÝߣ

ºÝºÝߣShare a Scribd company logo
UNDERSTANDING  ASP.NETUNDER THE COVERSMiguel A. Castromiguel.castro@idesign.net
AgendaDefining ASP.NETTerms & BuzzwordsA Request-to-Response WalkthroughAdditional TechnologiesSummary
inetaMiguel A. Castro.NET Architect, Developer, & Trainer
 Microsoft MVP
 ASP Insider
 Member of the INETA Speakers Bureau
 Conference Speaker
 Creator of CodeBreeze
 In IT business since 1986AgendaDefining ASP.NETTerms & BuzzwordsA Request-to-Response WalkthroughAdditional TechnologiesSummary
Classic ASPInterpreted languageIncluded embedded scripting code mixed into HTMLLimited to VBScriptRan in the same process as IISInherently not scalable (needed MTS)End of line
Classic ASPEnd of line
Walking UprightDesigned by Scott Guthrie & Mark AndersEarly iteration of ASP.NETOriginally known as XSPNot .NET-related ¨C Java based !Became ASP+ with the design of the CLRRewritten in C#Renamed when .NET branding introducedEnd of line
What is ASP.NETA framework for developing and delivering information & applications on the web.Known primarily as a page framework.A complete Request/Response management system.Can handle and respond to all sorts of requests on the Internet (or an Intranet).Not a language !End of line
Characteristics of ASP.NETRuns under its own worker process.No longer tied to IIS.Code execution managed by CLR.Code-Behind model allows code separation.Includes state handling facilities.Provides caching functionality.End of line
AgendaDefining ASP.NETTerms & BuzzwordsA Request-to-Response WalkthroughAdditional TechnologiesSummary
Commonly Used TermsRequestAn HTTP query initiated by a client to a server for the purpose of performing some action.ResponseA stream of information sent back to a client from the HTTP server that processed the client¡¯s request.ASP.NET PipelineA series of extensible functionality points which continue the process of a request in order to eventually obtain a response.End of line
Commonly Used TermsPage LifecycleAnother series of functionality points that form the process of converting an ASPX page to HTML output.The entire page lifecycle occurs between two pipeline points.Control ModelThe heart of how ASP.NET builds HTML from compiled classes that represent visual components.End of line
Commonly Used TermsHTTP HandlersClasses that are the target of HTTP requests.Assigned by file extension & verb.Map to ISAPI ExtensionsHTTP ModulesClasses that inject mode into the pipeline.Map to ISAPI FiltersMVCAn design pattern that separates the output design from the information that builds it.End of line
AgendaDefining ASP.NETTerms & BuzzwordsA Request-to-Response WalkthroughAdditional TechnologiesSummary
What Everyone SeesDesktop BrowserWeb Server (IIS)http://www.microsoft.com/default.aspxRendered HTMLNow the long version¡­End of line
Getting it to .NET (the low level stuff)Web Server (IIS)Web Server (IIS)Kernel Mode Driver:Http API used by IIShttp.sysWorker Process(w3wp.exe) ¨C (one per app pool)Worker Process started (one per pool) and if needed, AppDomain is created.aspnet_isapi.dllAppDomain(one per site/VD)Attached to the extension of the request.Unmanaged DLL that loads the CLR and routes requests to the managed runtime classes via COM-compliant interfaces. ISAPIRuntime(ProcessRequest method)HttpRuntime.ProcessRequestRequest sent to the ASP.NET runtime for processing.End of line
ASP.NET Takes OverHttpRuntime.ProcessRequest Accessible from now until the end of the request processing.  Accessible through HttpContext.CurrentHttpContext created.This serves as an entry point into the request, response, and other accessible variables.Each AppDomain manages multiple instances so they do not conflict with each other (different users or same user with more than one request).An HttpApplication instance is created.HttpApplicationThis is where it starts to mean something to you, the developer.Init method starts pipeline processing.End of line
Entering the PipelinePipeline kicked off in the Init method.HttpApplicationBeginRequestPerforms event processing.AuthenticateRequest / PostAuthorizeRequest / PostChecks hooks from Global.asax class.ResolveRequestCache / PostChecks hooks from external HTTP Modules.MapRequestHandler / PostAcquireRequestState / PostPreRequestHandlerExecute / PostReleaseRequestState / PostUpdateRequestCache / PostLogRequest / PostEndRequestPreSendRequestHeadersPreSendRequestContentEnd of line
Entering the PipelineHttpApplicationBeginRequestAuthenticateRequest / PostAuthorizeRequest / PostResolveRequestCache / PostMapRequestHandler / PostAcquireRequestState / PostPreRequestHandlerExecute / PostReleaseRequestState / PostUpdateRequestCache / PostLogRequest / PostEndRequestPreSendRequestHeadersPreSendRequestContentEnd of line
Pipeline Events of InterestHttpApplicationProvide URL-Rewriting functionality.BeginRequestAuthenticateRequest / PostRepopulate HttpContext.Current.User with stored principal.Page authentication occurs here.AuthorizeRequest / PostResolveRequestCache / PostMapRequestHandler / PostAcquireRequestState / PostPreRequestHandlerExecute / PostDetermine whether to use cached response.ReleaseRequestState / PostUpdateRequestCache / PostAny event can be hooked in Global.asax or in an HTTP Module.LogRequest / PostEndRequestPreSendRequestHeadersPreSendRequestContentEnd of line
HTTP ModulesClasses that implement IHttpModule.MyModule : IHttpModuleDelegate-based Properties in HttpApplication instance can be wired up.Method functionality equivalent to hooking event in Global.asaxEvent hooks in modules checked during pipeline processing.End of line
AuthenticateRequestWindowsAuthenticationModuleFormsAuthenticationModuleUrlAuthenticationModuleFileAuthorizationModuleServiceModelSessionStateModuleOutputCacheModuleAuthenticateRequestEndRequestAuthorizeRequestAuthorizeRequestPostAuthenticateRequestAcquireRequestStateAcquireRequestStateReleaseRequestStateEndRequestASP.NET HTTP Modules of InterestEnd of line
Module InstallationAny level in the Config chainYou do know what the Config chain is, right?End of line
The Process ContinuesHttpApplicationJust before this event:Proper HTTP Handler located based on request¡¯s extension.BeginRequestAuthenticateRequest / PostHandlers provide necessary processing in order to create a response.AuthorizeRequest / PostResolveRequestCache / PostMapRequestHandler / PostAcquireRequestState / PostPreRequestHandlerExecute / PostReleaseRequestState / PostUpdateRequestCache / PostLogRequest / PostEndRequestPreSendRequestHeadersPreSendRequestContentEnd of line
HTTP HandlersClasses that implement IHttpHandler.Determines if the handler instance can be reused by another request.MyHandler : IHttpHandlerFunctionality assigned to this particular handler.Remember the HttpContext contains all accessible variables, including Response.End of line
HTTP Handler FactoriesCan also implement IHttpHandlerFactory.Allows the instantiation of any handler based on specific conditioning scenarios.MyHandlerFactory : IHttpHandlerFactoryEnd of line
Characteristics of an HTTP HandlerAccess to current HttpContext.Request is in there (as is the Response) !Handlers are wired to extensions (aspx, etc.).Every handler is responsible for what the response is going to be for a request.ASPX requests expect an HTML response.Config requests expect a ¡°forbidden¡± response.End of line
Handler ExecutionHttpApplicationBeginRequestAuthenticateRequest / PostAuthorizeRequest / PostThe determined handler is processed between the PreRequestHandlerExecute and PostRequestHandlerExecute.ResolveRequestCache / PostMapRequestHandler / PostAcquireRequestState / PostPreRequestHandlerExecute / PostReleaseRequestState / PostUpdateRequestCache / PostLogRequest / PostEndRequestPreSendRequestHeadersPreSendRequestContentEnd of line
Handler InstallationHandler factory that returns and executes the handler that will convert an ASPX page to HTML output.Any level in the Config chainEnd of line
The PageHandlerFactory ClassImplements IHttpHandlerFactory.GetHandler method returns an IHttpHandler in the form of System.Web.UI.Page-derived class hierarchy.Page class implements IHttpHandler.Page class inherits from Control.Control contains events/methods for the ¡°Page Event Lifecycle¡±.PageHandlerFactory creates a class structure out of your request.End of line
Page Class StructureFollows the structure of an ASP.NET Server Control.Referred to as Page-Gen Class.Created by the PageHandlerFactory classVirtual class created from ASPX page.Controls created based on ASPX content.inheritsPartial class with control declarations (class name same as code-behind).partials withCode-behind class is other side of partial class.This is why you can tap into events from your code-behind.inheritsProcessRequest method calls lifecycle events in Control.System.Web.UI.PageinheritsimplementsSystem.Web.UI.ControlIHttpHandlerEnd of line
Page Class StructureCreated by the PageHandlerFactory classVirtual class created from ASPX page.inheritsPartial class with control declarations (class name same as code-behind).partials withCode-behind class is other side of partial class.inheritsSystem.Web.UI.PageinheritsimplementsSystem.Web.UI.ControlIHttpHandlerEnd of line
Virtual ClassCreated from ASPX contentDetermines language to be used to generate page-gen class.Specifies the partial class to serve as the code-behind.Optional:Name of the code-file for Visual Studio.End of line
Virtual ClassCreated from ASPX contentLiteralControlConverted to instances of System.Web.UI.LiteralControlthat are added to the control tree of this class.Remember, this class will ultimately inherit from System.Web.UI.ControlLiteralControlLiteralControlLiteralControlLiteralControlLiteralControlEnd of line
Virtual ClassCreated from ASPX contentLiteralControlLiteralControlProgram code directly added to virtual class.LiteralControlLiteralControlLiteralControlLiteralControlLiteralControlEnd of line
Virtual ClassCreated from ASPX contentLiteralControlConverted to instances of the corresponding server control class for each of these control tags, that will be added to the control tree of this class.LiteralControlThe Form control instance is placed directly in the control tree of the class being created; while the TextBox and Label controls are added to the control tree of the Form control.LiteralControlLiteralControlLiteralControlLiteralControlLiteralControlEnd of line
Virtual ClassCreated from ASPX contentLiteralControl¡°asp¡± tag-prefix located in config file or Register directive.LiteralControlClass with tag name located in appropriate namespace and assembly.LiteralControlLiteralControlLiteralControlLiteralControlLiteralControlEnd of line
Virtual ClassCreated from ASPX content__PAGE  System.Web.UI.PageLiteralControlctrl0  System.Web.UI.LiteralControlLiteralControlFunction CodeRemember: this class ¡°ultimately¡± inherits from System.Web.UI.Pagectrl1  System.Web.UI.LiteralControlform1  System.Web.UI.HtmlControls.HtmlFormLiteralControlctrl2  System.Web.UI.LiteralControlControl IDsTextBox1  System.Web.UI.WebControls.TextBoxLiteralControlctrl3  System.Web.UI.LiteralControlLiteralControlLabel1  System.Web.UI.WebControls.Labelctrl4  System.Web.UI.LiteralControlLiteralControlctrl5  System.Web.UI.LiteralControlLiteralControlEnd of line
Virtual ClassCreated from ASPX contentLiteralControlLiteralControlThis is the next class you¡¯ll see now.LiteralControlLiteralControlLiteralControlLiteralControlLiteralControlEnd of line
Page Class StructureCreated by the PageHandlerFactory classVirtual class created from ASPX page.inheritsPartial class with control declarations (class name same as code-behind).partials withCode-behind class is other side of partial class.inheritsSystem.Web.UI.PageinheritsimplementsSystem.Web.UI.ControlIHttpHandlerEnd of line
Partial ClassBase for virtual class and partial to code-behindNotice the name is the same as the page¡¯s code-behind class.End of line
Page Class StructureCreated by the PageHandlerFactory classVirtual class created from ASPX page.inheritsPartial class with control declarations (class name same as code-behind).partials withCode-behind class is other side of partial class.inheritsSystem.Web.UI.PageinheritsimplementsSystem.Web.UI.ControlIHttpHandlerEnd of line
Code-Behind ClassOther side of the Control Declarations classInheriting from Page gives you access to a control¡¯s event lifecycle.End of line
Page Class StructureCreated by the PageHandlerFactory classVirtual class created from ASPX page.Remember, this entire class hierarchy is the handler returned by the PageHandlerFactory class.It is the HttpApplication pipeline that calls ProcessRequest, kicking off the Page Lifecycle.inheritsPartial class with control declarations (class name same as code-behind).ProcessRequest comes from here.  It is from there that the lifecycle events are called.Events for the lifecycle come from here.partials withCode-behind class is other side of partial class.inheritsSystem.Web.UI.PageinheritsimplementsSystem.Web.UI.ControlIHttpHandlerEnd of line
Page (Control) LifecyclePreInitInitInitCompleteCreateChildControls (IsPostBack)LoadViewState/LoadControlStateIPostBackDataHandler.LoadPostDataPreLoadLoadIPostBackDataHandler.RaisePostBackChangedEventIPostBackEventHandler.RaisePostBackEventLoadCompleteCreateChildControls (!IsPostBack)PreRenderDataBindPreRenderCompleteSaveViewState/SaveControlStateRenderUnloadComplete ListEnd of line
Most Commonly Known PointsPostback onlyInitialize:OnInit method and Init eventBegin tracking ViewState:TrackViewState methodLoad View State:LoadViewState methodLoad Postback Data:IPostBackDataHandler.LoadPostdata methodLoad: OnLoad method and Load eventRaise Changed Events:IPostBackDataHandler.RaisePostBackChangedEvent methodRaise Postback Event:IPostBackEventHandler.RaisePostBackEvent methodPreRender:OnPreRender method and PreRender eventSave View State:SaveViewState methodRender: Render methodUnload:OnUnload method and Unload eventEnd of line
Control RenderingActivated through the Control class¡¯ Render method.Each control is designed to output something to the response buffer.Most controls output HTML.Some controls contain others in their tree.Control rendering involves recursively rendering child controls.Controls don¡¯t need to output anythingScriptManagerEnd of line
Getting a Response¡°Rendering¡± uses an HtmlTextWriter stored in the Response object.Response object is part of HttpContext.Writer sent into Render method.After pipeline complete, contents returned up the chain to aspnet_isapi.dllthen http.sys.Results viewed on browser.End of line
Getting a ResponseYou can intercept and/or write directly to the response using Response.Write.Remember classic ASP?Response.WriteFile can be used to output binary information.Can change content type for compatibility with any type of file.Inform browser what¡¯s coming.End of line
AgendaDefining ASP.NETTerms & BuzzwordsA Request-to-Response WalkthroughAdditional TechnologiesSummary
PostbacksInvoked by controls on form that trigger the form to ¡°post¡±.Another HTTP Request, but of a post-type.Certain lifecycle methods only invoked on postback only.In a postback, the Request object¡¯s Form property contains posted data from HTML elements (using their client IDs).
PostbacksPostback onlyInitialize:OnInit method and Init eventBegin tracking ViewState:TrackViewState methodLoad View State:LoadViewState methodLoad Postback Data:IPostBackDataHandler.LoadPostdata methodLoad: OnLoad method and Load eventRaise Changed Events:IPostBackDataHandler.RaisePostBackChangedEvent methodRaise Postback Event:IPostBackEventHandler.RaisePostBackEvent methodPreRender:OnPreRender method and PreRender eventSave View State:SaveViewState methodRender: Render methodUnload:OnUnload method and Unload eventEnd of line
ASCX User ControlsRegister directive defines tag prefix and name for user control.src points to an ascx file in the current web application.During parsing, virtual class is built just like a page, except the base is called UserControl.Also, added to Page¡¯s Controls collection.UserControl also inherits from Control but does NOT implement IHttpHandler.Usage in an ASPX page (or another ASCX control) is just like a server control.End of line
Master PagesCode-Behind class inherits from MasterPage, which inherits from UserControl.Master directive similar to a Page directive.ASPX page points to a master page file.End of line
Master PagesControl that specifies content to be defined in an ASPX page.Control that wraps content.Each Content control corresponds to a ContentPlaceHolder control.End of line
Master PagesWeb Server (IIS)Desktop BrowserBrowse to Default.aspxPageHandlerFactory commences building of virtual class.MasterPageFile attribute encountered.Parsing shifts to master page file and code-behind.Control tree build and added to virtual class.Parsing returns to ASPX page and Content controls turned to code.Each Content control added to the Controls collection of corresponding ContentPlaceHolder control.End of line
Direct BrowsingNote: you cannot browse directly to an ASCX control or a Master page.End of line
ASHX HandlersSimpleHandlerFactory in charge of returning HTTP Handler.End of line
ASHX HandlersPageHandlerFactory:Parses ASPX file, building virtual class as an HTTP Handler, with ProcessRequest kicking off page lifecycle.SimpleHandlerFactory:Takes this handler code and returns is as HTTP Handler.ProcessRequest called in the pipeline as always.End of line
Themes & SkinsContain server control declarations (without IDs) whose properties overwrite those declared on the ASPX page.Control ¡°registration¡± applies.Either in skin file or in config file.Applied just before Init lifecycle event.Programmatic application MUST be made in PreInit event.Application using Theme attribute occurs last.Application using StyleSheetTheme attribute occurs first.End of line
ASP.NET AjaxMore interactive model.Uses JavaScript to invoke Ajax requests.Web Service (WCF) technology can be used to handle response.Ships with controls and components that encapsulate functionality.Ajax Control Toolkit ¨C ships separatelyCommunity driven and supportedUndergoes Microsoft ScrutinyBetter user experience.End of line
ASP.NET MVCProcess nearly identical to conventional ASP.NET.It¡¯s still ASP.NETUses a URL routing engine to parse URLs and invoke appropriate classes.http://site/controller/action/idPipeline is intercepted by a module tapping into PostResolveRequestCache event.Request is picked up by another handler for processing.Controller classes are sought out and processed (similar to code-behind classes).Appropriate Views parsed and rendered.End of line
Why Custom ModulesBackground processesURL rewriting or routingIdentity persistence for custom providers (or any other kind of persistence)Benchmarking
Why Custom HandlersImage watermarkingDynamic image generationRSS output generationFile denial or protection
Tips & TricksUse your own base page to house common functionality.If overriding On{event} methods, remember that the event-wire-up methods in code-behind fire when you call base On{event}.Example: override OnLoad in a base class, Page_Load in code-behind gets called when you call base.OnLoad.Use <page pageBaseType=   demoRegister your server controls in your Web.Config file.Eliminates repeat registrations in ASPX & ASCX files.Eliminates registrations in Skin files.End of line

More Related Content

Understanding ASP.NET Under The Cover - Miguel A. Castro

  • 1. UNDERSTANDING ASP.NETUNDER THE COVERSMiguel A. Castromiguel.castro@idesign.net
  • 2. AgendaDefining ASP.NETTerms & BuzzwordsA Request-to-Response WalkthroughAdditional TechnologiesSummary
  • 3. inetaMiguel A. Castro.NET Architect, Developer, & Trainer
  • 6. Member of the INETA Speakers Bureau
  • 8. Creator of CodeBreeze
  • 9. In IT business since 1986AgendaDefining ASP.NETTerms & BuzzwordsA Request-to-Response WalkthroughAdditional TechnologiesSummary
  • 10. Classic ASPInterpreted languageIncluded embedded scripting code mixed into HTMLLimited to VBScriptRan in the same process as IISInherently not scalable (needed MTS)End of line
  • 12. Walking UprightDesigned by Scott Guthrie & Mark AndersEarly iteration of ASP.NETOriginally known as XSPNot .NET-related ¨C Java based !Became ASP+ with the design of the CLRRewritten in C#Renamed when .NET branding introducedEnd of line
  • 13. What is ASP.NETA framework for developing and delivering information & applications on the web.Known primarily as a page framework.A complete Request/Response management system.Can handle and respond to all sorts of requests on the Internet (or an Intranet).Not a language !End of line
  • 14. Characteristics of ASP.NETRuns under its own worker process.No longer tied to IIS.Code execution managed by CLR.Code-Behind model allows code separation.Includes state handling facilities.Provides caching functionality.End of line
  • 15. AgendaDefining ASP.NETTerms & BuzzwordsA Request-to-Response WalkthroughAdditional TechnologiesSummary
  • 16. Commonly Used TermsRequestAn HTTP query initiated by a client to a server for the purpose of performing some action.ResponseA stream of information sent back to a client from the HTTP server that processed the client¡¯s request.ASP.NET PipelineA series of extensible functionality points which continue the process of a request in order to eventually obtain a response.End of line
  • 17. Commonly Used TermsPage LifecycleAnother series of functionality points that form the process of converting an ASPX page to HTML output.The entire page lifecycle occurs between two pipeline points.Control ModelThe heart of how ASP.NET builds HTML from compiled classes that represent visual components.End of line
  • 18. Commonly Used TermsHTTP HandlersClasses that are the target of HTTP requests.Assigned by file extension & verb.Map to ISAPI ExtensionsHTTP ModulesClasses that inject mode into the pipeline.Map to ISAPI FiltersMVCAn design pattern that separates the output design from the information that builds it.End of line
  • 19. AgendaDefining ASP.NETTerms & BuzzwordsA Request-to-Response WalkthroughAdditional TechnologiesSummary
  • 20. What Everyone SeesDesktop BrowserWeb Server (IIS)http://www.microsoft.com/default.aspxRendered HTMLNow the long version¡­End of line
  • 21. Getting it to .NET (the low level stuff)Web Server (IIS)Web Server (IIS)Kernel Mode Driver:Http API used by IIShttp.sysWorker Process(w3wp.exe) ¨C (one per app pool)Worker Process started (one per pool) and if needed, AppDomain is created.aspnet_isapi.dllAppDomain(one per site/VD)Attached to the extension of the request.Unmanaged DLL that loads the CLR and routes requests to the managed runtime classes via COM-compliant interfaces. ISAPIRuntime(ProcessRequest method)HttpRuntime.ProcessRequestRequest sent to the ASP.NET runtime for processing.End of line
  • 22. ASP.NET Takes OverHttpRuntime.ProcessRequest Accessible from now until the end of the request processing. Accessible through HttpContext.CurrentHttpContext created.This serves as an entry point into the request, response, and other accessible variables.Each AppDomain manages multiple instances so they do not conflict with each other (different users or same user with more than one request).An HttpApplication instance is created.HttpApplicationThis is where it starts to mean something to you, the developer.Init method starts pipeline processing.End of line
  • 23. Entering the PipelinePipeline kicked off in the Init method.HttpApplicationBeginRequestPerforms event processing.AuthenticateRequest / PostAuthorizeRequest / PostChecks hooks from Global.asax class.ResolveRequestCache / PostChecks hooks from external HTTP Modules.MapRequestHandler / PostAcquireRequestState / PostPreRequestHandlerExecute / PostReleaseRequestState / PostUpdateRequestCache / PostLogRequest / PostEndRequestPreSendRequestHeadersPreSendRequestContentEnd of line
  • 24. Entering the PipelineHttpApplicationBeginRequestAuthenticateRequest / PostAuthorizeRequest / PostResolveRequestCache / PostMapRequestHandler / PostAcquireRequestState / PostPreRequestHandlerExecute / PostReleaseRequestState / PostUpdateRequestCache / PostLogRequest / PostEndRequestPreSendRequestHeadersPreSendRequestContentEnd of line
  • 25. Pipeline Events of InterestHttpApplicationProvide URL-Rewriting functionality.BeginRequestAuthenticateRequest / PostRepopulate HttpContext.Current.User with stored principal.Page authentication occurs here.AuthorizeRequest / PostResolveRequestCache / PostMapRequestHandler / PostAcquireRequestState / PostPreRequestHandlerExecute / PostDetermine whether to use cached response.ReleaseRequestState / PostUpdateRequestCache / PostAny event can be hooked in Global.asax or in an HTTP Module.LogRequest / PostEndRequestPreSendRequestHeadersPreSendRequestContentEnd of line
  • 26. HTTP ModulesClasses that implement IHttpModule.MyModule : IHttpModuleDelegate-based Properties in HttpApplication instance can be wired up.Method functionality equivalent to hooking event in Global.asaxEvent hooks in modules checked during pipeline processing.End of line
  • 28. Module InstallationAny level in the Config chainYou do know what the Config chain is, right?End of line
  • 29. The Process ContinuesHttpApplicationJust before this event:Proper HTTP Handler located based on request¡¯s extension.BeginRequestAuthenticateRequest / PostHandlers provide necessary processing in order to create a response.AuthorizeRequest / PostResolveRequestCache / PostMapRequestHandler / PostAcquireRequestState / PostPreRequestHandlerExecute / PostReleaseRequestState / PostUpdateRequestCache / PostLogRequest / PostEndRequestPreSendRequestHeadersPreSendRequestContentEnd of line
  • 30. HTTP HandlersClasses that implement IHttpHandler.Determines if the handler instance can be reused by another request.MyHandler : IHttpHandlerFunctionality assigned to this particular handler.Remember the HttpContext contains all accessible variables, including Response.End of line
  • 31. HTTP Handler FactoriesCan also implement IHttpHandlerFactory.Allows the instantiation of any handler based on specific conditioning scenarios.MyHandlerFactory : IHttpHandlerFactoryEnd of line
  • 32. Characteristics of an HTTP HandlerAccess to current HttpContext.Request is in there (as is the Response) !Handlers are wired to extensions (aspx, etc.).Every handler is responsible for what the response is going to be for a request.ASPX requests expect an HTML response.Config requests expect a ¡°forbidden¡± response.End of line
  • 33. Handler ExecutionHttpApplicationBeginRequestAuthenticateRequest / PostAuthorizeRequest / PostThe determined handler is processed between the PreRequestHandlerExecute and PostRequestHandlerExecute.ResolveRequestCache / PostMapRequestHandler / PostAcquireRequestState / PostPreRequestHandlerExecute / PostReleaseRequestState / PostUpdateRequestCache / PostLogRequest / PostEndRequestPreSendRequestHeadersPreSendRequestContentEnd of line
  • 34. Handler InstallationHandler factory that returns and executes the handler that will convert an ASPX page to HTML output.Any level in the Config chainEnd of line
  • 35. The PageHandlerFactory ClassImplements IHttpHandlerFactory.GetHandler method returns an IHttpHandler in the form of System.Web.UI.Page-derived class hierarchy.Page class implements IHttpHandler.Page class inherits from Control.Control contains events/methods for the ¡°Page Event Lifecycle¡±.PageHandlerFactory creates a class structure out of your request.End of line
  • 36. Page Class StructureFollows the structure of an ASP.NET Server Control.Referred to as Page-Gen Class.Created by the PageHandlerFactory classVirtual class created from ASPX page.Controls created based on ASPX content.inheritsPartial class with control declarations (class name same as code-behind).partials withCode-behind class is other side of partial class.This is why you can tap into events from your code-behind.inheritsProcessRequest method calls lifecycle events in Control.System.Web.UI.PageinheritsimplementsSystem.Web.UI.ControlIHttpHandlerEnd of line
  • 37. Page Class StructureCreated by the PageHandlerFactory classVirtual class created from ASPX page.inheritsPartial class with control declarations (class name same as code-behind).partials withCode-behind class is other side of partial class.inheritsSystem.Web.UI.PageinheritsimplementsSystem.Web.UI.ControlIHttpHandlerEnd of line
  • 38. Virtual ClassCreated from ASPX contentDetermines language to be used to generate page-gen class.Specifies the partial class to serve as the code-behind.Optional:Name of the code-file for Visual Studio.End of line
  • 39. Virtual ClassCreated from ASPX contentLiteralControlConverted to instances of System.Web.UI.LiteralControlthat are added to the control tree of this class.Remember, this class will ultimately inherit from System.Web.UI.ControlLiteralControlLiteralControlLiteralControlLiteralControlLiteralControlEnd of line
  • 40. Virtual ClassCreated from ASPX contentLiteralControlLiteralControlProgram code directly added to virtual class.LiteralControlLiteralControlLiteralControlLiteralControlLiteralControlEnd of line
  • 41. Virtual ClassCreated from ASPX contentLiteralControlConverted to instances of the corresponding server control class for each of these control tags, that will be added to the control tree of this class.LiteralControlThe Form control instance is placed directly in the control tree of the class being created; while the TextBox and Label controls are added to the control tree of the Form control.LiteralControlLiteralControlLiteralControlLiteralControlLiteralControlEnd of line
  • 42. Virtual ClassCreated from ASPX contentLiteralControl¡°asp¡± tag-prefix located in config file or Register directive.LiteralControlClass with tag name located in appropriate namespace and assembly.LiteralControlLiteralControlLiteralControlLiteralControlLiteralControlEnd of line
  • 43. Virtual ClassCreated from ASPX content__PAGE System.Web.UI.PageLiteralControlctrl0 System.Web.UI.LiteralControlLiteralControlFunction CodeRemember: this class ¡°ultimately¡± inherits from System.Web.UI.Pagectrl1 System.Web.UI.LiteralControlform1 System.Web.UI.HtmlControls.HtmlFormLiteralControlctrl2 System.Web.UI.LiteralControlControl IDsTextBox1 System.Web.UI.WebControls.TextBoxLiteralControlctrl3 System.Web.UI.LiteralControlLiteralControlLabel1 System.Web.UI.WebControls.Labelctrl4 System.Web.UI.LiteralControlLiteralControlctrl5 System.Web.UI.LiteralControlLiteralControlEnd of line
  • 44. Virtual ClassCreated from ASPX contentLiteralControlLiteralControlThis is the next class you¡¯ll see now.LiteralControlLiteralControlLiteralControlLiteralControlLiteralControlEnd of line
  • 45. Page Class StructureCreated by the PageHandlerFactory classVirtual class created from ASPX page.inheritsPartial class with control declarations (class name same as code-behind).partials withCode-behind class is other side of partial class.inheritsSystem.Web.UI.PageinheritsimplementsSystem.Web.UI.ControlIHttpHandlerEnd of line
  • 46. Partial ClassBase for virtual class and partial to code-behindNotice the name is the same as the page¡¯s code-behind class.End of line
  • 47. Page Class StructureCreated by the PageHandlerFactory classVirtual class created from ASPX page.inheritsPartial class with control declarations (class name same as code-behind).partials withCode-behind class is other side of partial class.inheritsSystem.Web.UI.PageinheritsimplementsSystem.Web.UI.ControlIHttpHandlerEnd of line
  • 48. Code-Behind ClassOther side of the Control Declarations classInheriting from Page gives you access to a control¡¯s event lifecycle.End of line
  • 49. Page Class StructureCreated by the PageHandlerFactory classVirtual class created from ASPX page.Remember, this entire class hierarchy is the handler returned by the PageHandlerFactory class.It is the HttpApplication pipeline that calls ProcessRequest, kicking off the Page Lifecycle.inheritsPartial class with control declarations (class name same as code-behind).ProcessRequest comes from here. It is from there that the lifecycle events are called.Events for the lifecycle come from here.partials withCode-behind class is other side of partial class.inheritsSystem.Web.UI.PageinheritsimplementsSystem.Web.UI.ControlIHttpHandlerEnd of line
  • 50. Page (Control) LifecyclePreInitInitInitCompleteCreateChildControls (IsPostBack)LoadViewState/LoadControlStateIPostBackDataHandler.LoadPostDataPreLoadLoadIPostBackDataHandler.RaisePostBackChangedEventIPostBackEventHandler.RaisePostBackEventLoadCompleteCreateChildControls (!IsPostBack)PreRenderDataBindPreRenderCompleteSaveViewState/SaveControlStateRenderUnloadComplete ListEnd of line
  • 51. Most Commonly Known PointsPostback onlyInitialize:OnInit method and Init eventBegin tracking ViewState:TrackViewState methodLoad View State:LoadViewState methodLoad Postback Data:IPostBackDataHandler.LoadPostdata methodLoad: OnLoad method and Load eventRaise Changed Events:IPostBackDataHandler.RaisePostBackChangedEvent methodRaise Postback Event:IPostBackEventHandler.RaisePostBackEvent methodPreRender:OnPreRender method and PreRender eventSave View State:SaveViewState methodRender: Render methodUnload:OnUnload method and Unload eventEnd of line
  • 52. Control RenderingActivated through the Control class¡¯ Render method.Each control is designed to output something to the response buffer.Most controls output HTML.Some controls contain others in their tree.Control rendering involves recursively rendering child controls.Controls don¡¯t need to output anythingScriptManagerEnd of line
  • 53. Getting a Response¡°Rendering¡± uses an HtmlTextWriter stored in the Response object.Response object is part of HttpContext.Writer sent into Render method.After pipeline complete, contents returned up the chain to aspnet_isapi.dllthen http.sys.Results viewed on browser.End of line
  • 54. Getting a ResponseYou can intercept and/or write directly to the response using Response.Write.Remember classic ASP?Response.WriteFile can be used to output binary information.Can change content type for compatibility with any type of file.Inform browser what¡¯s coming.End of line
  • 55. AgendaDefining ASP.NETTerms & BuzzwordsA Request-to-Response WalkthroughAdditional TechnologiesSummary
  • 56. PostbacksInvoked by controls on form that trigger the form to ¡°post¡±.Another HTTP Request, but of a post-type.Certain lifecycle methods only invoked on postback only.In a postback, the Request object¡¯s Form property contains posted data from HTML elements (using their client IDs).
  • 57. PostbacksPostback onlyInitialize:OnInit method and Init eventBegin tracking ViewState:TrackViewState methodLoad View State:LoadViewState methodLoad Postback Data:IPostBackDataHandler.LoadPostdata methodLoad: OnLoad method and Load eventRaise Changed Events:IPostBackDataHandler.RaisePostBackChangedEvent methodRaise Postback Event:IPostBackEventHandler.RaisePostBackEvent methodPreRender:OnPreRender method and PreRender eventSave View State:SaveViewState methodRender: Render methodUnload:OnUnload method and Unload eventEnd of line
  • 58. ASCX User ControlsRegister directive defines tag prefix and name for user control.src points to an ascx file in the current web application.During parsing, virtual class is built just like a page, except the base is called UserControl.Also, added to Page¡¯s Controls collection.UserControl also inherits from Control but does NOT implement IHttpHandler.Usage in an ASPX page (or another ASCX control) is just like a server control.End of line
  • 59. Master PagesCode-Behind class inherits from MasterPage, which inherits from UserControl.Master directive similar to a Page directive.ASPX page points to a master page file.End of line
  • 60. Master PagesControl that specifies content to be defined in an ASPX page.Control that wraps content.Each Content control corresponds to a ContentPlaceHolder control.End of line
  • 61. Master PagesWeb Server (IIS)Desktop BrowserBrowse to Default.aspxPageHandlerFactory commences building of virtual class.MasterPageFile attribute encountered.Parsing shifts to master page file and code-behind.Control tree build and added to virtual class.Parsing returns to ASPX page and Content controls turned to code.Each Content control added to the Controls collection of corresponding ContentPlaceHolder control.End of line
  • 62. Direct BrowsingNote: you cannot browse directly to an ASCX control or a Master page.End of line
  • 63. ASHX HandlersSimpleHandlerFactory in charge of returning HTTP Handler.End of line
  • 64. ASHX HandlersPageHandlerFactory:Parses ASPX file, building virtual class as an HTTP Handler, with ProcessRequest kicking off page lifecycle.SimpleHandlerFactory:Takes this handler code and returns is as HTTP Handler.ProcessRequest called in the pipeline as always.End of line
  • 65. Themes & SkinsContain server control declarations (without IDs) whose properties overwrite those declared on the ASPX page.Control ¡°registration¡± applies.Either in skin file or in config file.Applied just before Init lifecycle event.Programmatic application MUST be made in PreInit event.Application using Theme attribute occurs last.Application using StyleSheetTheme attribute occurs first.End of line
  • 66. ASP.NET AjaxMore interactive model.Uses JavaScript to invoke Ajax requests.Web Service (WCF) technology can be used to handle response.Ships with controls and components that encapsulate functionality.Ajax Control Toolkit ¨C ships separatelyCommunity driven and supportedUndergoes Microsoft ScrutinyBetter user experience.End of line
  • 67. ASP.NET MVCProcess nearly identical to conventional ASP.NET.It¡¯s still ASP.NETUses a URL routing engine to parse URLs and invoke appropriate classes.http://site/controller/action/idPipeline is intercepted by a module tapping into PostResolveRequestCache event.Request is picked up by another handler for processing.Controller classes are sought out and processed (similar to code-behind classes).Appropriate Views parsed and rendered.End of line
  • 68. Why Custom ModulesBackground processesURL rewriting or routingIdentity persistence for custom providers (or any other kind of persistence)Benchmarking
  • 69. Why Custom HandlersImage watermarkingDynamic image generationRSS output generationFile denial or protection
  • 70. Tips & TricksUse your own base page to house common functionality.If overriding On{event} methods, remember that the event-wire-up methods in code-behind fire when you call base On{event}.Example: override OnLoad in a base class, Page_Load in code-behind gets called when you call base.OnLoad.Use <page pageBaseType= demoRegister your server controls in your Web.Config file.Eliminates repeat registrations in ASPX & ASCX files.Eliminates registrations in Skin files.End of line
  • 71. Tips & TricksRemove HTTP Modules that you don¡¯t needIf file protection necessary, add file extension (ZIP) to registered extensions in IIS.Bring them into the pipeline for protection and controlled exposure.Presentation available on my site.End of line
  • 72. Tips & TricksTurn ViewState off in controls that don¡¯t need them ¨C especially grids.In 4.0 the model can be reversed.More compact in 4.0.Override LoadPageStateFromPersistenceMedium & SavePageStateToPersistenceMedium to alter where and how ViewState is saved.
  • 73. Tips & TricksDeployment ModeIn <system.web><deployment retail=¡°true¡± />Turns debugging, tracing, and detailed errors OFFMachine.Config ONLYWay AdvancedPageParserFilter abstract base classLets you govern the behavior of the ASP.NET Page Parser
  • 74. AgendaDefining ASP.NETTerms & BuzzwordsA Request-to-Response WalkthroughAdditional TechnologiesSummary
  • 75. What To Take Away From ThisASP.NET does much more than serve pages.Decoupled architecture allows flexible hosting.Pipeline and Event cycle ¨C two different things.Extensible architecture allows opportunities for interception and alteration.Module and Handler model enforce encapsulation and reusability.Be mindful of how much is happenning behind the scenes.End of line
  • 76. ReferencesGreat Wikipedia entryhttp://en.wikipedia.org/wiki/ASP+Article: How ASP.NET Workshttp://www.west-wind.com/presentations/howaspnetworks/howaspnetworks.aspCode Magazine ¨C Nov/Dec 2005Rick Strahl
  • 77. ReferencesArticle: Truly Understanding ViewStatehttp://weblogs.asp.net/infinitiesloop/archive/2006/08/03/truly-understanding-viewstate.aspxDave ReedUnderstanding ASP.NET Internalshttp://grokable.com/teched-2007-presentation-slides-and-demos/Rob Howard
  • 78. Essential ASP.NET 2.0Addison-WesleyFritz Onion & Keith BrownMy Site & Email:www.dotnetdude.com miguel.castro@idesign.net