Understanding ASP.NET Under The Cover - Miguel A. Castro
-
Upload
mohammad-tayseer -
Category
Documents
-
view
9.807 -
download
1
Transcript of Understanding ASP.NET Under The Cover - Miguel A. Castro
Agenda
Defining ASP.NET
Terms & Buzzwords
A Request-to-Response Walkthrough
Additional Technologies
Summary
Miguel A. Castro
ineta
.NET Architect, Developer, & Trainer Microsoft MVP ASP Insider Member of the INETA Speakers Bureau Conference Speaker Creator of CodeBreeze In IT business since 1986
Your Speaker
Miguel A. Castro
ineta
.NET Architect, Developer, & Trainer Microsoft MVP ASP Insider Member of the INETA Speakers Bureau Conference Speaker Creator of CodeBreeze In IT business since 1986
Agenda
Defining ASP.NET
Terms & Buzzwords
A Request-to-Response Walkthrough
Additional Technologies
Summary
Classic ASP
• Interpreted language• Included embedded scripting code mixed
into HTML• Limited to VBScript• Ran in the same process as IIS• Inherently not scalable (needed MTS)
End of line
Walking Upright
• Designed by Scott Guthrie & Mark Anders• Early iteration of ASP.NET• Originally known as XSP
– Not .NET-related – Java based !
• Became ASP+ with the design of the CLR– Rewritten in C#
• Renamed when .NET branding introduced
End of line
What is ASP.NET
• A 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.NET
• Runs 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
Agenda
Terms & Buzzwords
Defining ASP.NET
A Request-to-Response Walkthrough
Additional Technologies
Summary
Commonly Used Terms
• Request– An HTTP query initiated by a client to a server for
the purpose of performing some action.
• Response– A stream of information sent back to a client from
the HTTP server that processed the client’s request.
• ASP.NET Pipeline– A series of extensible functionality points which
continue the process of a request in order to eventually obtain a response.
End of line
Commonly Used Terms
• Page Lifecycle– Another 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 Model– The heart of how ASP.NET builds HTML from
compiled classes that represent visual components.
End of line
Agenda
A Request-to-Response Walkthrough
Defining ASP.NET
Terms & Buzzwords
Additional Technologies
Summary
What Everyone SeesDesktop Browser
http://www.microsoft.com/default.aspx
Web Server (IIS)
Convert ASPX to HTML
Rendered HTML
Now the long version…
End of line
Web Server (IIS)
Convert ASPX to HTML
Getting it to .NET (the low level stuff)
Web Server (IIS)
http.sys
Worker Process(w3wp.exe) – (one per app pool)
aspnet_isapi.dll
Kernel Mode Driver:Http API used by IIS
Worker Process started (one per pool)
and if needed, AppDomain is created.
AppDomain(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.
End of line
ISAPIRuntime(ProcessRequest method)
HttpRuntime.ProcessRequest
Request sent to the ASP.NET runtime for processing.
ASP.NET Takes Over
HttpRuntime.ProcessRequest
HttpContext created.This serves as an entry point into the request, response, and other
accessible variables.
Accessible from now until the end of the request processing.
Accessible through HttpContext.Current
An HttpApplication instance is created.
HttpApplication
Init method starts pipeline processing.
This is where it starts to mean something to you,
the developer.
Each AppDomain manages multiple instances so they do not conflict with each other
(different users or same user with more than one request).
End of line
Entering the Pipeline
Pipeline kicked off in the Init method. HttpApplication
Performs event processing.
Checks hooks from Global.asax class.
Checks hooks from external HTTP Modules.
BeginRequest
AuthenticateRequest / Post
AuthorizeRequest / Post
ResolveRequestCache / Post
MapRequestHandler / Post
AcquireRequestState / Post
PreRequestHandlerExecute / Post
ReleaseRequestState / Post
UpdateRequestCache / Post
LogRequest / Post
EndRequest
PreSendRequestHeaders
PreSendRequestContent
End of line
Entering the Pipeline
HttpApplication
BeginRequest
AuthenticateRequest / Post
AuthorizeRequest / Post
ResolveRequestCache / Post
MapRequestHandler / Post
AcquireRequestState / Post
PreRequestHandlerExecute / Post
ReleaseRequestState / Post
UpdateRequestCache / Post
LogRequest / Post
EndRequest
PreSendRequestHeaders
PreSendRequestContent
End of line
Pipeline Events of Interest
HttpApplication
BeginRequest
AuthenticateRequest / Post
AuthorizeRequest / Post
ResolveRequestCache / Post
MapRequestHandler / Post
AcquireRequestState / Post
PreRequestHandlerExecute / Post
ReleaseRequestState / Post
UpdateRequestCache / Post
LogRequest / Post
EndRequest
PreSendRequestHeaders
PreSendRequestContent
Determine whether to use cached response.
Provide URL-Rewriting functionality.
Repopulate HttpContext.Current.User with
stored principal.
Page authentication occurs here.
End of line
Any event can be hooked in
Global.asax or in an HTTP Module.
HTTP Modules
• Classes that implement IHttpModule.MyModule : IHttpModule
Delegate-based Properties in HttpApplication instance
can be wired up.
Method functionality equivalent to hooking event
in Global.asax
Event hooks in modules checked
during pipeline processing.
End of line
• WindowsAuthenticationModule• FormsAuthenticationModule• UrlAuthenticationModule• FileAuthorizationModule• ServiceModel• SessionStateModule• OutputCacheModule
AuthenticateRequest
AuthenticateRequest
EndRequest
AuthorizeRequest
AuthorizeRequest
PostAuthenticateRequest
AcquireRequestState
ReleaseRequestState
EndRequest
AcquireRequestState
ASP.NET HTTP Modules of Interest
End of line
Module Installation
Any level in the Config chain
You do know what the Config chain is, right?
End of line
The Process Continues
HttpApplication
BeginRequest
AuthenticateRequest / Post
AuthorizeRequest / Post
ResolveRequestCache / Post
MapRequestHandler / Post
AcquireRequestState / Post
PreRequestHandlerExecute / Post
ReleaseRequestState / Post
UpdateRequestCache / Post
LogRequest / Post
EndRequest
PreSendRequestHeaders
PreSendRequestContent
Just before this event:Proper HTTP Handler located based on request’s extension.
End of line
Handlers provide necessary processing in order to create a response.
HTTP Handlers
• Classes that implement IHttpHandler.
MyHandler : IHttpHandler Determines if the handler instance can be reused by
another request.
Functionality assigned to this particular handler.
Remember the HttpContext contains
all accessible variables, including
Response.
End of line
HTTP Handler Factories
• Can also implement IHttpHandlerFactory.
MyHandlerFactory : IHttpHandlerFactory Allows the instantiation of any handler based on specific
conditioning scenarios.
End of line
Characteristics of an HTTP Handler
• Access 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 Execution
HttpApplication
BeginRequest
AuthenticateRequest / Post
AuthorizeRequest / Post
ResolveRequestCache / Post
MapRequestHandler / Post
AcquireRequestState / Post
PreRequestHandlerExecute / Post
ReleaseRequestState / Post
UpdateRequestCache / Post
LogRequest / Post
EndRequest
PreSendRequestHeaders
PreSendRequestContent
The determined handler is processed between the
PreRequestHandlerExecute and
PostRequestHandlerExecute.
End of line
Handler Installation
Any level in the Config chain
End of line
Handler factory that returns and executes the handler that will
convert an ASPX page to HTML output.
The PageHandlerFactory Class
• Implements 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 StructureCreated by the PageHandlerFactory class
Virtual class created from ASPX page.
Partial class with control declarations (class name same as code-behind).
Code-behind class is other side of partial class.
System.Web.UI.Page
System.Web.UI.Control IHttpHandler
inherits
partials with
inherits
inherits implements
Follows the structure of an ASP.NET Server Control.Referred to as Page-Gen
Class.
Controls created based on ASPX
content.
This is why you can tap into
events from your code-behind. ProcessRequest
method calls lifecycle events in
Control.
End of line
Page Class StructureCreated by the PageHandlerFactory class
Virtual class created from ASPX page.
Partial class with control declarations (class name same as code-behind).
Code-behind class is other side of partial class.
System.Web.UI.Page
System.Web.UI.Control IHttpHandler
inherits
partials with
inherits
inherits implements
End of line
Virtual ClassCreated from ASPX content
Determines 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 content
LiteralControl
End of line
LiteralControl
LiteralControl
LiteralControl
LiteralControl
LiteralControl
Converted to instances of System.Web.UI.LiteralControl
that are added to the control tree of this class.Remember, this class will ultimately inherit from
System.Web.UI.Control
Virtual ClassCreated from ASPX content
LiteralControl
End of line
LiteralControl
LiteralControl
LiteralControl
LiteralControl
LiteralControl
LiteralControl
Program code directly added to virtual class.
Virtual ClassCreated from ASPX content
LiteralControl
End of line
LiteralControl
LiteralControl
LiteralControl
LiteralControl
LiteralControl
LiteralControl
Converted 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. The 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.
Virtual ClassCreated from ASPX content
LiteralControl
End of line
LiteralControl
LiteralControl
LiteralControl
LiteralControl
LiteralControl
LiteralControl
“asp” tag-prefix located in config file or Register directive.
Class with tag name located in appropriate namespace and assembly.
Virtual ClassCreated from ASPX content
LiteralControl
LiteralControl
End of line
LiteralControl
LiteralControl
LiteralControl
LiteralControl
LiteralControl
__PAGE System.Web.UI.Page
ctrl0 System.Web.UI.LiteralControl
Function Code
ctrl1 System.Web.UI.LiteralControl
form1 System.Web.UI.HtmlControls.HtmlForm
ctrl2 System.Web.UI.LiteralControl
TextBox1 System.Web.UI.WebControls.TextBox
ctrl3 System.Web.UI.LiteralControl
Label1 System.Web.UI.WebControls.Label
ctrl4 System.Web.UI.LiteralControl
ctrl5 System.Web.UI.LiteralControl
Remember: this class “ultimately” inherits from System.Web.UI.Page
Control IDs
Virtual ClassCreated from ASPX content
LiteralControl
LiteralControl
End of line
LiteralControl
LiteralControl
LiteralControl
LiteralControl
LiteralControl
This is the next class you’ll see now.
Page Class StructureCreated by the PageHandlerFactory class
Virtual class created from ASPX page.
Partial class with control declarations (class name same as code-behind).
Code-behind class is other side of partial class.
System.Web.UI.Page
System.Web.UI.Control IHttpHandler
inherits
partials with
inherits
inherits implements
End of line
Partial ClassBase for virtual class and partial to code-behind
Notice the name is the same as the page’s code-behind class.
End of line
Page Class StructureCreated by the PageHandlerFactory class
Virtual class created from ASPX page.
Partial class with control declarations (class name same as code-behind).
Code-behind class is other side of partial class.
System.Web.UI.Page
System.Web.UI.Control IHttpHandler
inherits
partials with
inherits
inherits implements
End of line
Code-Behind ClassOther side of the Control Declarations class
Inheriting from Page gives you access to a control’s event lifecycle.
End of line
Page Class StructureCreated by the PageHandlerFactory class
Virtual class created from ASPX page.
Partial class with control declarations (class name same as code-behind).
Code-behind class is other side of partial class.
System.Web.UI.Page
System.Web.UI.Control IHttpHandler
inherits
partials with
inherits
inherits implements
End of line
Events for the lifecycle come
from here.
ProcessRequest comes from here.
It is from there that the lifecycle
events are called.
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.
Page (Control) Lifecycle• PreInit• Init• InitComplete• CreateChildControls (IsPostBack)• LoadViewState/LoadControlState• IPostBackDataHandler.LoadPostData• PreLoad• Load• IPostBackDataHandler.RaisePostBackChangedEvent• IPostBackEventHandler.RaisePostBackEvent• LoadComplete• CreateChildControls (!IsPostBack)• PreRender• DataBind• PreRenderComplete• SaveViewState/SaveControlState• Render• Unload
Complete List
End of line
Most Commonly Known Points
Postback only
Begin tracking ViewState: TrackViewState methodBegin tracking ViewState: TrackViewState method
Load: OnLoad method and Load eventLoad: OnLoad method and Load event
PreRender: OnPreRender method and PreRender eventPreRender: OnPreRender method and PreRender event
Save View State: SaveViewState methodSave View State: SaveViewState method
Render: Render methodRender: Render method
Unload: OnUnload method and Unload eventUnload: OnUnload method and Unload event
Raise Postback Event: IPostBackEventHandler.RaisePostBackEvent methodRaise Postback Event: IPostBackEventHandler.RaisePostBackEvent method
Raise Changed Events: IPostBackDataHandler.RaisePostBackChangedEvent methodRaise Changed Events: IPostBackDataHandler.RaisePostBackChangedEvent method
Load Postback Data: IPostBackDataHandler.LoadPostdata methodLoad Postback Data: IPostBackDataHandler.LoadPostdata method
Load View State: LoadViewState methodLoad View State: LoadViewState method
Initialize: OnInit method and Init eventInitialize: OnInit method and Init event
End of line
Control Rendering
• Activated 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 anything
– ScriptManager
End 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.dll then http.sys.
• Results viewed on browser.
End of line
Agenda
Additional Technologies
Defining ASP.NET
Terms & Buzzwords
A Request-to-Response Walkthrough
Summary
Postbacks
• Invoked 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).
Postbacks
Postback only
Begin tracking ViewState: TrackViewState methodBegin tracking ViewState: TrackViewState method
Load: OnLoad method and Load eventLoad: OnLoad method and Load event
PreRender: OnPreRender method and PreRender eventPreRender: OnPreRender method and PreRender event
Save View State: SaveViewState methodSave View State: SaveViewState method
Render: Render methodRender: Render method
Unload: OnUnload method and Unload eventUnload: OnUnload method and Unload event
Raise Postback Event: IPostBackEventHandler.RaisePostBackEvent methodRaise Postback Event: IPostBackEventHandler.RaisePostBackEvent method
Raise Changed Events: IPostBackDataHandler.RaisePostBackChangedEvent methodRaise Changed Events: IPostBackDataHandler.RaisePostBackChangedEvent method
Load Postback Data: IPostBackDataHandler.LoadPostdata methodLoad Postback Data: IPostBackDataHandler.LoadPostdata method
Load View State: LoadViewState methodLoad View State: LoadViewState method
Initialize: OnInit method and Init eventInitialize: OnInit method and Init event
End of line
ASCX User Controls
Register directive defines tag prefix and name for user control.
src points to an ascx file in the current web application.
Usage in an ASPX page (or another ASCX control) is just
like a server control.
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.
End of line
Master Pages
End of line
Master directive similar to a Page directive.
Code-Behind class inherits from MasterPage, which inherits from
UserControl.
ASPX page points to a master page file.
Master Pages
End of line
Control that specifies content to be defined in
an ASPX page.
Control that wraps content. Each Content control
corresponds to a ContentPlaceHolder control.
Master PagesWeb Server (IIS)Desktop Browser
Browse to Default.aspx
PageHandlerFactory 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 Browsing
End of line
Note: you cannot browse directly to an ASCX control or a Master page.
ASHX Handlers
End of line
SimpleHandlerFactory in charge of returning HTTP Handler.
ASHX Handlers
PageHandlerFactory: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.
End of line
ProcessRequest called in the pipeline as always.
Themes & Skins
• Contain 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 Ajax
• More 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 – ships separately
– Community driven and supported– Undergoes Microsoft Scrutiny
• Better user experience.
End of line
ASP.NET MVC• Process nearly identical to conventional ASP.NET.
– It’s still ASP.NET
• Uses a URL routing engine to parse URLs and invoke appropriate classes.– http://site/controller/action/id
• Pipeline 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 Modules
• Background processes• URL rewriting or routing• Identity persistence for custom providers
(or any other kind of persistence)• Benchmarking
Why Custom Handlers
• Image watermarking• Dynamic image generation• RSS output generation• File denial or protection
Tips & Tricks
• Use 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= demo
• Register your server controls in your Web.Config file.– Eliminates repeat registrations in ASPX & ASCX files.– Eliminates registrations in Skin files.
End of line
Tips & Tricks
• Remove HTTP Modules that you don’t need
• If 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
Tips & Tricks
• Turn ViewState off in controls that don’t need them – 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.
Tips & Tricks
• Deployment Mode– In <system.web>– <deployment retail=“true” />– Turns debugging, tracing, and detailed errors
OFF– Machine.Config ONLY
• Way Advanced– PageParserFilter abstract base class– Lets you govern the behavior of the ASP.NET
Page Parser
Agenda
Summary
Defining ASP.NET
Terms & Buzzwords
A Request-to-Response Walkthrough
Additional Technologies
What To Take Away From This
• ASP.NET does much more than serve pages.• Decoupled architecture allows flexible hosting.• Pipeline and Event cycle – 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
References
• Great Wikipedia entry– http://en.wikipedia.org/wiki/ASP+
• Article: How ASP.NET Works– http://www.west-wind.com/presentations/
howaspnetworks/howaspnetworks.asp– Code Magazine – Nov/Dec 2005– Rick Strahl
References
• Article: Truly Understanding ViewState– http://weblogs.asp.net/infinitiesloop/archive/
2006/08/03/truly-understanding-viewstate.aspx
– Dave Reed
• Understanding ASP.NET Internals– http://grokable.com/teched-2007-
presentation-slides-and-demos/– Rob Howard
References
www.dotnetdude.comwww.steelbluesolutions.com
• Essential ASP.NET 2.0• Addison-Wesley• Fritz Onion & Keith Brown
• My Site & Email:• www.dotnetdude.com • [email protected]