Title: The ASP'NET AJAX Extensions
1The ASP.NET AJAX Extensions
- Jeff Prosise
- Cofounder, Wintellect
- www.wintellect.com
2Architecture
ASPX
ASMX
ASP.NET AJAX Extensions
Application Services Bridge
Server Controls
Asynchronous Communications
ASP.NET 2.0
Page Framework Server Controls
Application Services
3Server Controls
Script Management
Partial-Page Rendering
Futures CTP
UpdatePanel
ScriptManager
DragOverlay- Extender
Update- Progress
ScriptManager- Proxy
ProfileService
Timer
4ScriptManager
- Starting point for ASP.NET AJAX pages
- What does ScriptManager do?
- Downloads JavaScript files to client
- Enables partial-page rendering using UpdatePanel
- Provides access to Web services from client
- Manages callback timeouts and provides error
handling options and infrastructure and more - Every page requires one ScriptManager!
5ScriptManager Schema
ltaspScriptManager ID"ScriptManager1"
Runat"server" EnablePartialRendering"truefals
e" EnablePageMethods"truefalse"
AsyncPostBackTimeout"seconds"
AsyncPostBackErrorMessage"message"
AllowCustomErrorsRedirect"truefalse"
OnAsyncPostBackError"handler"
EnableScriptGlobalization"truefalse"
EnableScriptLocalization"truefalse"
ScriptMode"AutoInheritDebugRelease"
ScriptPath"path"gt ltScriptsgt lt!-- Declare
script references here --gt lt/Scriptsgt
ltServicesgt lt!-- Declare Web service
references here --gt lt/Servicesgt lt/aspScriptMana
gergt
6Script References
"Name" references load script resources
ltaspScriptManager ID"ScriptManager1"
Runat"server"gt ltScriptsgt
ltaspScriptReference Name"PreviewScript.js"
Assembly"Microsoft.Web.Preview" /gt
ltaspScriptReference Name"PreviewDragDrop.js"
Assembly"Microsoft.Web.Preview" /gt
ltaspScriptReference Path"/Scripts/UIMap.js"
/gt lt/Scriptsgt lt/aspScriptManagergt
"Path" references load script files
7Service References
ltaspScriptManager ID"ScriptManager1"
Runat"server"gt ltServicesgt
ltaspServiceReference Path"ZipCodeService.asmx"
/gt lt/Servicesgt lt/aspScriptManagergt
8ScriptManagerProxy
- "Proxy" for ScriptManager controls declared in
master pages - Lets content pages declare script and service
references
ltaspScriptManagerProxy ID"ScriptManagerProxy1"
Runat"server"gt ltScriptsgt lt!-- Declare
additional script references here --gt
lt/Scriptsgt ltServicesgt lt!-- Declare
additional service references here --gt
lt/Servicesgt lt/aspScriptManagerProxygt
9UpdatePanel
- Partial-page rendering in a box
- Clean round trips and flicker-free updates
- Leverages client-side PageRequestManager
- EnablePartialRendering"true" in ScriptManager
- Supports explicitly defined triggers
- By default, postbacks from all controls in an
UpdatePanel are converted into async callbacks - Triggers expand/shrink postback-gtcallback scope
- Works in virtually all scenarios
10UpdatePanel Schema
ltaspScriptManager ID"ScriptManager1"
Runat"server" EnablePartialRendering"true"
/gt . . . ltaspUpdatePanel
ID"UpdatePanel1" Runat"server"
UpdateMode"AlwaysConditional"
ChildrenAsTriggers"truefalse"gt ltTriggersgt
lt!-- Define triggers (if any) here --gt
lt/Triggersgt ltContentTemplategt lt!-- Define
content here --gt lt/ContentTemplategt lt/aspUpdate
Panelgt
11Triggers
- AsyncPostBackTrigger
- Converts postbacks into asynchronous callbacks
- Typically used to trigger updates when controls
outside an UpdatePanel post back and fire events - If ChildrenAsTriggers"false", specifies which
controls should call back rather than post back - PostBackTrigger
- Allows controls inside UpdatePanel to post back
12Triggers Example
ltaspUpdatePanel ID"UpdatePanel1"
Runat"server" UpdateMode"Conditional"gt
ltTriggersgt ltaspAsyncPostBackTrigger
ControlID"Button1" /gt ltaspAsyncPostBackTrigg
er ControlID"TreeView1" EventName"TreeNode
Expanded" /gt ltaspAsyncPostBackTrigger
ControlID"TreeView1" EventName"TreeNodeCol
lapsed" /gt ltaspPostBackTrigger
ControlID"Button2" /gt lt/Triggersgt
ltContentTemplategt ... lt/ContentTemplategt lt/a
spUpdatePanelgt
13Periodic Updates
- Combine UpdatePanel with Timer control to perform
periodic updates - Use Timer control Tick events as triggers
ltaspTimer ID"Timer1" Runat"server"
Interval"5000" OnTick"OnTimerTick" /gt
... ltaspUpdatePanel UpdateMode"Conditional"
...gt ltTriggersgt ltaspAsyncPostBackTrigger
ControlID"Timer1" /gt lt/Triggersgt
... lt/aspUpdatePanelgt
14(No Transcript)
15UpdateProgress
- Companion to UpdatePanel controls
- Displays custom template-driven UI for
- Indicating that an async update is in progress
- Canceling an async update that is in progress
- Automatically displayed when update begins or
"DisplayAfter" interval elapses
16UpdateProgress Schema
ltaspUpdateProgress ID"UpdateProgress1"
Runat"server" DisplayAfter"milliseconds"
DynamicLayout"truefalse" AssociatedUpdatePanel
ID"UpdatePanelID"gt ltProgressTemplategt lt!--
Declare UpdateProgress UI here --gt
lt/ProgressTemplategt lt/aspUpdateProgressgt
17UpdateProgress Example
Display after ½ second
ltaspUpdateProgress DisplayAfter"500" ...gt
ltProgressTemplategt ltaspImage
ID"ProgressImage" Runat"server"
ImageUrl"/Images/SpinningClock.gif" /gt
lt/ProgressTemplategt lt/aspUpdateProgressgt
Animated GIF
18Canceling an Update
ltaspUpdateProgress DisplayAfter"500" ...gt
ltProgressTemplategt ltbgtWorking...lt/bgt
ltaspButton ID"CancelButton" Runat"server"
Text"Cancel" OnClientClick"cancelUpdate()
return false" /gt lt/ProgressTemplategt lt/aspUpda
teProgressgt ltscript type"text/javascript"gt funct
ion cancelUpdate() var obj
Sys.WebForms.PageRequestManager.getInstance()
if (obj.get_isInAsyncPostBack())
obj.abortPostBack() lt/scriptgt
19(No Transcript)
20ASP.NET AJAX Web Services
- ASP.NET AJAX supports ASMX Web methods as
endpoints for asynchronous AJAX callbacks - Efficient on the wire (no SOAP or XML)
- Efficient on the server (no page lifecycle)
- ScriptService attribute on server indicates Web
service is callable from client-side script - JavaScript proxy on client enables JavaScript
clients to call Web methods on server
21Script-Callable Web Service
System.Web.Script.Services.ScriptService public
class ZipCodeService System.Web.Services.WebServ
ice System.Web.Services.WebMethod
public string GetCityAndState (string zip)
...
22Declaring a Service Reference
ltaspScriptManager ID"ScriptManager1"
Runat"server"gt ltServicesgt
ltaspServiceReference Path"ZipCodeService.asmx"
/gt lt/Servicesgt lt/aspScriptManagergt
23Consuming a Web Service
ZipCodeService.GetCityAndState("98052",
onCompleted) . . . function onCompleted
(result) window.alert(result)
24Handling Errors
ZipCodeService.GetCityAndState("98052",
onCompleted, onFailed) . . . function
onCompleted (result, context, methodName)
window.alert(result) function onFailed (err,
context, methodName) window.alert(err.get_me
ssage())
25(No Transcript)
26ASMX Wire Format
Request
POST /AtlasRC/ZipCodeService.asmx/GetCityAndState
HTTP/1.1 Accept / Accept-Language
en-us Referer http//localhost1997/AtlasRC/ZipCo
dePage.aspx UA-CPU x86 Accept-Encoding gzip,
deflate User-Agent Mozilla/4.0 (compatible MSIE
7.0 ...) Host localhost1997 Content-Length
15 Connection Keep-Alive Cache-Control
no-cache "zip""98052"
Response
HTTP/1.1 200 OK Server ASP.NET Development
Server/8.0.0.0 Date Fri, 29 Dec 2006 210617
GMT X-AspNet-Version 2.0.50727 Cache-Control
private, max-age0 Content-Type
application/json charsetutf-8 Content-Length
16 Connection Close "REDMOND","WA"
JSON-encoded input
JSON-encoded output
27ScriptHandlerFactory
- Wraps (replaces) default ASMX handler
- Extends ASMX model with "special" URLs
- JavaScript proxy generation (.asmx/js)
- Calls to Web methods (.asmx/methodname)
lthttpHandlersgt ltremove verb"" path".asmx"
/gt ltadd verb"" path".asmx"
validate"false" type"System.Web.Script.Servi
ces.ScriptHandlerFactory, System.Web.Extension
s, ..." /gt lt/httpHandlersgt
28ASMX Request Handling
ASMX Extensions
ScriptHandler- Factory
RestClient- ProxyHandler
Helper Classes
.asmx
.asmx/js
RestHandler
.asmx/methodname
"Normal" ASMX calls
WebService- HandlerFactory
Default ASMX handler
29JSON
- JavaScript Object Notation
- Lightweight data interchange format
- Easier to read and write than XML
- Based on subset of JavaScript
- Default interchange format in ASP.NET AJAX
- Microsoft.Web.Script.-Serialization.JavaScriptSeri
alizer - Sys.Serialization.-JavaScriptSerializer
- JSON home page www.json.org
30JSON vs. XML
Point p new Point(100, 200)
31The ScriptMethod Attribute
- Optional attribute for script-callable Web
methods - Offers added control over wire format of calls
Property
Description
UseHttpGet
True Use HTTP GET, False Use HTTP POST
(default)
ResponseFormat
ResponseFormat.Xml or ResponseFormat.Json
(default)
XmlSerializeString
True Serialize everything (including strings)
as XML, False Serialize response strings as
JSON (default) (Only valid if ResponseFormat
ResponseFormat.Xml)
32Using ScriptMethod
System.Web.Script.Services.ScriptService public
class ZipCodeService System.Web.Services.WebServ
ice System.Web.Services.WebMethod
System.Web.Script.Services.ScriptMethod
(ResponseFormatResponseFormat.Xml) public
XmlDocument GetCityAndState (string zip)
...
Method returns XML document, so serialize as XML
rather than JSON
33Page Methods
- Script-callable Web methods built into pages
- Simpler than writing a full-blown Web service
- Do not require service references
- Do not require dedicated ASMX files
- Must be public static methods
- Must be enabled via ScriptManager.-EnablePageMetho
ds (disabled by default) - Called through PageMethods proxy on client
34Enabling Page Methods
ltaspScriptManager ID"ScriptManager1"
EnablePageMethods"true" Runat"server" /gt
35Defining a Page Method
public partial class MyPage System.Web.UI.Page
System.Web.Services.WebMethod public
static string GetCityAndState (string zip)
... ...
36Calling a Page Method
PageMethods.GetCityAndState("98052",
onComplete) . . . function
onComplete(result) window.alert(result)
37(No Transcript)
38Built-In Web Services
- AuthenticationService
- Front end to ASP.NET 2.0 membership service
- Use Sys.Services.AuthenticationService proxy
- Global instance of Sys.Services._AuthenticationSer
vice - ProfileService
- Front-end to ASP.NET 2.0 profile service
- Use Sys.Services.Profile proxy
- Global instance of Sys.Services._ProfileService
- Accessed through ScriptHandlerFactory
39Using AuthenticationService
Sys.Services.AuthenticationService.login
(username, password, false, null, null,
onLoginCompleted, onLoginFailed)
... function onLoginCompleted(result, context,
methodName) window.alert(result ? 'Login
succeeded' 'Login failed') function
onLoginFailed(err, context, methodName)
window.alert(err.get_message())
40Loading Profile Properties
Pass null to load all profile properties
Sys.Services.ProfileService.load('ScreenName',
onLoadCompleted, onLoadFailed)
... function onLoadCompleted(result, context,
methodName) window.alert(Sys.Services.ProfileS
ervice.properties.ScreenName) function
onLoadFailed(err, context, methodName)
window.alert(err.get_message())
41Saving Profile Properties
Pass null to save all profile properties
Sys.Services.ProfileService.properties.ScreenName
'Bob' Sys.Services.ProfileService.save('Screen
Name', onSaveCompleted, onSaveFailed)
... function onSaveCompleted(result, context,
methodName) window.alert('Save
succeeded') function onSaveFailed(err,
context, methodName) window.alert(err.get_me
ssage())
42(No Transcript)