Download - DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Transcript
Page 1: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

DEV401

Developing ASP.NET Server Controls - Part II: Adv Topics

Tony GoodhewProduct ManagerMicrosoft Corp

Page 2: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Agenda

Introduction

Build a real-world control – DataBoundTableSimplified version of ASP.NET DataGrid

Control authoring topics coveredComposition

DataBinding

Styles

State Management

Templates

Control Designer topics coveredDataBinding in the designer

Template Editing in the designer

Page 3: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

ASP.NET Control Gallery

http://www.asp.net

Lots of ISV-written controls are available

Extensibility is a feature

Page 4: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Quick Review

A server control is a programmable Web user interface component

From Part I (DEV 300)Simple properties (ColoredLabel)

Events (ActiveLabel)

Client-side behavior (HoverLabel)

Extending controls (BulletedList)

Compositing controls (RequiredTextField)

Page 5: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

DataBoundTable

Tabular rendering of records in a data source

Feature AttributesFlexible

Can be bound to variety of data sources

Manages state so page developer does not have to fetch data during each request

CustomizablePage developer can specify look and feel

Styles and Templates

DesignableCan be customized at design-time

Offers a design-time representation

Page 6: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

DataBoundTable Usage<sample:DataBoundTable runat=“server” id=“dbt1” DataSource=‘<%# dataView1 %>’ EnableSelection=“true” OnSelectedIndexChanged=“dbt1_SelIndexChanged” Font-Name=“Verdana” Font-Size=“20pt” BackColor=“Beige” ForeColor=“Black”>

<AlternatingItemStyle BackColor=“Tan”/> <HeaderStyle Font-Bold=“true”/>

<CaptionTemplate> This is the current list of available items. </CaptionTemplate>

</sample:DataBoundTable>

Page 7: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

DataBoundTableDataBoundTable

Usage Demo,Usage Demo,Building DataBoundTableBuilding DataBoundTable

Page 8: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Composite Control

Contains Table, TableRows and TableCells

Implements the standard composite control pattern

Implements INamingContainer

Overrides Controls property to ensure child controls

Overrides CreateChildControls to implement logic of creating child controls

Page 9: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Data-Bound Control

Provides a DataSource propertypublic IEnumerable DataSource { get; set; }

Typically use a suitable collection interfaceE.g., IEnumerable, ICollection, or IList

Creates control hierarchyUsing the assigned data source on DataBind()Using ViewState on postback

Overrides DataBind() method to enumerate objects in the assigned data source

Page 10: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Data-Bound ControlsBasic Implementation Pattern

Create same control tree with and without a data source

void CreateControlHierarchy(bool useDataSource);

protected override void CreateChildControls() { Controls.Clear(); CreateControlHierarchy(false);}

protected override void DataBind() { OnDataBinding(EventArgs.Empty); Controls.Clear(); ClearChildViewState(); CreateControlHierarchy(true);}

Page 11: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Styles

Implement Styles as get-only properties. Create Styles on-demand

public virtual Style ItemStyle { get { if (_itemStyle == null) _itemStyle = new Style(); return _itemStyle; }}

Use by applying styles to controls during Render

if (_itemStyle != null) item.ApplyStyle(_itemStyle);

Page 12: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Styles

Merging multiple stylesAlternatingItem is also an Item

AlternatingItem’s should have both ItemStyle and AlternatingItemStyle applied

TableItemStyle altStyle = _itemStyle;if (_altItemStyle != null) { altStyle = new TableItemStyle(); altStyle.CopyFrom(_itemStyle); altStyle.CopyFrom(_altItemStyle);}

Page 13: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

State Management

Override various methods to perform custom state management

TrackViewState

SaveViewState

LoadViewState

Required any time you have nested objects like Styles or collection properties

Call on IStateManager implementation of these objects to include their state as part of Control’s state

Page 14: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

State Management

TrackViewStateif (_itemStyle != null) { ((IStateManager)_itemStyle).TrackViewState();}

SaveViewStateif (_itemStyle != null) { state[1] = ((IStateManager)_itemStyle).SaveViewState();}

LoadViewStateif (state[1] != null) { ((IStateManager)ItemStyle).LoadViewState(state[1]);}

On-demand Creationif (IsTrackingViewState) { ((IStateManager)_itemStyle).TrackViewState();}

