DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager...
-
Upload
philip-robinson -
Category
Documents
-
view
216 -
download
0
Transcript of DEV401 Developing ASP.NET Server Controls - Part II: Adv Topics Tony Goodhew Product Manager...
DEV401
Developing ASP.NET Server Controls - Part II: Adv Topics
Tony GoodhewProduct ManagerMicrosoft 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
ASP.NET Control Gallery
http://www.asp.net
Lots of ISV-written controls are available
Extensibility is a feature
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)
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
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>
DataBoundTableDataBoundTable
Usage Demo,Usage Demo,Building DataBoundTableBuilding DataBoundTable
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
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
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);}
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);
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);}
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
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();}
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);
DataBoundTable Designer
Offers a design-time experience to DataBoundTable
Picking a DataSource in the property grid
Sample rendering of DataBoundTable
Template editing
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
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
DataBoundTable DataBoundTable Design-timeDesign-time
Usage Demo,Usage Demo,Building Building DataBoundTableDesignerDataBoundTableDesigner
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 { ... } }}
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 { ... }
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 { … }
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;}
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
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"); }}
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;}
Template Editing
Derive your designer from TemplatedControlDesigner
Implement abstract methodsGetCachedTemplateEditingVerbs
CreateTemplateEditingFrame
GetTemplateContent
SetTemplateContent
Use ITemplateEditingService and TemplatedControlDesigner helper methods
Template Editing In Action
GetCachedTemplateEditingVerbsGetCachedTemplateEditingVerbs
CreateTemplateEditingFrameCreateTemplateEditingFrame
GetTemplateContentGetTemplateContent
SetTemplateContentSetTemplateContent
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
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
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
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
Ask The ExpertsGet Your Questions Answered
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
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
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
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
Questions And Answers
evaluationsevaluations
© 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.
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.