1 / 44

DEV300 Building ASP Server Controls Part I: The Basics

Agenda (Part I). IntroductionBasic control authoring topics (with demos built along the way)Implementing propertiesRenderingRaising EventsAdding client-side behavior with scriptExtending existing controlsCompositing existing controlsBuilding controls in Visual Studio .NET. Agenda (Part II ?

zan
Download Presentation

DEV300 Building ASP Server Controls Part I: The Basics

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. DEV300 Building ASP.NET Server Controls Part I: The Basics Nikhil Kothari Development Lead ASP.NET Microsoft Corporation

    2. Agenda (Part I) Introduction Basic control authoring topics (with demos built along the way) Implementing properties Rendering Raising Events Adding client-side behavior with script Extending existing controls Compositing existing controls Building controls in Visual Studio .NET I’ll cover the fundamentals of writing controls in this session. Specifically, we’ll look at implementing properties so page developers can customize controls Rendering, which allows your control to generate markup sent to the browser Raising events, which provide interesting places for the page developer to write code Adding client-side behavior, so you can improve the usability and functionality of your control We’ll also look at two mechanisms for writing controls – extending and composing. Finally we’ll look at how you can use Visual Studio .NET to create controls, and debug them. I’ll cover the fundamentals of writing controls in this session. Specifically, we’ll look at implementing properties so page developers can customize controls Rendering, which allows your control to generate markup sent to the browser Raising events, which provide interesting places for the page developer to write code Adding client-side behavior, so you can improve the usability and functionality of your control We’ll also look at two mechanisms for writing controls – extending and composing. Finally we’ll look at how you can use Visual Studio .NET to create controls, and debug them.

    3. Agenda (Part II – DEV 401) Build a real-world control – DataBoundTable Simplified version of ASP.NET DataGrid Control authoring topics covered DataBinding Styles State Management Templates Control Designer topics covered DataBinding in the designer Template Editing in the designer In part 2, I’ll be building on the fundamental topics we just talked about to write a more realistic and somewhat more complex control. In that session I’ll be building a DataBoundTable that is like a mini-version of the ASP.NET datagrid.In part 2, I’ll be building on the fundamental topics we just talked about to write a more realistic and somewhat more complex control. In that session I’ll be building a DataBoundTable that is like a mini-version of the ASP.NET datagrid.

    4. ASP.NET Control Gallery http://www.asp.net Lots of ISV-written controls are available Extensibility is a feature

    5. What Is A Server Control? A server control is a .NET component that is used to generate the user interface of an ASP.NET Web application. It is implemented as a managed class deriving directly or indirectly from the System.Web.UI.Control base class. On this slide I have somewhat of a techy definition of what a server control is. Its basically a managed component that is used by page developers to put together the user interface of their web application. All server controls derive directly or indirectly from the System.Web.UI.Control base class.On this slide I have somewhat of a techy definition of what a server control is. Its basically a managed component that is used by page developers to put together the user interface of their web application. All server controls derive directly or indirectly from the System.Web.UI.Control base class.

    6. What Is A Server Control? Speaking More Practically… A Web user interface element Renders into HTML, script or a different markup format Allows customization of rendering A Web user interface component Exposes properties, events and methods and is programmable Provides higher level abstractions Performs post-back processing Handles differences between browsers Consistent programming model A RAD component that offers a design-time experience User Interface Element Single control can render into multiple tags, in multiple markup formats based on customization done by the page developer Web user interface component As opposed to static HTML, a control offers a programming model Higher level abstracts Eg. Handling postback, so page developers don’t have to grovel in the Form collection Hide inconsistencies such as <input type=“text”> vs. <textarea> Consistent with UI frameworks you might have used in the past – eg. Enabled instead of DisabledUser Interface Element Single control can render into multiple tags, in multiple markup formats based on customization done by the page developer Web user interface component As opposed to static HTML, a control offers a programming model Higher level abstracts Eg. Handling postback, so page developers don’t have to grovel in the Form collection Hide inconsistencies such as <input type=“text”> vs. <textarea> Consistent with UI frameworks you might have used in the past – eg. Enabled instead of Disabled

    8. 2 Ways To Author Server Controls User Controls Simple, declarative authoring model (.ascx file) Scoped to a single application Well suited to static content and layout “Custom” or Compiled Controls Code-based authoring model (.cs or .vb class file) Easily shared across applications Well suited to dynamic or programmatic generation of content and layout More complex, but also more capabilities

    9. Control Authoring Basics ColoredLabel ActiveLabel HoverLabel

    10. ColoredLabel Simple, minimal control Renders as a <span> tag with CSS color attribute Offers a couple of properties Text and Color Metadata on properties Demonstrates state management Uses ViewState in property implementation Demonstrates basic rendering Render method Usage of HtmlTextWriter

    11. ColoredLabel (cont’d) Metadata on properties Declarative way of specifying behavior Property editing in property browser Property persistence Conversion of types to/from strings Metadata can be applied to events, methods and types as well

    13. Text Property Talking points Never return null Strongly typed properties – Eg. ColorTalking points Never return null Strongly typed properties – Eg. Color

    14. Rendering Override Render to representative markup Use HtmlTextWriter API to implement rendering logic public override void Render(HtmlTextWriter writer) { writer.AddStyleAttribute(HtmlTextWriterStyle.Color, color); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write(Text); writer.RenderEndTag(); }

    15. ActiveLabel Adds Click event to the ColoredLabel control Maps a Click browser event to equivalent server event Generates post-back script using Page.GetPostBackEventReference() Implements IPostBackEventHandler

    17. Event Implementation Standard event pattern has two parts Event declaration On<Event> protected virtual method An alternate event implementation: private static readonly object ClickEventKey = new object(); public event EventHandler Click { add { Events.AddHandler(ClickEventKey, value); } remove { Events.RemoveHandler(ClickEventKey, value); } } Benefits: We don’t create a field per event per control instance. Typically control users are interested in a small set of events, and adding fields for every event bloats the instance size of a control. The auto-generated add/remove methods are synchronized, i.e., the generated methods incur the cost of acquiring and releasing a lock for each call. This lock is not required in asp.net scenarios, since a whole request is executed on a single thread. An alternate event implementation: private static readonly object ClickEventKey = new object(); public event EventHandler Click { add { Events.AddHandler(ClickEventKey, value); } remove { Events.RemoveHandler(ClickEventKey, value); } } Benefits: We don’t create a field per event per control instance. Typically control users are interested in a small set of events, and adding fields for every event bloats the instance size of a control. The auto-generated add/remove methods are synchronized, i.e., the generated methods incur the cost of acquiring and releasing a lock for each call. This lock is not required in asp.net scenarios, since a whole request is executed on a single thread.

    18. Handling The Client Event Controls render script handler protected override void Render(HtmlTextWriter writer) { string scriptHandler = Page.GetPostBackEventReference(this,””); writer.AddAttribute(HtmlTextWriterAttribute.Onclick, scriptHandler); base.Render(writer); } Resulting markup: <span onclick="__doPostBack(‘label1','')">Text</span> Page framework implements the actual post-back logic

    19. Raising The Server Event Control implements IPostBackEventHandler Page framework calls control’s RaisePostBackEvent() method

    20. Raising A Server Event Mapping a browser event to server event

    21. HoverLabel Adds client-side hover and cursor effects Use of client script for better visual feedback Uses external script file to implement client functionality Script library instead of script within the page Script file is cached on the client Script installed to aspnet_client folder on web server

    22. Client Script Support Check if client-side functionality should be enabled Override OnPreRender Provide an “Enable” property for page developer Use BrowserCapabilities to determine if the client supports scripting Page.Request.Browser.EcmaScriptVersion Use Page.RegisterStartupScript to render a script include Render client event handler during Render Typically as an attribute to handle a client event

    24. BulletedList Implementing a control by extending an existing control Extends ListControl Gets a lot of implementation for “free” Items Collection Data-binding Designer experience in VS.NET Overrides the rendering functionality Renders an HTML unordered list <UL>

    26. Override Rendering Override the right Render method protected override void RenderContents( HtmlTextWriter writer) { foreach (ListItem li in Items) { RenderListItem(writer, li); } } Other interesting Render methods Render, RenderBeginTag, RenderEndTag

    27. The Rendered Tag Override the HtmlTagKey property public override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Ul; } } WebControl by default renders a <span> ListControl by default renders a <select>

    28. Rendering Attributes Override RenderAttributes to add new attributes on the begin tag protected override void AddAttributesToRender(…) { writer.AddAttribute("type", "square"); base.AddAttributesToRender(writer); } Controls that derive from WebControl render Style properties on begin tag Basic uplevel/downlevel styles support

    29. RequiredTextField Implementing a control by compositing existing controls RequiredTextField combines a TextBox and a RequiredFieldValidator to reuse their functionality Implements Text property by delegating Implements the standard composite control pattern Implements INamingContainer Overrides Controls property to ensure child controls Overrides CreateChildControls to implement logic of creating child controls TODO: Switch code to use delegation to implement Text propertyTODO: Switch code to use delegation to implement Text property

    31. Composite Control Pattern public class RequiredTextField : Control, INamingContainer { public override ControlCollection Controls { get { EnsureChildControls(); return base.Controls; } } protected override void CreateChildControls() { ... } }

    32. CreateChildControls() protected override void CreateChildControls() { TextBox text1 = new TextBox(); text1.ID = "text1"; text1.Text = “Enter Text"; RequiredFieldValidator req1 = new RequiredFieldValidator(); req1.ControlToValidate = "text1"; req1.Text = "*"; Controls.Add(text1); Controls.Add(new LiteralControl(" ")); Controls.Add(req1); }

    33. Building Controls In Visual Studio .NET Setting up your Solution Choosing a Tag Prefix Choosing a Toolbox Glyph Debugging your Control

    34. Setting up your Solution Use a WebControlLibrary project to create custom compiled controls Initialize the Version attribute Add a Web app to test controls Solution > Add New > Web Application Add a ToolBox reference Customize Toolbox > Browse

    35. Choosing A Tag Prefix Tools such as Visual Studio .NET use this as the “suggested” tag prefix for your control Specified using an assembly attribute in AssemblyInfo.cs using System.Web.UI [assembly: TagPrefix( “Microsoft.Samples.TechEd2003.WebControls”, “sample”)] Result: <sample:HoverLabel .../>

    36. Custom Toolbox Glyph Bitmap file with same base name as control class in the same namespace BulletedList.bmp Build Action = “Embedded Resource” Image properties: File type supported is bitmap 16x16 pixels Lower-left pixel is used to determine transparency Adds an extra professional touch ?

    37. Debugging Your Control Set a breakpoint in your control runtime Set the Web App as Startup Project Set a Startup Web page F5 Use your control in the running page

    38. Essential Resources Developing Microsoft ASP.NET Server Controls and Components

    39. Related Talks DEV 401: Building ASP.NET Controls, Part II: Advanced Topics Right here, Wednesday at 10:15 am DEV 200, DEV 201: Introducing ASP.NET DEV 400: Black Belt WebForms Programming DEV 402: Extending the ASP.NET Runtime

    40. Key Take Aways Controls provide an abstraction and reusability mechanism for web apps ASP.NET provides a rich framework for creating server controls Create specialized derived controls to make incremental changes to existing controls Use composition to leverage existing controls in more specialized scenarios

    41. Questions… And Answers

    42. Suggested Reading And Resources

    44. Abstract Learn about the key concepts to develop ASP.NET server controls. Start with a simple control with custom properties and rendering, and evolve it to add support for view-state, post-back events, and client-side DHTML behavior. Implement new controls by extending or reusing existing server controls. Assumes a working knowledge of ASP.NET pages, controls, post-back and view-state.

More Related