ASP.NET Server Controls

53
ASP.NET Server Controls ASP.NET Server Controls Presented By: Presented By: Robin Lilly Robin Lilly iLogbook iLogbook

description

ASP.NET Server Controls. Presented By: Robin Lilly iLogbook. Agenda. Introduction Basic control authoring topics Implementing properties Rendering Raising Events Extending existing controls Compositing existing controls. Agenda. Build some real world examples 2 ADA controls Label - PowerPoint PPT Presentation

Transcript of ASP.NET Server Controls

Page 1: ASP.NET Server Controls

ASP.NET Server ControlsASP.NET Server Controls

Presented By: Presented By: Robin LillyRobin LillyiLogbookiLogbook

Page 2: ASP.NET Server Controls

AgendaAgenda IntroductionIntroduction Basic control authoring topicsBasic control authoring topics

Implementing propertiesImplementing properties RenderingRendering Raising EventsRaising Events Extending existing controlsExtending existing controls Compositing existing controlsCompositing existing controls

Page 3: ASP.NET Server Controls

AgendaAgenda Build some real world examplesBuild some real world examples

2 ADA controls 2 ADA controls LabelLabel

<label for=<%=ClientID%>Name</label>, <label for=<%=ClientID%>Name</label>, TextboxTextbox

Inherited textbox that implements onfocus & onblurInherited textbox that implements onfocus & onblur Inspect a Shopping CartInspect a Shopping Cart

Composite ControlComposite Control Inspect codeInspect code

CreateChildControls()CreateChildControls() BackButton prevention via session stateBackButton prevention via session state

PropertiesProperties UI Type EditorUI Type Editor EventsEvents State Management – View State and SessionState Management – View State and Session

Page 4: ASP.NET Server Controls

What Is A Server Control?What Is A Server Control?

A server control is a .NET component A server control is a .NET component that is used to generate the user that is used to generate the user interface of an ASP.NET Web application.interface of an ASP.NET Web application.

It is implemented as a managed class It is implemented as a managed class deriving directly or indirectly from the deriving directly or indirectly from the System.Web.UI.Control base class.System.Web.UI.Control base class.

Page 5: ASP.NET Server Controls

What Is A Server Control?What Is A Server Control?Speaking More Practically…Speaking More Practically…

A Web user interface elementA Web user interface element Renders into HTML, script or a different markup formatRenders into HTML, script or a different markup format Allows customization of renderingAllows customization of rendering

A Web user interface componentA Web user interface component Exposes properties, events and methods and is Exposes properties, events and methods and is

programmableprogrammable Provides higher level abstractionsProvides higher level abstractions

Performs post-back processingPerforms post-back processing Handles differences between browsersHandles differences between browsers Consistent programming modelConsistent programming model

A RAD component that offers aA RAD component that offers adesign-time experiencedesign-time experience

Page 6: ASP.NET Server Controls

2 Ways To Author2 Ways To AuthorServer ControlsServer Controls

User ControlsUser Controls Simple, declarative authoring model (.ascx file)Simple, declarative authoring model (.ascx file) Scoped to a single applicationScoped to a single application Well suited to static content and layoutWell suited to static content and layout

““Custom” or Compiled ControlsCustom” or Compiled Controls Code-based authoring model (.cs or .vb class file)Code-based authoring model (.cs or .vb class file) Easily shared across applicationsEasily shared across applications Well suited to dynamic or programmatic Well suited to dynamic or programmatic

generation of content and layoutgeneration of content and layout More complex, but also more capabilitiesMore complex, but also more capabilities

Page 7: ASP.NET Server Controls

Setting up your SolutionSetting up your Solution Use a WebControlLibrary project to Use a WebControlLibrary project to

create custom compiled controlscreate custom compiled controls Initialize the Version attributeInitialize the Version attribute Add a Web app to test controlsAdd a Web app to test controls

Solution > Add New > Web ApplicationSolution > Add New > Web Application Add a ToolBox referenceAdd a ToolBox reference

Customize Toolbox > BrowseCustomize Toolbox > Browse

Page 8: ASP.NET Server Controls

RenderingRendering Override Render to representative markupOverride Render to representative markup Use HtmlTextWriter API to implement Use HtmlTextWriter API to implement

rendering logicrendering logic

public override void Render(HtmlTextWriter writer) {public override void Render(HtmlTextWriter writer) {

writer.RenderBeginTag(HtmlTextWriterTag.Span);writer.RenderBeginTag(HtmlTextWriterTag.Span);

writer.Write(Text);writer.Write(Text);

writer.RenderEndTag();writer.RenderEndTag();

}}

Page 9: ASP.NET Server Controls

Custom Toolbox GlyphCustom Toolbox Glyph Bitmap file with same base name as Bitmap file with same base name as

control class in the same namespacecontrol class in the same namespace TextBoxADATextBoxADA

Build Action = “Embedded Resource”Build Action = “Embedded Resource” Image properties:Image properties:

File type supported is bitmapFile type supported is bitmap 16x16 pixels16x16 pixels Lower-left pixel is used to determine Lower-left pixel is used to determine

