42
Satisfy Your Technical Curiosity The ASP.NET AJAX The ASP.NET AJAX Extensions Extensions Jeff Prosise Jeff Prosise Cofounder, Wintellect Cofounder, Wintellect www.wintellect.com www.wintellect.com

Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Embed Size (px)

Citation preview

Page 1: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

The ASP.NET AJAX ExtensionsThe ASP.NET AJAX Extensions

Jeff ProsiseJeff ProsiseCofounder, WintellectCofounder, Wintellectwww.wintellect.comwww.wintellect.com

Page 2: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Architecture

ASP.NET 2.0

Page Framework & Server Controls

Page Framework & Server Controls

ApplicationServices

ApplicationServices

ASP.NET AJAX Extensions

ServerControls

ServerControls

ASPXASPX ASMXASMX

Application ServicesBridge

Application ServicesBridge

AsynchronousCommunications

AsynchronousCommunications

Page 3: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Server Controls

UpdatePanelUpdatePanel

Update-ProgressUpdate-Progress

TimerTimer

DragOverlay-Extender

DragOverlay-ExtenderScriptManagerScriptManager

ScriptManager-Proxy

ScriptManager-Proxy ProfileServiceProfileService

ScriptScriptManagementManagement

Partial-Page Partial-Page RenderingRendering Futures CTPFutures CTP

Page 4: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

ScriptManager

Starting point for ASP.NET AJAX pagesWhat does ScriptManager do?

Downloads JavaScript files to clientEnables partial-page rendering using UpdatePanelProvides access to Web services from clientManages callback timeouts and provides error handling options and infrastructure and more

Every page requires one ScriptManager!

Page 5: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

ScriptManager Schema

<asp:ScriptManager ID="ScriptManager1" Runat="server" EnablePartialRendering="true|false" EnablePageMethods="true|false" AsyncPostBackTimeout="seconds" AsyncPostBackErrorMessage="message" AllowCustomErrorsRedirect="true|false" OnAsyncPostBackError="handler" EnableScriptGlobalization="true|false" EnableScriptLocalization="true|false" ScriptMode="Auto|Inherit|Debug|Release" ScriptPath="path"> <Scripts> <!-- Declare script references here --> </Scripts> <Services> <!-- Declare Web service references here --> </Services></asp:ScriptManager>

Page 6: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Script References

<asp:ScriptManager ID="ScriptManager1" Runat="server"> <Scripts> <asp:ScriptReference Name="PreviewScript.js" Assembly="Microsoft.Web.Preview" /> <asp:ScriptReference Name="PreviewDragDrop.js" Assembly="Microsoft.Web.Preview" /> <asp:ScriptReference Path="~/Scripts/UIMap.js" /> </Scripts></asp:ScriptManager>

"Path" references load script files"Path" references load script files

"Name" references load script resources"Name" references load script resources

Page 7: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Service References

<asp:ScriptManager ID="ScriptManager1" Runat="server"> <Services> <asp:ServiceReference Path="ZipCodeService.asmx" /> </Services></asp:ScriptManager>

Page 8: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

ScriptManagerProxy

"Proxy" for ScriptManager controls declared in master pagesLets content pages declare script and service references

<asp:ScriptManagerProxy ID="ScriptManagerProxy1" Runat="server"> <Scripts> <!-- Declare additional script references here --> </Scripts> <Services> <!-- Declare additional service references here --> </Services></asp:ScriptManagerProxy>

Page 9: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

UpdatePanel

Partial-page rendering in a boxClean round trips and flicker-free updates

Leverages client-side PageRequestManagerEnablePartialRendering="true" in ScriptManager

Supports explicitly defined triggersBy default, postbacks from all controls in an UpdatePanel are converted into async callbacksTriggers expand/shrink postback->callback scope

Works in virtually all scenarios

Page 10: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

UpdatePanel Schema<asp:ScriptManager ID="ScriptManager1" Runat="server" EnablePartialRendering="true" /> . . .<asp:UpdatePanel ID="UpdatePanel1" Runat="server" UpdateMode="Always|Conditional" ChildrenAsTriggers="true|false"> <Triggers> <!-- Define triggers (if any) here --> </Triggers> <ContentTemplate> <!-- Define content here --> </ContentTemplate></asp:UpdatePanel>

Page 11: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Triggers

AsyncPostBackTriggerConverts postbacks into asynchronous callbacksTypically used to trigger updates when controls outside an UpdatePanel post back and fire eventsIf ChildrenAsTriggers="false", specifies which controls should call back rather than post back

PostBackTriggerAllows controls inside UpdatePanel to post back

Page 12: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Triggers Example

