Download DEV330 Building ASP.NET Server Controls - The Basics

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Team Foundation Server wikipedia , lookup

C Sharp (programming language) wikipedia , lookup

Transcript
DEV300
Building ASP.NET Server
Controls - Part I: The Basics
Tony Goodhew
Product Manager
Microsoft Corp
Agenda
Introduction
Basic control authoring topics
(with demos)
Implementing properties
Rendering
Raising Events
Adding client-side behavior with script
Extending existing controls
Compositing existing controls
Building controls in Visual Studio .NET
ASP.NET Control Gallery
http://www.asp.net
Lots of ISVwritten controls
are available
Extensibility is a
feature
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.
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
demo
From Pages To Controls
Declarative markup in an .aspx Page
Re-factor markup into an .ascx User
Control
Reusable behavior packaged as a
custom Control
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
Control Authoring Basics
ColoredLabel
ActiveLabel
HoverLabel
BulletedList
RequiredTextField
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
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
demo
ColoredLabel
State managed properties,
Rendering
Text Property
[ Bindable(true), Category("Appearance"),
DefaultValue(""), Description(“...") ]
public String Text {
get {
object o = ViewState[“Text"];
if (o == null)
return String.Empty;
else
return (string)o;
}
set {
ViewState[“Text"] = value;
}
}
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();
}
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
demo
ActiveLabel
Implementing a Click event,
Mapping a browser event into a
server action
Event Implementation
Standard event pattern has two parts
Event declaration
On<Event> protected virtual method
public event EventHandler Click;
protected virtual void OnClick(EventArgs e) {
if (Click != null) {
Click(this,e);
}
}
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
Raising The Server Event
Control implements
IPostBackEventHandler
Page framework calls control’s
RaisePostBackEvent() method
public class ActiveLabel :
ColoredLabel, IPostBackEventHandler {
void RaisePostBackEvent(string eventArg) {
OnClick(EventArgs.Empty);
}
}
Raising A Server Event
Mapping a browser event to server event
IPostBackEventHandler
ASP.NET Server App
Click!
Button1
Button1 .RaisePostBackEvent()
Control
raises OnClick()
Control
Control
HTTP form post
Controls registered to receive
post-back event notification
calls event handler
Button1_Click()
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
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
demo
HoverLabel
Using JavaScript to provide rich
client-side functionality
BulletedList
Implementing a control by extending an
existing control
Extends ListControl
Gets a lot of implementation for “free”
ListItemCollection
Data-binding
Designer experience in VS.NET
Overrides the rendering functionality
Renders an HTML unordered list <UL>
demo
BulletedList
Authoring new controls by
deriving from existing controls
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
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>
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
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
demo
RequiredTextField
Authoring new controls by
compositing existing controls
Composite Control Pattern
public class RequiredTextField :
Control, INamingContainer {
public override ControlCollection Controls {
get {
EnsureChildControls();
return base.Controls;
}
}
protected override void CreateChildControls() {
...
}
}
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("&nbsp;"));
Controls.Add(req1);
}
Building Controls In Visual
Studio .NET
Setting up your Solution
Choosing a Tag Prefix
Choosing a Toolbox Glyph
Debugging your Control
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
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 .../>
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 
Debugging Your Control
1.
2.
3.
4.
5.
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
Essential Resources
Developing Microsoft ASP.NET Server
Controls and Components
ISBN 0-7356-1582-9
Download
Source Code
Design Guidelines
http://www.microsoft.com/mspress/books/572
8.asp
ASP.NET Forums at http://www.asp.net/forums
MSDN and .NET Framework SDK Documentation
Related Talks
DEV 401: Building ASP.NET Controls,
Part II: Advanced Topics
Right here, << INSERT RIGHT TIME>>
DEV 200, DEV 201: Introducing ASP.NET
DEV 400: Black Belt WebForms
Programming
DEV 402: Extending the ASP.NET
Runtime
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
Questions… And Answers
Suggested Reading And Resources
The tools you need to put technology to work!
TITLE
Microsoft® ASP.NET
Programming with Microsoft
Visual C#® .NET Version 2003
Step By Step:0-7356-1935-2
Microsoft® ASP.NET Setup and
Configuration Pocket
Reference: 0-7356-1936-0
Available
Today
Today
Microsoft Press books are 20% off at the TechEd Bookstore
Also buy any TWO Microsoft Press books and get a FREE T-Shirt
Community Resources
Community Resources
http://www.microsoft.com/communities/default.mspx
Most Valuable Professional (MVP)
http://www.mvp.support.microsoft.com/
Newsgroups
Converse online with Microsoft Newsgroups, including Worldwide
http://www.microsoft.com/communities/newsgroups/default.mspx
User Groups
Meet and learn with your peers
http://www.microsoft.com/communities/usergroups/default.mspx
evaluations
© 2003 Microsoft Corporation. All rights reserved.
This presentation is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.
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 clientside DHTML behavior. Implement new
controls by extending or reusing existing
server controls. Assumes a working
knowledge of ASP.NET pages, controls, postback and view-state.