Page 15: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Templates

Implement templates as simple get/set properties

public ITemplate CaptionTemplate { get { return _captionTemplate; } set { _captionTemplate = value; }}

Parser creates and assigns templateInstantiate as part of creating child controls

_captionControl = new Control();_captionTemplate.InstantiateIn(_captionControl);

Page 16: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

DataBoundTable Designer

Offers a design-time experience to DataBoundTable

Picking a DataSource in the property grid

Sample rendering of DataBoundTable

Template editing

Page 17: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Design-Time Overview

Behavior through metadataBrowsable, Category, Description attributes on properties

DefaultProperty, DefaultEvent attributes on Controls

Enhanced property editing through TypeConverters and UITypeEditors

Dropdown for Color properties

Page 18: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Design-Time Overview

Control DesignersCustomize rendering on design surface

Showing sample data in DataGrid

Manipulate a control to ensure meaningful design-time display

Text on Label

Template editingIn-place editing of DataList templates

Page 19: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

DataBoundTable DataBoundTable Design-timeDesign-time

Usage Demo,Usage Demo,Building Building DataBoundTableDesignerDataBoundTableDesigner

Page 20: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Metadata Attributes

Declarative way to specify behaviorDefaultProperty class metadataDefaultValue, Category, Description, Bindable etc. property metadata

[ DefaultProperty(“DataSource”), DefaultEvent(“SelectedIndexChanged”)]public class DataBoundTable : WebControl { [ Category(“Behavior"), DefaultValue(false), Description(“Toggles row selection") ] public bool EnableSelection { get { ... } set { ... } }}

Page 21: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Enhanced Property Editing

Customize conversion to/from a string using a TypeConverter

Specify a UITypeEditor using EditorAttribute

[ Editor( typeof(System.Web.UI.Design.ImageUrlEditor), typeof(UITypeEditor))]public string BackImageUrl { ... }

Page 22: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Control Designers

Derives from System.Web.UI.Design.ControlDesigner

Associate using DesignerAttribute

Typically used to provide a customized design-time rendering

[Designer(typeof(Microsoft.Samples.TechEd2003.

WebControls.Design.DataBoundTableDesigner))]public class DataBoundTable : WebControl { … }

Page 23: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Design-Time HTML

