2 Asp Dot Net Ajax Extensions
Upcoming SlideShare
Loading in...5

2 Asp Dot Net Ajax Extensions







Total Views
Views on SlideShare
Embed Views



1 Embed 6

http://www.slideshare.net 6



Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment
  • If no event name is specified in a trigger, the trigger automatically references the control's default event (e.g., Button.Click)
  • One of the "Helper Classes" is WebServiceClientProxyGenerator , which RestClientProxyHandler calls upon to generate JavaScript proxies.
  • ASP.NET AJAX’s JSON serializers provide special handling for one common .NET data type that isn’t handled natively by JSON: System.DateTime . Here’s how System.Web.Script.Serialization.JavaScriptSerializer serializes a date and time representing midnight on January 1, 2000 into JSON: "@946702800000@" The number between @ signs is the number of milliseconds elapsed since January 1, 1970. This is the format used by the ASP.NET AJAX Release Candidate (RC); it will probably be tweaked before RTM.
  • The first null passed to the login function is used to pass custom data. The second null is a redirect URL. If a redirect URL is specified, the user is redirected to that location following a successful login. The third parameter to the login function specifies whether a logged-in user should be issued a temporary auth cookie (false) or a persistent auth cookie (true). In order for all this to work, the application's authentication mode must be set to "Forms."

