ASP.NET Page Rendering Training


Published on

This slide deck is from an Intertech presentation on ASP.NET Page Rendering delivered at VSLive.

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

ASP.NET Page Rendering Training

  1. 1. The Page Rendering Process Intertech
  2. 2. Overview  Page Type Basics  The ASPX Class File  The Control Base Class  The Control Tree  The Page’s Lifetime  Page Rendering  Custom Rendering  Capturing Rendered Output
  3. 3. The Page Type  Plugs into the request pipeline  Implements IHTTP handler  Responsible for returning a result stream to IIS – The Page class’s return value is typically HTML  Other handlers return other result streams – Web Services return a SOAP message – The remoting handler returns SOAP or binary info
  4. 4. Structure of a Page Type Implementation System.Web.UI.Control System.Web.UI.TemplateControl ASPX Code Page Page Behind Base (Markup) Page Class
  5. 5. Structure of a Page Type Implementation <HTML><HEAD><title>WebForm1</title></HEAD><body> <form id=quot;Form1quot; method=quot;postquot; runat=quot;serverquot;> <asp:Label id=quot;Label3“ runat=quot;serverquot;>User Name</asp:Label> <asp:TextBox id=quot;TextBox1quot; runat=quot;serverquot; /> <asp:Label id=quot;Label2quot; runat=quot;serverquot;>Password</asp:Label> System.Web.UI.Control <asp:TextBox id=quot;TextBox3quot; runat=quot;serverquot; /> <asp:Button id=quot;Button1quot; runat=quot;serverquot; Text=quot;Loginquot; /> <asp:Label id=quot;lblOutputquot; runat=quot;serverquot; /> </form> System.Web.UI.TemplateControl </body></HTML> ASPX Code Page Page Behind Base (Markup) Page Class
  6. 6. Structure of a Page Type Implementation public class WebForm1_aspx : GeekWebApp.WebForm1, System.Web.SessionState.IRequiresSessionState { … private void __BuildControlTree(System.Web.UI.Control __ctrl) { System.Web.UI.Control System.Web.UI.IParserAccessor __parser = ((System.Web.UI.IParserAccessor)(__ctrl)); __parser.AddParsedSubObject(new System.Web.UI.LiteralControl( System.Web.UI.TemplateControl quot;<HTML><HEAD><title>WebForm1</title></HEAD><body>quot;)); this.__BuildControlForm1(); __parser.AddParsedSubObject(this.Form1); ASPX __parser.AddParsedSubObject(new Code Page Page System.Web.UI.LiteralControl( Behind Base (Markup) quot;</body></HTML>quot;)); Page Class }
  7. 7. Structure of a Page Type Implementation ControlCollection System.Web.UI.Control Init System.Web.UI.TemplateControl Load Control Events PreRender ASPX Code Page Page Behind Base Rendering (Markup) Page Class Unload
  8. 8. Control Base Class Interesting Member Meaning in Life Of System.Web.UI.Control Controls This property gets a ControlCollection object that represents the child controls for a specified server control in the UI hierarchy. EnableViewState This property gets or sets a value indicating whether the server control persists its view state, and the view state of any child controls it contains, to the requesting client. ID This property gets or sets the programmatic identifier assigned to the server control. Page This property gets a reference to the Page instance that contains the server control. Parent This property gets a reference to the server control's parent control in the page control hierarchy. Visible This property gets or sets a value that indicates whether a server control is rendered as UI on the page. DataBind() Binds a data source to the invoked server control and all its child controls. HasControls() Determines if the server control contains any child controls. DataBinding This event occurs when the server control binds to a data source. Init This event occurs when the server control is initialized, which is the first step in its lifecycle. Load This event occurs when the server control is loaded into the Page object. PreRender Occurs just before page does a recursive descent of its control tree and calls the render method to assemble to output stream Unload This event occurs when the server control is unloaded from memory.
  9. 9. Control Tree Essentials  All Controls expose a collection of Control objects – The Page type inherits from the Control base class, so it also exposes its own collection  Structure of nested collections become control tree  Hierarchy of control tree maps roughly to the hierarchy of your Html document – Static markup that does not contain “runat=server” gets flattened in this tree  Page output is generated by doing a recursive descent of the control tree – Render method called on each control in the tree – Page object aggregates the output and returns it to IIS as the page result  Use Trace report to examine relative sizes
  10. 10. <html> Page.Controls <head> <title>WebForm2</title> Literal Control </head> <body> Form Control <form id=quot;Form1quot; method=quot;postquot; runat=quot;serverquot;> <asp:Label Runat=server ID=lbl1 Label Control text='User Name' /> <asp:TextBox Runat=server ID=txtUserName /> Text Box Control <asp:Label Runat=server ID=quot;lbl1quot; text='Password' /> Label Control <asp:TextBox Runat=server ID=quot;txtPasswordquot; TextMode=Password /> Text Box Control <asp:Button Runat=server ID=btn1 text=‘Login' /> Button Control </form> </body> Literal Control </html>
  11. 11. The PreRender Event  “Last Call” for output changes  Fires just before page enters rendering descent  Good place to catch last minute changes – I.E. Your page contains a User Control used menuing – LinkButton on User Control causes postback – Click trap on server sets Navigation value on hosting page – Page executes the navigation in the PreRender  Can completely clear control collection and start from scratch
  12. 12. Demo Examining the Control Collection
  13. 13. Data Binding  But doesn’t the data binding engine generate HTML?  No. The data binding engine generates a collection of objects – Collection of ListItem objects for list controls – Collection of DataGridItem objects for the DataGrid  These objects are part of the control collection of the containing control  When the control renders, the collection of objects is transformed into Html as part of the standard page rendering process
  14. 14. Memory Usage During Data Binding private void Page_Load (object sender, System.EventArgs e) { SqlConnection cn = Database DataSet new SqlConnection (quot;server=.;database=pubs;uid=sa;pwd=quot;); SqlCommand cm = new SqlCommand (quot;select * from authorsquot;, cn); SqlDataAdapter da = Html + Data Grid new SqlDataAdapter(cm); View State Item for Output Collection DataSet ds = new DataSet(); Stream da.Fill(ds); DataGrid1.DataSource = ds.Tables[0]; Web Server Memory Usage DataGrid1.DataBind(); } //Page Rendering…
  15. 15. Minimizing Memory Consumption  Use a SqlDataReader  Set EnableViewState=false  Bind to small result sets  Use paging for larger result sets  Use custom paging and implement paging at the database level – Avoids marshaling the full result set across the network on every page change  If there’s high contention for a specific result set, put it in the cache – Filter the in-memory result to tailor to users – All users share the in-memory image instead of each user getting their own
  16. 16. Custom Rendering  Creating a custom Web Control allows you to implement your own rendering behavior  Overriding the Render method of the Control base class is your main task  Instance of HtmlTextWriter is passed to render method as argument – This is your hook into the IIS output stream  RegisterClientScriptBlock can be used to include client side script in output stream – Registering causes it to be only included once in case more than one instance of your control is in use
  17. 17. Demo Custom Rendering by Inheriting from System.Web.UI.Control
  18. 18. Capturing the Rendered Output Stream  The Page’s output stream can be captured and redirected  Can be used to: – Pre generate your Html for storage in a database or as static files – Send a web page as an Html Email – Capture output for digital signatures  The Page exposes a Render method  Pass your own stream as an argument  Use stream to make output do your bidding  Redirect or call Response.End after calling Render – Failure to do so will cause an exception
  19. 19. Demo Capturing the Page’s Output Stream
  20. 20. Rendering Redirection Code StringBuilder sb = new StringBuilder(); HtmlTextWriter t = new HtmlTextWriter(new StringWriter(sb)); this.Render(t); string s = sb.ToString(); MailMessage m =new MailMessage(); m.BodyFormat = MailFormat.Html; m.From = quot;Enrollment@IntertechTraining.comquot;; m.To = Request.QueryString[quot;emailquot;].ToString(); m.Subject = quot;Course Descriptionquot;; m.Body = s; WebStatic.SendEmail(m); Response.Write(quot;<body onload='window.close();'>quot;); Response.End();
  21. 21. Summary  The core structure of the Page type is the Control tree  Everything you use in ASP.NET inherits from System.Web.UI.Control – Including the Page object, Web Controls, and Html Controls  Create a Web Form is really the act of creating this in- memory control tree  An ASPX page, as markup, is an abstraction provided to us by the Framework – It actually gets generated into a class file at runtime  You have full programmatic access to the control tree all the way through the pre-render event  You can override the render event by creating a custom web control  You can redirect the output stream generated when the page renders and send it where you please
  22. 22. Help | About Dominic Selly  Instructor for Intertech Training – Now Offering Live Instructor Lead Virtual Training!  – Full course outlines and descriptions Questions? Comments?