public string GetDesignTimeHtml() { string designTimeHtml = “”; try { // modify runtime control here // then render the control designTimeHtml = base.GetDesignTimeHtml(); } catch (Exception e) { designTimeHtml = GetErrorDesignTimeHtml(e); } finally { // restore runtime control to original state } if (designTimeHtml.Length == 0) { designTimeHtml = GetEmptyDesignTimeHtml(); } return designTimeHtml;}

Page 24: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

DataSource Property at Design-Time

DataSource is persisted as a data-binding

<sample:DataBoundTable DataSource=“<%# dataView1 %>” … >

Designer implements its own version of DataSource property which works on top of the DataBindings collection of a control

Use the selected data source to generate sample data and data-bind to it at design-time as part of their GetDesignTimeHtml() implementation

Page 25: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

DataSource Property at Design-Timepublic string DataSource { get { DataBinding binding = DataBindings["DataSource"]; if (binding != null) { return binding.Expression; } return String.Empty; } set { if ((value == null) || (value.Length == 0)) { DataBindings.Remove("DataSource"); } else { DataBinding binding = DataBindings["DataSource"]; if (binding == null) { binding = new DataBinding("DataSource", typeof(IEnumerable), value); DataBindings.Add(binding); } else { binding.Expression = value; } } OnBindingsCollectionChanged("DataSource"); }}

Page 26: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

DataSource Property at Design-time

Designer’s property replaces runtime property using property filtering, and is associated with a TypeConverter that implements a picker dropdown

protected override void PreFilterProperties(IDictionary properties) {

base.PreFilterProperties(properties);

PropertyDescriptor prop = (PropertyDescriptor)properties["DataSource"]; prop = TypeDescriptor.CreateProperty(this.GetType(), prop, new Attribute[] { new

TypeConverterAttribute(typeof(DataSourceConverter))});

properties["DataSource"] = prop;}

Page 27: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Template Editing

Derive your designer from TemplatedControlDesigner

Implement abstract methodsGetCachedTemplateEditingVerbs

CreateTemplateEditingFrame

GetTemplateContent

SetTemplateContent

Use ITemplateEditingService and TemplatedControlDesigner helper methods

Page 28: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Template Editing In Action

GetCachedTemplateEditingVerbsGetCachedTemplateEditingVerbs

CreateTemplateEditingFrameCreateTemplateEditingFrame

GetTemplateContentGetTemplateContent

SetTemplateContentSetTemplateContent

Page 29: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Template Editing

Step 1: GetCachedTemplateEditingVerbsProvide list of verbs shown in context menuNew TemplateEditingVerb(…)

Step 2: CreateTemplateEditingFrameProvide information about templates associated with a TemplateEditingVerb

Step 3: GetTemplateContentUse GetTextFromTemplate helper

Step 4: SetTemplateContentUse GetTemplateFromText helper

Page 30: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Debugging Designers

In your control project:Set the “Start Application” to devenv.exe

Set “Debug mode” to Program

Set breakpoints in your designer or control code

F5

In the new Visual Studio .NET instance:Create a Web application

Add a reference to your control assembly

Drop your control on a web form

Page 31: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Key Take Aways

Create controls with higher degree of abstraction

Simplify app development, reusabilityUse styles and templates to provide customizability

Provide rich design-time experienceVisual representation in designerCustom editing metaphors

Controls are the most important extensibility mechanism of ASP.NET

Huge range of third-party opportunities

Page 32: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Essential ResourcesDeveloping Microsoft ASP.NET Server Controls and Components

ASP.NET Forums at http://www.asp.net/forums

MSDN and .NET Framework SDK Documentation

ISBN 0-7356-1582-9Download

Source Code

Design Guidelines

http://www.microsoft.com/mspress/books/5728.asp

Page 33: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Ask The ExpertsGet Your Questions Answered

Page 34: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Community Resources

Community Resourceshttp://www.microsoft.com/communities/default.mspx

Most Valuable Professional (MVP)http://www.mvp.support.microsoft.com/

NewsgroupsConverse online with Microsoft Newsgroups, including Worldwidehttp://www.microsoft.com/communities/newsgroups/default.mspx

User GroupsMeet and learn with your peershttp://www.microsoft.com/communities/usergroups/default.mspx

Page 35: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Suggested Reading And Resources

The tools you need to put technology to work!The tools you need to put technology to work!

TITLETITLE AvailableAvailable

Microsoft® ASP.NET Microsoft® ASP.NET Programming with Microsoft Programming with Microsoft Visual C#® .NET Version 2003 Visual C#® .NET Version 2003 Step By Step:0-7356-1935-2Step By Step:0-7356-1935-2

TodayToday

Microsoft® ASP.NET Setup and Microsoft® ASP.NET Setup and Configuration Pocket Configuration Pocket Reference: 0-7356-1936-0Reference: 0-7356-1936-0

TodayToday

Microsoft Press books are 20% off at the TechEd Bookstore

Also buy any TWO Microsoft Press books and get a FREE T-Shirt

Page 36: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Related Talks

DEV 200, DEV 201: Introducing ASP.NET

DEV 300: Building ASP.NET Controls, Part I: The Basics

DEV 400: Black Belt WebForms Programming

DEV 402: Extending the ASP.NET Runtime

Page 37: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Community Resources

Community Resourceshttp://www.microsoft.com/communities/default.mspx

Most Valuable Professional (MVP)http://www.mvp.support.microsoft.com/

NewsgroupsConverse online with Microsoft Newsgroups, including Worldwidehttp://www.microsoft.com/communities/newsgroups/default.mspx

User GroupsMeet and learn with your peershttp://www.microsoft.com/communities/usergroups/default.mspx

Page 38: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Questions And Answers

Page 39: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

evaluationsevaluations

Page 40: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

© 2003 Microsoft Corporation. All rights reserved.© 2003 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.This presentation is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.

Page 41: DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager Microsoft Corp.

Abstract

Explore advanced control building topics, including state management, composition, templates, data-binding, and providing rich design-time support for tools like Visual Studio .NET. Step through a complete real-world control - the “DataBoundTable” built end-to-end. Attendees should be familiar with creating basic ASP.NET server controls.