31
Delivering Excellence in Software Engineering ® 2006. EPAM Systems. All rights reserved. Web Controls

Web Controls

  • Upload
    damisi

  • View
    46

  • Download
    2

Embed Size (px)

DESCRIPTION

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. - PowerPoint PPT Presentation

Citation preview

Page 1: Web Controls

Delivering Excellence in Software Engineering

® 2006. EPAM Systems. All rights reserved.

Web Controls

Page 2: Web Controls

® 2006. EPAM Systems. All rights reserved.

Control architecture

• ASP.NET is a control-based architecture and is defined in the following way:1.A Page is a control2.Any control may contain child controls3.A control is rendered by rendering its

contents and iteratively rendering its children

Page 3: Web Controls

® 2006. EPAM Systems. All rights reserved.

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

Page 4: Web Controls

® 2006. EPAM Systems. All rights reserved.

<%@ Page language='C#' trace='true' %><html><head><script runat='server'>protected void OnEnterName(object src, EventArgs e){ _message.Text = string.Format("Hi, {0}, how are you?", _name.Text);}</script></head><body><form runat='server'><h2>Enter your name: <asp:TextBox id='_name' runat='server'/></h2><asp:Button Text='Enter' OnClick='OnEnterName' runat='server'/><br/><asp:Label Id='_message' runat='server'/></form></body></html>

An .ASPX page prior to compilation

<%@ Page language='C#' trace='true' %>

Page 5: Web Controls

® 2006. EPAM Systems. All rights reserved.

In-memory representation of an .ASPX page

LiteralControl

"<h2>Enteryour

name: "

TextBoxControl

I D=m_Name

LiteralControl"</ h2>"

ButtonControl

OnCl i ck=OnEnterName

LiteralControl"<br/ >"

LabelControl

I D=m_Message

LiteralControl"<html ><head></ head><body>"

LiteralControl

"</ body></ html >"

HtmlFormControl

Control s

PageControl

Control s

Page 6: Web Controls

® 2006. EPAM Systems. All rights reserved.

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

Page 7: Web Controls

® 2006. EPAM Systems. All rights reserved.

namespace EssentialAspDotNet.CustomControls { public class NameControl : Control { private string _name; private bool _isImportant;

public string Name { get { return _name; } set { _name = value; } }

public bool IsImportant { get { return _isImportant; } set { _isImportant = value; } }

protected override void 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); } }}

A simple custom control

Page 8: Web Controls

® 2006. EPAM Systems. All rights reserved.

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"/>

Page 9: Web Controls

® 2006. EPAM Systems. All rights reserved.

<%@ Page Language="C#" %><%@ Register TagPrefix="DM" Namespace="EssentialAspDotNet.CustomControls" Assembly="SimpleControl" %><html><body>

<form runat=server> <DM:NameControl runat='server' Name='Fred' IsImportant='false'/> <DM:NameControl runat='server' Name='George' IsImportant='true' /> </form>

</body></html>

Client .aspx page for the SimpleControl custom server control

<%@ Page Language="C#" %><%@ Register TagPrefix="DM" Namespace="EssentialAspDotNet.CustomControls" Assembly="SimpleControl" %>

Page 10: Web Controls

® 2006. EPAM Systems. All rights reserved.

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

Page 11: Web Controls

® 2006. EPAM Systems. All rights reserved.