<asp:UpdatePanel ID="UpdatePanel1" Runat="server" UpdateMode="Conditional"> <Triggers> <asp:AsyncPostBackTrigger ControlID="Button1" /> <asp:AsyncPostBackTrigger ControlID="TreeView1" EventName="TreeNodeExpanded" /> <asp:AsyncPostBackTrigger ControlID="TreeView1" EventName="TreeNodeCollapsed" /> <asp:PostBackTrigger ControlID="Button2" /> </Triggers> <ContentTemplate> ... </ContentTemplate></asp:UpdatePanel>

Page 13: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Periodic Updates

Combine UpdatePanel with Timer control to perform periodic updatesUse Timer control Tick events as triggers

<asp:Timer ID="Timer1" Runat="server" Interval="5000" OnTick="OnTimerTick" /> ...<asp:UpdatePanel UpdateMode="Conditional" ...> <Triggers> <asp:AsyncPostBackTrigger ControlID="Timer1" /> </Triggers> ...</asp:UpdatePanel>

Page 14: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Page 15: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

UpdateProgress

Companion to UpdatePanel controlsDisplays custom template-driven UI for:

Indicating that an async update is in progressCanceling an async update that is in progress

Automatically displayed when update begins or "DisplayAfter" interval elapses

Page 16: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

UpdateProgress Schema

<asp:UpdateProgress ID="UpdateProgress1" Runat="server" DisplayAfter="milliseconds" DynamicLayout="true|false" AssociatedUpdatePanelID="UpdatePanelID"> <ProgressTemplate> <!-- Declare UpdateProgress UI here --> </ProgressTemplate></asp:UpdateProgress>

Page 17: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

UpdateProgress Example

<asp:UpdateProgress DisplayAfter="500" ...> <ProgressTemplate> <asp:Image ID="ProgressImage" Runat="server" ImageUrl="~/Images/SpinningClock.gif" /> </ProgressTemplate></asp:UpdateProgress>

Animated GIFAnimated GIF

Display after ½ secondDisplay after ½ second

Page 18: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Canceling an Update

<asp:UpdateProgress DisplayAfter="500" ...> <ProgressTemplate> <b>Working...</b> <asp:Button ID="CancelButton" Runat="server" Text="Cancel" OnClientClick="cancelUpdate(); return false" /> </ProgressTemplate></asp:UpdateProgress>

<script type="text/javascript">function cancelUpdate(){ var obj = Sys.WebForms.PageRequestManager.getInstance(); if (obj.get_isInAsyncPostBack()) obj.abortPostBack();}</script>

Page 19: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Page 20: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

ASP.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 scriptJavaScript proxy on client enables JavaScript clients to call Web methods on server

Page 21: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Script-Callable Web Service

[System.Web.Script.Services.ScriptService]public class ZipCodeService : System.Web.Services.WebService{ [System.Web.Services.WebMethod] public string[] GetCityAndState (string zip) { ... }}

Page 22: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Declaring a Service Reference

<asp:ScriptManager ID="ScriptManager1" Runat="server"> <Services> <asp:ServiceReference Path="ZipCodeService.asmx" /> </Services></asp:ScriptManager>

<script src="ZipCodeService.asmx/js" type="text/javascript"></script>

<script src="ZipCodeService.asmx/js" type="text/javascript"></script>

Page 23: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Consuming a Web Service

ZipCodeService.GetCityAndState("98052", onCompleted); . . .function onCompleted (result){ window.alert(result);}

Page 24: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Handling Errors

ZipCodeService.GetCityAndState("98052", onCompleted, onFailed); . . .function onCompleted (result, context, methodName){ window.alert(result);}

function onFailed (err, context, methodName){ window.alert(err.get_message());}

Page 25: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Page 26: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