2 Asp Dot Net Ajax Extensions 2 Asp Dot Net Ajax Extensions Presentation Transcript

  • The ASP.NET AJAX Extensions Jeff Prosise Cofounder, Wintellect www.wintellect.com
  • Architecture ASP.NET 2.0 Page Framework & Server Controls Application Services ASP.NET AJAX Extensions Server Controls ASPX ASMX Application Services Bridge Asynchronous Communications
  • Server Controls UpdatePanel Update- Progress Timer DragOverlay- Extender ScriptManager ScriptManager- Proxy ProfileService Script Management Partial-Page Rendering Futures CTP
  • ScriptManager
    • 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 via client-side proxies
      • Manages callback timeouts, provides error handling options and infrastructure, and more
    • Every page requires one ScriptManager!
  • ScriptManager Schema <asp:ScriptManager ID=&quot;ScriptManager1&quot; Runat=&quot;server&quot; EnablePartialRendering=&quot;true|false&quot; EnablePageMethods=&quot;true|false&quot; AsyncPostBackTimeout=&quot; seconds &quot; AsyncPostBackErrorMessage=&quot; message &quot; AllowCustomErrorsRedirect=&quot;true|false&quot; OnAsyncPostBackError=&quot; handler &quot; EnableScriptGlobalization=&quot;true|false&quot; EnableScriptLocalization=&quot;true|false&quot; ScriptMode=&quot;Auto|Inherit|Debug|Release&quot; ScriptPath=&quot; path &quot;> <Scripts> <!-- Declare script references here --> </Scripts> <Services> <!-- Declare Web service references here --> </Services> </asp:ScriptManager>
  • Script References <asp:ScriptManager ID=&quot;ScriptManager1&quot; Runat=&quot;server&quot;> <Scripts> <asp:ScriptReference Name=&quot;PreviewScript.js&quot; Assembly=&quot;Microsoft.Web.Preview&quot; /> <asp:ScriptReference Name=&quot;PreviewDragDrop.js&quot; Assembly=&quot;Microsoft.Web.Preview&quot; /> <asp:ScriptReference Path=&quot;~/Scripts/UIMap.js&quot; /> </Scripts> </asp:ScriptManager> &quot;Path&quot; references load script files &quot;Name&quot; references load script resources
  • Service References <asp:ScriptManager ID=&quot;ScriptManager1&quot; Runat=&quot;server&quot;> <Services> <asp:ServiceReference Path=&quot;ZipCodeService.asmx&quot; /> </Services> </asp:ScriptManager>
  • ScriptManagerProxy
    • &quot;Proxy&quot; for ScriptManager controls declared in master pages
    • Lets content pages declare script and service references
    <asp:ScriptManagerProxy ID=&quot;ScriptManagerProxy1&quot; Runat=&quot;server&quot;> <Scripts> <!-- Declare additional script references here --> </Scripts> <Services> <!-- Declare additional service references here --> </Services> </asp:ScriptManagerProxy>
  • UpdatePanel
    • Partial-page rendering in a box
      • Clean round trips to server and updates
      • Requires no knowledge of JavaScript or AJAX
    • Leverages PageRequestManager class
      • EnablePartialRendering=&quot;true&quot;
    • Supports explicitly defined triggers
      • Postbacks from controls in UpdatePanel are converted into async callbacks
      • Triggers expand (or shrink) postback->callback scope
  • UpdatePanel Schema <asp:ScriptManager ID=&quot;ScriptManager1&quot; Runat=&quot;server&quot; EnablePartialRendering=&quot;true&quot; /> . . . <asp:UpdatePanel ID=&quot;UpdatePanel1&quot; Runat=&quot;server&quot; UpdateMode=&quot;Always|Conditional&quot; ChildrenAsTriggers=&quot;true|false&quot;> <Triggers> <!-- Define triggers (if any) here --> </Triggers> <ContentTemplate> <!-- Define content here --> </ContentTemplate> </asp:UpdatePanel>
  • Triggers
    • AsyncPostBackTrigger
      • Converts postbacks into async callbacks
      • Typically used to trigger updates when controls outside an UpdatePanel post back
      • If ChildrenAsTriggers=&quot;false&quot;, can be used to specify which controls inside UpdatePanel should call back rather than post back
    • PostBackTrigger
      • Lets controls inside UpdatePanel post back
      • Typically used to allow certain controls to post back when ChildrenAsTriggers=&quot;true&quot;
  • Triggers Example <asp:UpdatePanel ID=&quot;UpdatePanel1&quot; Runat=&quot;server&quot; UpdateMode=&quot;Conditional&quot;> <Triggers> <asp:AsyncPostBackTrigger ControlID=&quot;Button1&quot; /> <asp:AsyncPostBackTrigger ControlID=&quot;TreeView1&quot; EventName=&quot;TreeNodeExpanded&quot; /> <asp:AsyncPostBackTrigger ControlID=&quot;TreeView1&quot; EventName=&quot;TreeNodeCollapsed&quot; /> <asp:PostBackTrigger ControlID=&quot;Button2&quot; /> </Triggers> <ContentTemplate> ... </ContentTemplate> </asp:UpdatePanel>
  • Periodic Updates
    • Combine UpdatePanel with Timer control to perform periodic updates
    • Use Timer control Tick events as triggers
    <asp:Timer ID=&quot;Timer1&quot; Runat=&quot;server&quot; Interval=&quot;5000&quot; OnTick=&quot;OnTimerTick&quot; /> ... <asp:UpdatePanel UpdateMode=&quot;Conditional&quot; ...> <Triggers> <asp:AsyncPostBackTrigger ControlID=&quot;Timer1&quot; /> </Triggers> ... </asp:UpdatePanel>
  • Demo
  • UpdateProgress
    • 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 &quot;DisplayAfter&quot; interval elapses
  • UpdateProgress Schema <asp:UpdateProgress ID=&quot;UpdateProgress1&quot; Runat=&quot;server&quot; DisplayAfter=&quot; milliseconds &quot; DynamicLayout=&quot;true|false&quot; AssociatedUpdatePanelID=&quot; UpdatePanelID &quot;> <ProgressTemplate> <!-- Declare UpdateProgress UI here --> </ProgressTemplate> </asp:UpdateProgress>
  • UpdateProgress Example <asp:UpdateProgress DisplayAfter=&quot;500&quot; ...> <ProgressTemplate> <asp:Image ID=&quot;ProgressImage&quot; Runat=&quot;server&quot; ImageUrl=&quot;~/Images/SpinningClock.gif&quot; /> </ProgressTemplate> </asp:UpdateProgress> Animated GIF Display after ½ second
  • Canceling an Update <asp:UpdateProgress DisplayAfter=&quot;500&quot; ...> <ProgressTemplate> <b>Working...</b> <asp:Button ID=&quot;CancelButton&quot; Runat=&quot;server&quot; Text=&quot;Cancel&quot; OnClientClick=&quot;cancelUpdate(); return false&quot; /> </ProgressTemplate> </asp:UpdateProgress> <script type=&quot;text/javascript&quot;> function cancelUpdate() { var obj = Sys.WebForms.PageRequestManager.getInstance(); if (obj.get_isInAsyncPostBack()) obj.abortPostBack(); } </script>
  • Demo
  • 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 script
    • JavaScript proxy on client enables JavaScript clients to call Web methods
  • 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) { ... } }
  • Declaring a Service Reference <asp:ScriptManager ID=&quot;ScriptManager1&quot; Runat=&quot;server&quot;> <Services> <asp:ServiceReference Path=&quot;ZipCodeService.asmx&quot; /> </Services> </asp:ScriptManager> <script src=&quot;ZipCodeService.asmx/js&quot; type=&quot;text/javascript&quot;> </script>
  • Consuming a Web Service ZipCodeService.GetCityAndState(&quot;98052&quot;, onCompleted); . . . function onCompleted (result) { window.alert(result); }
  • Handling Errors ZipCodeService.GetCityAndState(&quot;98052&quot;, onCompleted, onFailed); . . . function onCompleted (result, context, methodName) { window.alert(result); } function onFailed (err, context, methodName) { window.alert(err.get_message()); }
  • Demo
  • ASMX Wire Format POST /AtlasRC/ZipCodeService.asmx/GetCityAndState HTTP/1.1 Accept: */* Accept-Language: en-us Referer: http://localhost:1997/AtlasRC/ZipCodePage.aspx UA-CPU: x86 Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; ...) Host: localhost:1997 Content-Length: 15 Connection: Keep-Alive Cache-Control: no-cache {&quot;zip&quot;:&quot;98052&quot;} Request HTTP/1.1 200 OK Server: ASP.NET Development Server/ Date: Fri, 29 Dec 2006 21:06:17 GMT X-AspNet-Version: 2.0.50727 Cache-Control: private, max-age=0 Content-Type: application/json; charset=utf-8 Content-Length: 16 Connection: Close [&quot;REDMOND&quot;,&quot;WA&quot;] Response JSON-encoded input JSON-encoded output
  • ScriptHandlerFactory
    • Wraps default ASP.NET ASMX handler
    • Extends ASMX model with &quot;special&quot; URLs
      • JavaScript proxy generation (*.asmx/js)
      • Calls to Web methods (*.asmx/ methodname )
    <httpHandlers> <remove verb=&quot;*&quot; path=&quot;*.asmx&quot; /> <add verb=&quot;*&quot; path=&quot;*.asmx&quot; validate=&quot;false&quot; type=&quot;System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, ...&quot; /> </httpHandlers>
  • ASMX Request Handling ScriptHandler- Factory RestClient- ProxyHandler RestHandler WebService- HandlerFactory *.asmx &quot;Normal&quot; ASMX calls ASMX Extensions *.asmx/js *.asmx/ methodname Helper Classes Default ASMX handler
  • JSON
    • 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.JavaScriptSerializer (server)
      • Sys.Serialization.JavaScriptSerializer (client)
    • JSON home page: www.json.org
  • JSON vs. XML Point p = new Point(100, 200); {&quot;IsEmpty&quot;:false,&quot;X&quot;:100,&quot;Y&quot;:200} JSON <?xml version=&quot;1.0&quot;?> <Point xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot;> <X>100</X> <Y>200</Y> </Point> XML
  • The 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)
  • 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 serialize as XML rather than JSON
  • Page Methods
    • Script-callable Web methods in pages
    • Simpler than full-blown Web services
      • Do not require service references
      • Do not require dedicated ASMX files
    • Must be public static methods
    • Must be enabled via ScriptManager.-EnablePageMethods (disabled by default)
    • Called through PageMethods proxy on client
  • Enabling Page Methods <asp:ScriptManager ID=&quot;ScriptManager1&quot; EnablePageMethods=&quot;true&quot; Runat=&quot;server&quot; /> var PageMethods = function() { PageMethods.initializeBase(this); this._timeout = 0; this._userContext = null; this._succeeded = null; this._failed = null; } PageMethods.prototype = { ... }
  • Defining a Page Method public partial class MyPage : System.Web.UI.Page { [System.Web.Services.WebMethod] public static string[] GetCityAndState (string zip) { ... } ... }
  • Calling a Page Method PageMethods.GetCityAndState(&quot;98052&quot;, onComplete); . . . function onComplete(result) { window.alert(result); }
  • Demo
  • Built-In Web Services
    • AuthenticationService
      • Front end to membership service
      • Sys.Services.AuthenticationService proxy
        • Global instance of Sys.Services._AuthenticationService
    • ProfileService
      • Front-end to profile service
      • Sys.Services.Profile proxy
        • Global instance of Sys.Services._ProfileService
    • Accessed through ScriptHandlerFactory
  • 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()); }
  • 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 properties
  • 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 properties