public class Control : IComponent, IParserAccessor, ...{ // Rendering protected virtual void Render(HtmlTextWriter); public void RenderControl(HtmlTextWriter); protected virtual void RenderChildren(HtmlTextWriter); public virtual bool Visible {get; set;} // Request to create child controls protected virtual void CreateChildControls(); // Accessors public virtual Page Page {get; set;} public virtual Control Parent {get;} protected virtual HttpContext Context {get;} // Events public event EventHandler Init; public event EventHandler Load; public event EventHandler PreRender; public event EventHandler Unload; //...}

Important members of the System.Web.UI.Control class

Page 12: Web Controls

® 2006. EPAM Systems. All rights reserved.

HtmlTextWriter

• The HtmlTextWriter class passed into Render provides– Methods for rendering specific HTML elements– Stack-based rendering of closing tags– Browser-independent rendering (to an extent)

public class HtmlTextWriter : TextWriter{ // Convenience, stack-based methods public virtual void AddAttribute(HtmlTextWriterAttribute, string); public virtual void AddStyleAttribute(HtmlTextWriterStyle, string); public virtual void RenderBeginTag(HtmlTextWriterTag); public virtual void RenderEndTag(); //...}

Page 13: Web Controls

® 2006. EPAM Systems. All rights reserved.

protected override void 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>}

Sample Control Render method using stack-based methods

Page 14: Web Controls

® 2006. EPAM Systems. All rights reserved.

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

Page 15: Web Controls

® 2006. EPAM Systems. All rights reserved.

ChildControl 1

ChildControl 2

ChildControl 3

Page

...

Request

HtmlTextWriterBrowserIE 5.5

Request

Html32TextWriterBrowser

Netscape 3.0

Render Render Render

ProcessRequest

<table width="50%" border="1"> <tr> <td align="left"> <font color="blue" size="4"> txt</font></td> <td align="right"> <font color="green"> txt2</font></td> </tr></table>

<table width="50%" border="1"> <tr> <td align="left" style="font-size:medium;color:blue;"> txt</td> <td align="right" style="color:green;"> txt2</td>

</tr></table>

Browser-contingent rendering

Page 16: Web Controls

® 2006. EPAM Systems. All rights reserved.

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

Page 17: Web Controls

® 2006. EPAM Systems. All rights reserved.

class HttpBrowserCapabilities : HttpCapabilitiesBase{ public bool ActiveXControls {get;} public bool AOL {get;} public bool BackgroundSounds {get;} public bool Beta {get;} public bool Browser {get;} public Version ClrVersion {get;} public bool CDF {get;} public bool Cookies {get;} public bool Crawler {get;} public bool Frames {get;} public bool JavaApplets {get;} public bool JavaScript {get;} public int MajorVersion {get;} public double MinorVersion {get;} public string Platform {get;} public bool Tables {get;} public string Type {get;} public bool VBScript {get;} public string Version {get;} public Version W3CDomVersion {get;} public bool Win16 {get;} public bool Win32 {get;} //...}

The HttpBrowserCapabilities class, used to query client browser capabilities

Page 18: Web Controls

® 2006. EPAM Systems. All rights reserved.

public class BrowserIndependentControl : Control { protected override void 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>"); }}

An example of a control that changes based on browser type

Page 19: Web Controls

® 2006. EPAM Systems. All rights reserved.

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> <case match="^Mozilla[^(]*\(compatible; MSIE (?'version'(?'major'\d+)(?'minor'\.\d+) (?'letters'\w*))(?'extra'.*)"> browser=IE version=${version} majorversion=${major} minorversion=${minor} </case> <!--...--> </filter></browserCaps>

machine.config

Page 20: Web Controls

® 2006. EPAM Systems. All rights reserved.

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

ie4ie5upleveldownlevel

<%@ Page Language='C#' ClientTarget='downlevel' %>

Page 21: Web Controls

® 2006. EPAM Systems. All rights reserved.

Creating additional targets

<!-- web.config file --><configuration> <system.web> <clientTarget> <add alias='nn6' userAgent='Mozilla/5.0 (en-US;) Netscape6/6.0' /> </clientTarget> </system.web></configuration>

<%@ Page Language='C#' ClientTarget='nn6' %>

Page 22: Web Controls

® 2006. EPAM Systems. All rights reserved.

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 instancesclass Page : TemplateControl, IHttpHandler{ public virtual void RegisterClientScriptBlock( string key, string script); //...}

Page 23: Web Controls

® 2006. EPAM Systems. All rights reserved.

public class TicTacToe : Control{ protected override void 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); } protected override void Render(HtmlTextWriter output) {/* render with references to script */ }}

Control with client-side script generation

Page 24: Web Controls

® 2006. EPAM Systems. All rights reserved.

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

Page 25: Web Controls

® 2006. EPAM Systems. All rights reserved.

public class WebControl : Control{ public virtual string AccessKey {get; set;} public virtual Color BackColor {get; set;} public virtual Color BorderColor {get; set;} public virtual BorderStyle BorderStyle {get; set;} public virtual Unit BorderWidth {get; set;} public virtual string CssClass {get; set;} public virtual bool Enabled {get; set;} public virtual FontInfo Font {get; } public virtual Color ForeColor {get; set;} public virtual Unit Height {get; set;} public virtual short TabIndex {get; set;} public virtual string ToolTip {get; set;} public virtual Unit Width {get; set;} //...}

Additional properties defined by WebControl

Page 26: Web Controls

® 2006. EPAM Systems. All rights reserved.

Sample WebControl-derived control

public class SampleWebControl : WebControl{ protected override void RenderContents(HtmlTextWriter w) { w.Write("<h2>hi from my web control</h2>"); base.RenderContents(w); }}

<span style="..."><h2>hi from my web control</h2></span>

Renders as

populated with attributes inherited from WebControl(and set by client)

Page 27: Web Controls

® 2006. EPAM Systems. All rights reserved.

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

Page 28: Web Controls

® 2006. EPAM Systems. All rights reserved.

public class Control : IComponent, IParserAccessor, ...{ public virtual bool EnableViewState {get; set;}

protected virtual StateBag ViewState {get;}

protected bool HasChildViewState {get;} protected bool IsTrackingViewState {get;} protected virtual bool ViewStateIgnoresCase {get;} protected void ClearChildViewState(); protected virtual object SaveViewState(); protected virtual void TrackViewState();

//...}

State in the System.Web.UI.Control class

Page 29: Web Controls

® 2006. EPAM Systems. All rights reserved.

public class SimpleControl : Control { public string Prop { get { return (String) ViewState["Prop"]; } set { ViewState["Prop"] = value; } }

protected override void Render(HtmlTextWriter output) { output.Write("<h1>Property value:"+this.Prop+"</h1>"); }}

Sample control using state

Page 30: Web Controls

® 2006. EPAM Systems. All rights reserved.

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

Page 31: Web Controls

Delivering Excellence in Software Engineering

® 2006. EPAM Systems. All rights reserved.

For more information, please contact:

Uladzimir TsikhonSoftware Engineering Manager, Belarus Recourse Development DepartmentEPAM Systems, Inc.Belarus, MinskPhone: +375(17) 2101662 ext 1756Fax: +375(17) 2101168Email: [email protected]://www.epam.com