ASMX Wire FormatPOST /AtlasRC/ZipCodeService.asmx/GetCityAndState HTTP/1.1Accept: */*Accept-Language: en-usReferer: http://localhost:1997/AtlasRC/ZipCodePage.aspxUA-CPU: x86Accept-Encoding: gzip, deflateUser-Agent: Mozilla/4.0 (compatible; MSIE 7.0; ...)Host: localhost:1997Content-Length: 15Connection: Keep-AliveCache-Control: no-cache

{"zip":"98052"}

RequestRequest

HTTP/1.1 200 OKServer: ASP.NET Development Server/8.0.0.0Date: Fri, 29 Dec 2006 21:06:17 GMTX-AspNet-Version: 2.0.50727Cache-Control: private, max-age=0Content-Type: application/json; charset=utf-8Content-Length: 16Connection: Close

["REDMOND","WA"]

ResponseResponse

JSON-encodedJSON-encodedinputinput

JSON-encodedJSON-encodedoutputoutput

Page 27: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

ScriptHandlerFactory

Wraps (replaces) default ASMX handler

Extends ASMX model with "special" URLsJavaScript proxy generation (*.asmx/js)Calls to Web methods (*.asmx/methodname)

<httpHandlers> <remove verb="*" path="*.asmx" /> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, ..." /></httpHandlers>

Page 28: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

ASMX Request Handling

ScriptHandler-Factory

ScriptHandler-Factory

RestClient-ProxyHandler

RestClient-ProxyHandler

RestHandlerRestHandler

WebService-HandlerFactory

WebService-HandlerFactory

*.asmx

"Normal" ASMX calls"Normal" ASMX calls

ASMX Extensions

*.asmx/js

*.asmx/methodname

HelperClasses

HelperClasses

Default ASMX handlerDefault ASMX handler

Page 29: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

JSON

JavaScript Object NotationLightweight data interchange formatEasier to read and write than XMLBased on subset of JavaScript

Default interchange format in ASP.NET AJAXMicrosoft.Web.Script.-Serialization.JavaScriptSerializerSys.Serialization.-JavaScriptSerializer

JSON home page: www.json.org

Page 30: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

JSON vs. XMLPoint p = new Point(100, 200);

{"IsEmpty":false,"X":100,"Y":200}{"IsEmpty":false,"X":100,"Y":200}

JSONJSON

<?xml version="1.0"?><Point xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <X>100</X> <Y>200</Y></Point>

<?xml version="1.0"?><Point xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <X>100</X> <Y>200</Y></Point>

XMLXML

Page 31: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

The ScriptMethod Attribute

Optional attribute for script-callable Web methodsOffers 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)

Page 32: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Using ScriptMethod[System.Web.Script.Services.ScriptService]public class ZipCodeService : System.Web.Services.WebService{ [System.Web.Services.WebMethod] [System.Web.Script.Services.ScriptMethod (ResponseFormat=ResponseFormat.Xml)] public XmlDocument GetCityAndState (string zip) { ... }}

Method returns XML document, so serializeMethod returns XML document, so serializeas XML rather than JSONas XML rather than JSON

Page 33: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Page Methods

Script-callable Web methods built into pagesSimpler than writing a full-blown Web service

Do not require service referencesDo not require dedicated ASMX files

Must be public static methodsMust be enabled via ScriptManager.-EnablePageMethods (disabled by default)Called through PageMethods proxy on client

Page 34: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Enabling Page Methods<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" Runat="server" />

var PageMethods = function() { PageMethods.initializeBase(this); this._timeout = 0; this._userContext = null; this._succeeded = null; this._failed = null;}PageMethods.prototype = { ...}

var PageMethods = function() { PageMethods.initializeBase(this); this._timeout = 0; this._userContext = null; this._succeeded = null; this._failed = null;}PageMethods.prototype = { ...}

Page 35: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Defining a Page Method

public partial class MyPage : System.Web.UI.Page{ [System.Web.Services.WebMethod] public static string[] GetCityAndState (string zip) { ... } ...}

Page 36: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

PageMethods.GetCityAndState("98052", onComplete); . . .function onComplete(result){ window.alert(result);}

Calling a Page Method

Page 37: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Page 38: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Built-In Web Services

AuthenticationServiceFront end to ASP.NET 2.0 membership serviceUse Sys.Services.AuthenticationService proxy

Global instance of Sys.Services._AuthenticationService

ProfileServiceFront-end to ASP.NET 2.0 profile serviceUse Sys.Services.Profile proxy

Global instance of Sys.Services._ProfileService

Accessed through ScriptHandlerFactory

Page 39: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Using 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());}

Page 40: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Loading Profile Properties

Sys.Services.ProfileService.load(['ScreenName'], onLoadCompleted, onLoadFailed); ...function onLoadCompleted(result, context, methodName){ window.alert(Sys.Services.ProfileService.properties.ScreenName);}

function onLoadFailed(err, context, methodName){ window.alert(err.get_message());}

Pass null to load all profile propertiesPass null to load all profile properties

Page 41: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity

Saving Profile Properties

Sys.Services.ProfileService.properties.ScreenName = 'Bob';Sys.Services.ProfileService.save(['ScreenName'], onSaveCompleted, onSaveFailed); ...function onSaveCompleted(result, context, methodName){ window.alert('Save succeeded');}

function onSaveFailed(err, context, methodName){ window.alert(err.get_message());}

Pass null to save all profile propertiesPass null to save all profile properties

Page 42: Satisfy Your Technical Curiosity The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect

Satisfy Your Technical Curiosity