1 / 31

Web Controls

Web Controls. Control architecture. ASP.NET is a control-based architecture and is defined in the following way: A Page is a control Any control may contain child controls A control is rendered by rendering its contents and iteratively rendering its children. Controls and Pages.

damisi
Download Presentation

Web Controls

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Web Controls

  2. Control architecture • ASP.NET is a control-based architecture and is defined in the following way: • A Page is a control • Any control may contain child controls • A control is rendered by rendering its contents and iteratively rendering its children

  3. Controls and Pages • Every ASP.NET Page is constituted by a collection of controls • System.Web.UI.Page is itself the top-level control • System.Web.UI.HTMLControls define server-side equivalents of HTML elements • System.Web.UI.WebControls define server-side controls that generate HTML in an intuitive, standard way • System.Web.UI.LiteralControl is the catch-all control used to represent all literal HTML text on a Page • System.Web.UI.Control is the base class for all of these controls, and can be extended to build custom controls

  4. An .ASPX page prior to compilation <%@ Page language='C#' trace='true' %> <html> <head> <scriptrunat='server'> protected void OnEnterName(object src, EventArgs e) { _message.Text = string.Format("Hi, {0}, how are you?", _name.Text); } </script> </head> <body> <formrunat='server'> <h2>Enter your name: <asp:TextBoxid='_name'runat='server'/> </h2> <asp:ButtonText='Enter' OnClick='OnEnterName'runat='server'/> <br/> <asp:LabelId='_message'runat='server'/> </form> </body> </html> <%@ Page language='C#' trace='true' %>

  5. In-memory representation of an .ASPX page

  6. Building Custom Controls • You build new custom server controls by creating a new class derived from Control • Create a new class derived from System.Web.UI.Control (typically in a distinct namespace) • Add any control-specific properties • Add any control-specific events • Override its Render() method to generate HTML using the HtmlTextWriter passed in • Compile the code into an assembly and deploy

  7. A simple custom control namespace EssentialAspDotNet.CustomControls { publicclass NameControl : Control { privatestring _name; privatebool _isImportant; publicstring Name { get { return _name; } set { _name = value; } } publicbool IsImportant { get { return _isImportant; } set { _isImportant = value; } } protectedoverridevoid Render(HtmlTextWriter writer) { string txt; if (_isImportant) txt = string.Format("<h1>{0}</h1>", _name); else txt = string.Format("<h2>{0}</h2>", _name); writer.Write(txt); } } }

  8. Using Custom Controls • Custom controls may be used from any ASP.NET page with the Register directive • TagPrefix is the shorthand name you would like to use to scope any controls in the Namespace • Namespace specifies the namespace of the control you want to reference • Assembly is the name of the assembly containing the control <%@ Register TagPrefix="DM" Namespace="EssentialAspDotNet.CustomControls" Assembly="SimpleControl" %> <DM:NameControl runat="server"/>

  9. Client .aspx page for the SimpleControl custom server control <%@ Page Language="C#" %> <%@ Register TagPrefix="DM" Namespace="EssentialAspDotNet.CustomControls" Assembly="SimpleControl" %> <html> <body> <formrunat=server> <DM:NameControlrunat='server'Name='Fred' IsImportant='false'/> <DM:NameControlrunat='server'Name='George' IsImportant='true'/> </form> </body> </html> <%@ Page Language="C#" %> <%@ Register TagPrefix="DM" Namespace="EssentialAspDotNet.CustomControls" Assembly="SimpleControl" %>

  10. System.Web.UI.Control • System.Web.UI.Control serves as the base class for all controls and provides • A virtual Render method for display • Accessors to Page and immediate parent control • Events to access various points in the control's lifetime • ViewState control methods • Child control management functions

  11. Important members of the System.Web.UI.Control class publicclass Control : IComponent, IParserAccessor, ... { // Rendering protectedvirtualvoid Render(HtmlTextWriter); publicvoid RenderControl(HtmlTextWriter); protectedvirtualvoid RenderChildren(HtmlTextWriter); publicvirtualbool Visible {get; set;} // Request to create child controls protectedvirtualvoid CreateChildControls(); // Accessors publicvirtual Page Page {get; set;} publicvirtual Control Parent {get;} protectedvirtual HttpContext Context {get;} // Events publicevent EventHandler Init; publicevent EventHandler Load; publicevent EventHandler PreRender; publicevent EventHandler Unload; //... }

  12. HtmlTextWriter • The HtmlTextWriterclass passed into Render provides • Methods for rendering specific HTML elements • Stack-based rendering of closing tags • Browser-independent rendering (to an extent) publicclass HtmlTextWriter : TextWriter { // Convenience, stack-based methods publicvirtualvoid AddAttribute(HtmlTextWriterAttribute, string); publicvirtualvoid AddStyleAttribute(HtmlTextWriterStyle, string); publicvirtualvoid RenderBeginTag(HtmlTextWriterTag); publicvirtualvoid RenderEndTag(); //... }

  13. Sample Control Render method using stack-based methods protectedoverridevoid Render(HtmlTextWriter output) { output.AddAttribute(HtmlTextWriterAttribute.Width, "50%"); output.AddAttribute(HtmlTextWriterAttribute.Border, "1"); output.RenderBeginTag(HtmlTextWriterTag.Table); //<table> output.RenderBeginTag(HtmlTextWriterTag.Tr); // <tr> output.AddAttribute(HtmlTextWriterAttribute.Align, "left"); output.AddStyleAttribute(HtmlTextWriterStyle.FontSize, "medium"); output.AddStyleAttribute(HtmlTextWriterStyle.Color, "blue"); output.RenderBeginTag(HtmlTextWriterTag.Td); // <td> output.Write("This is row 0 column 0"); output.RenderEndTag(); // </td> output.AddAttribute(HtmlTextWriterAttribute.Align, "right"); output.AddStyleAttribute(HtmlTextWriterStyle.Color, "green"); output.RenderBeginTag(HtmlTextWriterTag.Td); // <td> output.Write("This is row 0 column 1"); output.RenderEndTag(); // </td> output.RenderEndTag(); // </tr> output.RenderEndTag(); // </table> }

  14. HtmlTextWriter browser independence • Request processing architecture chooses a writer • Determined by checking TagWriter attribute of HttpBrowserCapabilities class • HtmlTextWriter for HTML 4.0 compliant browser rendering • Uses style attribute • Html32TextWriter for Html 3.2 compliant browser rendering • Does not use style attribute, instead uses font and color attributes of tables and other elements

  15. Browser-contingent rendering

  16. Building Browser-Independent Controls • One of the primary benefits of server-side controls is the ability to customize output based on the client browser • Custom controls can easily generate alternate HTML in their Render() methods based on the client browser capabilities • Browser capabilities can be queried through the Page.Request.Browser object (of type HttpBrowserCapabilities) • Many ASP.NET server controls generate different HTML based on client browser (Calendar, ValidationXXX, AdRotater, etc.) • One common approach for complex controls, is to use JavaScript on browsers that are capable, and revert to server processing on those that aren't

  17. The HttpBrowserCapabilities class, used to query client browser capabilities classHttpBrowserCapabilities : HttpCapabilitiesBase { publicboolActiveXControls {get;} publicbool AOL {get;} publicboolBackgroundSounds {get;} publicbool Beta {get;} publicbool Browser {get;} public Version ClrVersion {get;} publicbool CDF {get;} publicbool Cookies {get;} publicbool Crawler {get;} publicbool Frames {get;} publicboolJavaApplets {get;} publicbool JavaScript {get;} publicintMajorVersion {get;} publicdoubleMinorVersion {get;} publicstring Platform {get;} publicbool Tables {get;} publicstring Type {get;} publicbool VBScript {get;} publicstring Version {get;} public Version W3CDomVersion {get;} publicbool Win16 {get;} publicbool Win32 {get;} //... }

  18. An example of a control that changes based on browser type publicclass BrowserIndependentControl : Control { protectedoverridevoid Render(HtmlTextWriter output) { if (Page.Request.Browser.JavaScript) output.Write( "<h3 onclick=\"alert('Hi there')\">click me!</h3>"); else output.Write("<h3>Don't bother</h3>"); } }

  19. Client browser recognition • The HTTP_USER_AGENT header is parsed to determine client browser capabilities • <browserCaps> element in machine.config contains regular expression mappings • used to populate HttpBrowserCapabilities class per request <browserCaps> <filter> <casematch="^Mozilla[^(]*\(compatible; MSIE (?'version'(?'major'\d+)(?'minor'\.\d+) (?'letters'\w*))(?'extra'.*)"> browser=IE version=${version} majorversion=${major} minorversion=${minor} </case> <!--...--> </filter> </browserCaps> machine.config

  20. Hard-coding client targets • It can be useful to test the alternate rendering by setting the clientTarget attribute of the @Page directive explicitly • Built-in client targets include ie4 ie5 uplevel downlevel <%@ Page Language='C#' ClientTarget='downlevel' %>

  21. Creating additional targets <!-- web.config file --> <configuration> <system.web> <clientTarget> <addalias='nn6' userAgent='Mozilla/5.0 (en-US;) Netscape6/6.0'/> </clientTarget> </system.web> </configuration> <%@ Page Language='C#' ClientTarget='nn6' %>

  22. Generating client-side script • Custom controls may want to render client-side script • To push some functionality to the client, reducing round trips • To enhance the client UI using the DOM • The Page class provides a method for inserting script • Each script must be uniquely named with a key • Scripts are inserted near the beginning of the page • Scripts are rendered only once, even with multiple control instances class Page : TemplateControl, IHttpHandler { publicvirtualvoid RegisterClientScriptBlock( string key, string script); //... }

  23. Control with client-side script generation publicclass TicTacToe : Control { protectedoverridevoid OnInit(EventArgs e) { string sCode = @"<script language=javascript> var g_rgbXWentLast = new Object(); function OnClickCell(cell, idx) { if (cell.innerText == ' ') { if (g_rgbXWentLast[idx]) cell.innerText = 'O'; else cell.innerText = 'X'; g_rgbXWentLast[idx] = !g_rgbXWentLast[idx]; } else cell.innerText = ' '; }</script>"; Page.RegisterClientScriptBlock("CellCode", sCode); } protectedoverridevoid Render(HtmlTextWriter output) {/* render with references to script */ } }

  24. System.Web.UI.WebControls.WebControl • WebControl serves as the base class for all WebControls • Derives directly from Control • Adds several additional fields, properties, and methods used commonly by all of the WebControls (Button, Label, etc.) • Controls created with Visual Studio .NET use this as the base class by default • Instead of overriding Render() you can override RenderContents() and WebControl will render a span around your content

  25. Additional properties defined by WebControl publicclass WebControl : Control { publicvirtualstring AccessKey {get; set;} publicvirtual Color BackColor {get; set;} publicvirtual Color BorderColor {get; set;} publicvirtual BorderStyle BorderStyle {get; set;} publicvirtual Unit BorderWidth {get; set;} publicvirtualstring CssClass {get; set;} publicvirtualbool Enabled {get; set;} publicvirtual FontInfo Font {get; } publicvirtual Color ForeColor {get; set;} publicvirtual Unit Height {get; set;} publicvirtualshort TabIndex {get; set;} publicvirtualstring ToolTip {get; set;} publicvirtual Unit Width {get; set;} //... }

  26. Sample WebControl-derived control publicclass SampleWebControl : WebControl { protectedoverridevoid RenderContents(HtmlTextWriter w) { w.Write("<h2>hi from my web control</h2>"); base.RenderContents(w); } } Renders as <span style="..."><h2>hi from my web control</h2></span> populated with attributes inherited from WebControl (and set by client)

  27. State management in custom controls • Custom controls can propagate state through the hidden __VIEWSTATE form field if needed • State retention in any control can be enabled or disabled through the EnableViewState property • Controls can store and retrieve state through the ViewState property (which is of type StateBag) • Any state stored into the ViewState state bag will be propagated to and from a client through the __VIEWSTATE field

  28. State in the System.Web.UI.Control class publicclass Control : IComponent, IParserAccessor, ... { publicvirtualboolEnableViewState {get; set;} protectedvirtualStateBagViewState {get;} protectedboolHasChildViewState {get;} protectedboolIsTrackingViewState {get;} protectedvirtualboolViewStateIgnoresCase {get;} protectedvoidClearChildViewState(); protectedvirtualobjectSaveViewState(); protectedvirtualvoidTrackViewState(); //... }

  29. Sample control using state publicclass SimpleControl : Control { publicstring Prop { get { return (String) ViewState["Prop"]; } set { ViewState["Prop"] = value; } } protectedoverridevoid Render(HtmlTextWriter output) { output.Write("<h1>Property value:"+this.Prop+"</h1>"); } }

  30. Summary • A page is constituted by collection of controls • All controls derive from Control and typically override the Render() method • Custom controls are referenced using the Register directive from an .aspx page • Controls can conditionally generate different HTML based on browser capabilities • Controls can render client-side script • Control can manage their own state

  31. For more information, please contact: Uladzimir Tsikhon Software Engineering Manager, Belarus Recourse Development Department EPAM Systems, Inc. Belarus, MinskPhone: +375(17) 2101662 ext 1756 Fax: +375(17) 2101168 Email: uladzimir_tsikhon@epam.com http://www.epam.com

More Related