transparencytransparency Adds an extra professional touchAdds an extra professional touch

Page 10: ASP.NET Server Controls

Building Controls In Visual Building Controls In Visual Studio .NETStudio .NET

Setting up your SolutionSetting up your Solution Choosing a Tag PrefixChoosing a Tag Prefix Choosing a Toolbox GlyphChoosing a Toolbox Glyph Debugging your ControlDebugging your Control

Page 11: ASP.NET Server Controls

What is the ADA?What is the ADA?

Defines web accessibilityDefines web accessibility American Disabilities Act or US Section American Disabilities Act or US Section

508 compliance 508 compliance http://www.section508.gov/http://www.section508.gov/ http://www.usdoj.gov/crt/ada/adahom1.http://www.usdoj.gov/crt/ada/adahom1.htmhtm

Universities and Governments are Universities and Governments are required to implement.required to implement.

Page 12: ASP.NET Server Controls

Some Requirements for ADASome Requirements for ADA

Input controls must have a description of Input controls must have a description of the input item.the input item.

Page 13: ASP.NET Server Controls

Requirements for ADARequirements for ADA

Lets see it in action Lets see it in action http://localhost/serverregistration/registrahttp://localhost/serverregistration/registration2.aspxtion2.aspx

Page 14: ASP.NET Server Controls

ADALabelADALabel Simple, minimal controlSimple, minimal control

Renders a <label for=clientid>Name</label> Renders a <label for=clientid>Name</label> Inherits from LiteralControlInherits from LiteralControl Metadata on propertiesMetadata on properties

Demonstrates state managementDemonstrates state management Uses ViewState in property implementationUses ViewState in property implementation

Demonstrates basic renderingDemonstrates basic rendering Render MethodRender Method

Page 15: ASP.NET Server Controls

ADATextBoxADATextBox

Simple, minimal controlSimple, minimal control Renders in TextBox Renders in TextBox

onfocus="if(this.value=='Enter Serial Number')value='';" onfocus="if(this.value=='Enter Serial Number')value='';" onblur="if(this.value=='')value='Enter Serial Number';“onblur="if(this.value=='')value='Enter Serial Number';“ Inherits from LiteralControlInherits from LiteralControl

Inherits from TextBoxInherits from TextBox Demonstrates state managementDemonstrates state management

Uses ViewState in property implementationUses ViewState in property implementation Demonstrates basic renderingDemonstrates basic rendering

AddAttributesToRender methodAddAttributesToRender method

Page 16: ASP.NET Server Controls

ADATextBoxADATextBox Metadata on propertiesMetadata on properties

Declarative way of specifying behaviorDeclarative way of specifying behavior Property editing in property browserProperty editing in property browser Property persistenceProperty persistence Conversion of types to/from stringsConversion of types to/from strings

Metadata can be applied to events, Metadata can be applied to events, methods and types as wellmethods and types as well

Page 17: ASP.NET Server Controls

ADATextBoxADATextBoxADALabelADALabel

demodemo

State managed properties, State managed properties, RenderingRendering

Page 18: ASP.NET Server Controls

Composite ControlComposite Control Contains Table, TableRows and Contains Table, TableRows and

TableCells, Textbox, Button TableCells, Textbox, Button Implements the standard composite Implements the standard composite

control patterncontrol pattern Implements INamingContainerImplements INamingContainer Overrides Controls property to ensure Overrides Controls property to ensure

child controlschild controls Overrides CreateChildControls to Overrides CreateChildControls to

implement logic of creating child controlsimplement logic of creating child controls

Page 19: ASP.NET Server Controls

Why Our own Shopping Cart at Why Our own Shopping Cart at UTEPUTEP

Needed to call our own credit card api Needed to call our own credit card api – TOUCHNET internally– TOUCHNET internally

Needed to be reusable by all Needed to be reusable by all programmers programmers

Handle financial accounting Handle financial accounting transactions differently.transactions differently.

Nothing existed that solved the Nothing existed that solved the problemsproblems

Page 20: ASP.NET Server Controls

Shopping Cart CompositeShopping Cart Composite

Page 21: ASP.NET Server Controls

CreateChildControlsCreateChildControls

Page 22: ASP.NET Server Controls

AddDataGridAddDataGrid

Page 23: ASP.NET Server Controls

AddDataGrid (cont)AddDataGrid (cont)

Page 24: ASP.NET Server Controls

AddDataGrid (cont)AddDataGrid (cont)

Page 25: ASP.NET Server Controls

Event ImplementationEvent Implementation

Standard event pattern has two partsStandard event pattern has two parts Event declarationEvent declaration On<Event> protected virtual methodOn<Event> protected virtual method

Public Event FinishShopping as ShoppingEventHandler Public Event FinishShopping as ShoppingEventHandler Protected Sub OnFinishShopping(E as ShoppingEventArgs) Protected Sub OnFinishShopping(E as ShoppingEventArgs) RaiseEvent FinishShopping(Me,E)RaiseEvent FinishShopping(Me,E)End SubEnd Sub

Page 26: ASP.NET Server Controls

Events ImplementedEvents Implemented

SuccessShoppingSuccessShopping CancelShoppingCancelShopping FinishShoppingFinishShopping

Page 27: ASP.NET Server Controls

ShoppingEventArgs ShoppingEventArgs

Page 28: ASP.NET Server Controls

Shopping SessionShopping Session TableTable

Exists to prevent Recharges Exists to prevent Recharges Hitting the Back in Browser and then Hitting the Back in Browser and then

recharging the card for the same purchaserecharging the card for the same purchase

Page 29: ASP.NET Server Controls

Session State TableSession State Table

CreateSessionShoppingCartCreateSessionShoppingCart

Page 30: ASP.NET Server Controls

Shopping SessionShopping Session TableTable

IsSessionShoppingCartExistIsSessionShoppingCartExist

Page 31: ASP.NET Server Controls

Session State ProceduresSession State Procedures DeleteOldShoppingCartSessionsDeleteOldShoppingCartSessions

delete SessionShoppingCartdelete SessionShoppingCart

where CreateDate < DateAdd(day,-where CreateDate < DateAdd(day,-7,GetDate())7,GetDate())

Page 32: ASP.NET Server Controls

Add Item to CartAdd Item to Cart

Page 33: ASP.NET Server Controls

Shopping CartShopping Cart

demodemo

Page 34: ASP.NET Server Controls

CartDataCartData

Page 35: ASP.NET Server Controls

MySessionMySession

Page 36: ASP.NET Server Controls

EmptyCartEmptyCart

Used after Finish Shopping?Used after Finish Shopping?

Page 37: ASP.NET Server Controls

AddCreditCardAddCreditCard

Page 38: ASP.NET Server Controls

AddCreditCardAddCreditCard

Page 39: ASP.NET Server Controls

AddCreditCard (cont)AddCreditCard (cont)

Page 40: ASP.NET Server Controls

AddCreditCardAddCreditCard

Page 41: ASP.NET Server Controls

AddCreditCard(coAddCreditCard(cont)nt)

Page 42: ASP.NET Server Controls

Successful ChargeSuccessful Charge

Page 43: ASP.NET Server Controls

Charge Credit Card ButtonCharge Credit Card Button

Page 44: ASP.NET Server Controls
Page 45: ASP.NET Server Controls

Some of Public Style PropertiesSome of Public Style Properties

ItemHeaderText - get/setItemHeaderText - get/set DescriptionHeaderText – get/setDescriptionHeaderText – get/set QuantityHeaderText – get/setQuantityHeaderText – get/set PriceHeaderText – get/setPriceHeaderText – get/set AmountHeaderText – get/setAmountHeaderText – get/set DisplayQuantity – get/setDisplayQuantity – get/set DisplayGrid – get/setDisplayGrid – get/set DataGridCSSClass – get/set DataGrid StyleDataGridCSSClass – get/set DataGrid Style ValidateCSSClass – get/set Validator StylesValidateCSSClass – get/set Validator Styles RequireCSSClass – get/set Required Validator StylesRequireCSSClass – get/set Required Validator Styles DisplayErrorStar – get/set BoolDisplayErrorStar – get/set Bool DataGridBackColor – get/set ColorDataGridBackColor – get/set Color DataGridHeaderColor – get/set ColorDataGridHeaderColor – get/set Color DataGridForeColor – get/set ColorDataGridForeColor – get/set Color

Page 46: ASP.NET Server Controls

State ManagementState Management Session vs. View StateSession vs. View State View State:View State:

Override various methods to perform Override various methods to perform custom state managementcustom state management

TrackViewStateTrackViewState SaveViewStateSaveViewState LoadViewStateLoadViewState

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

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

Page 47: ASP.NET Server Controls

Key PointsKey Points Controls provide an abstraction and Controls provide an abstraction and

reusability mechanism for web appsreusability mechanism for web apps ASP.NET provides a rich framework for ASP.NET provides a rich framework for

creating server controlscreating server controls Create specialized derived controls to Create specialized derived controls to

make incremental changes tomake incremental changes toexisting controlsexisting controls

Use composition to leverage existing Use composition to leverage existing controls in more specialized scenarioscontrols in more specialized scenarios

Think about your Markup!!!!!Think about your Markup!!!!!

Page 48: ASP.NET Server Controls

Essential ResourcesEssential ResourcesDeveloping Microsoft ASP.NET Server Developing Microsoft ASP.NET Server Controls and ComponentsControls and Components

ASP.NET Forums at ASP.NET Forums at http://www.asp.net/forumshttp://www.asp.net/forums MSDN and .NET Framework SDK DocumentationMSDN and .NET Framework SDK Documentation

ISBN 0-7356-1582-9ISBN 0-7356-1582-9

DownloadDownload Source CodeSource Code Design GuidelinesDesign Guidelines

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

Page 49: ASP.NET Server Controls

http://www.ilogbook.com/http://www.ilogbook.com/

DownloadDownload

SamplesSamples

Page 50: ASP.NET Server Controls

Questions… And AnswersQuestions… And Answers

Page 51: ASP.NET Server Controls

Server ControlServer Control

Page 52: ASP.NET Server Controls
Page 53: ASP.NET Server Controls