Esposito Ajax Remote


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Esposito Ajax Remote

  1. 1. ASP.NET AJAX Extensions Calling Remote Services from ASP.NET AJAX
  2. 2. What You’re Going to See <ul><li>Defining remote services </li></ul><ul><li>Implementing remote services </li></ul><ul><li>REST vs. SOAP </li></ul><ul><li>Considerations </li></ul>
  3. 3. Need for services <ul><li>AJAX’s big win is invoking server code from the client page </li></ul><ul><ul><li>How do you expose server code to the client? </li></ul></ul><ul><li>Learn from the past </li></ul><ul><ul><li>Remote Scripting back in 1997 </li></ul></ul><ul><ul><li>Client engine nearly identical (was a Java applet) </li></ul></ul><ul><ul><li>Server infrastructure based on classic ASP </li></ul></ul><ul><ul><li>Public, fixed-name, contract-bound object exposed by the page and invoked by the client code </li></ul></ul><ul><ul><li>Contract implementation to determine subsequent server behavior </li></ul></ul><ul><ul><li>Data exchanged through strings </li></ul></ul><ul><ul><li>Client sets method to call and passes/receives values </li></ul></ul>
  4. 4. Define a contract <ul><li>Give your service an explicit contract </li></ul><ul><li>Not strictly required by ASP.NET AJAX v1.0 </li></ul><ul><li>Implement the contract in a service class </li></ul><ul><ul><li>SOA architecture </li></ul></ul>
  5. 5. Expose the server API <ul><li>Build a RESTful service </li></ul><ul><ul><li>Build a service that documents itself through headers and URLs, not SOAP </li></ul></ul><ul><li>Translated to the ASP.NET AJAX’s jargon </li></ul><ul><ul><li>Build an ASP.NET Web service with a special attribute </li></ul></ul><ul><ul><li>Or </li></ul></ul><ul><ul><li>Use the ASP.NET page as a special Web service </li></ul></ul>
  6. 6. Common misconception <ul><li>ASP.NET AJAX Lets You Call Web Services </li></ul><ul><ul><li>Untrue and incorrect </li></ul></ul><ul><ul><li>but it may happen … </li></ul></ul>
  7. 7. REST vs. SOAP <ul><li>REpresentational State Transfer </li></ul><ul><ul><li>It’s all about the URL (and headers) </li></ul></ul><ul><ul><li>Resource = URL </li></ul></ul><ul><li>Simple Object Access Protocol </li></ul><ul><ul><li>One URL fits all </li></ul></ul><ul><ul><li>Use a XML schema to describe the call </li></ul></ul><ul><ul><li>Use WSDL to describe the API </li></ul></ul><ul><li>SOAP-based services require the client know about SOAP </li></ul>
  8. 8. ASP.NET AJAX Perspective <ul><li>Expose the server API as REST services </li></ul><ul><li>You write ASP.NET Web services with an extra attribute </li></ul><ul><ul><li>Expose the service the REST way </li></ul></ul><ul><ul><li>JSON feeds consumed </li></ul></ul><ul><ul><li>No SOAP at all (simpler, faster) </li></ul></ul><ul><ul><li>Same Origin Policy </li></ul></ul><ul><li>Call made to the local server </li></ul>
  9. 9. JavaScript Proxy <ul><li>Mirrors all WebMethods of the Web services </li></ul><ul><li>Extra members </li></ul><ul><ul><li>Properties: path , timeout , defaultUserContext , default Succeeded Callback , defaultFailedCallback </li></ul></ul><ul><ul><li>Static (private) instance of the class </li></ul></ul><ul><ul><li>Static members for the client to call (no proxy instantiation) </li></ul></ul>IntroAjax.WebServices.TimeService . prototype = { GetTime : function (succeededCallback, failedCallback, userContext) { return this ._invoke( IntroAjax.WebServices.TimeService .get_path(), ' GetTime ', false , {}, succeededCallback, failedCallback, userContext); }, GetTimeAsFormat : function ( timeFormat , succeededCallback, failedCallback, userContext) { return this ._invoke( IntroAjax.WebServices.TimeService .get_path(), ' GetTimeAsFormat ', false , {format: timeFormat }, succeededCallback, failedCallback, userContext); } }
  10. 10. Calling Web Methods <ul><li>Use static methods on the proxy and add callbacks </li></ul>< script language =&quot;javascript&quot; type =&quot;text/javascript&quot;> function getTime() { var timeFormat = &quot; ddd, dd MMMM yyyy [hh:mm:ss] &quot;; IntroAjax.WebServices.TimeService .GetTimeFormat(timeFormat, onMethodComplete); } function onMethodComplete(results) { $get (&quot; Label1 &quot;).innerHTML = results; } </ script > < html xmlns =&quot;;> < head runat =&quot;server&quot;>< title>The Time Web service</ title ></ head > < body > < form id =&quot;form1&quot; runat =&quot;server&quot;> < asp:ScriptManager ID =&quot;ScriptManager1&quot; runat =&quot;server&quot;> < Services > < asp:ServiceReference Path =&quot;~/WebServices/TimeService.asmx&quot; /> </ Services > </ asp:ScriptManager > < h2 > What time is it on the server? </ h2 > < input type =&quot;button&quot; value =&quot;Get Time&quot; onclick =&quot;getTime()&quot; /> < asp:Label runat =&quot;server&quot; ID =&quot;Label1&quot; /> </ form > </ body > </ html >
  11. 11. DEMO <ul><li>Invoking a Web service from an AJAX page </li></ul>
  12. 12. JSON Serialization <ul><li>Page/server communication is based on strings </li></ul><ul><ul><li>Data is automatically serialized using JSON </li></ul></ul><ul><li>JavaScript Object Notation (simpler than XML) </li></ul><ul><ul><li>Text format to represent an object—actually, an (associative) array </li></ul></ul><ul><ul><li>Needs a “proxy” to represent a server type </li></ul></ul><ul><li>Server and client infrastructure to proxy data </li></ul><ul><li>Sample call: </li></ul><ul><ul><li>IntroAjax.TimeService.GetTimeFormat(&quot;ddd, dd MMMM yyyy [hh:mm:ss]&quot;, ...) </li></ul></ul>{&quot;format&quot;:&quot;ddd, dd MMMM yyyy [hh:mm:ss]&quot;} &quot;Thu, 25 January 2007 [07:10:31]&quot; Request body Response Content
  13. 13. Using Complex Types <ul><li>JSON can be used to serialize complex types </li></ul><ul><ul><li>.NET types JSON-serialized using server class JavaScriptSerializer </li></ul></ul><ul><ul><li>String processed on the client to an instance of a proxy class that mirrors the original type </li></ul></ul><ul><ul><li>And vice-versa </li></ul></ul>{&quot;id&quot;:&quot;ALFKI&quot;} { &quot;__type&quot;:&quot;IntroAjax.Customer&quot;, &quot;ID&quot;:&quot;ALFKI&quot;, &quot;CompanyName&quot;:&quot;Alfreds Futterkiste&quot;, &quot;ContactName&quot;:&quot;Maria Anders&quot;, &quot;ContactTitle&quot;:&quot;Sales Representative&quot;, &quot;Street&quot;:&quot;Obere Str. 57&quot;, &quot;PostalCode&quot;:&quot;12209&quot;, &quot;City&quot;:&quot;Berlin&quot;, &quot;Country&quot;:&quot;Germany&quot;, &quot;Phone&quot;:&quot;030-0074321“ } Response content Request body IntroAjax.WebServices.MyDataService .LookupCustomer( &quot; ALFKI &quot; , onSearchComplete);
  14. 14. Client Callbacks <ul><li>Methods on the proxy class have an extended prototype </li></ul><ul><ul><li>Params array, success and error callbacks, user context info </li></ul></ul><ul><li>Callbacks prototype </li></ul><ul><ul><li>function methodCompleted(results, context, methodName) </li></ul></ul><ul><ul><li>User context is any information developers want to pass from the client and reuse in the callback </li></ul></ul>IntroAjax.WebServices.TimeService . prototype = { GetTimeAsFormat : function ( timeFormat , succeededCallback, failedCallback, userContext) { return this ._invoke( IntroAjax.WebServices.TimeService .get_path(), // service path ' GetTimeAsFormat ', // method name false , // use GET verb {format: timeFormat }, // parameters succeededCallback, // completed callback failedCallback, // error callback userContext); // context extra information } } Method prototype
  15. 15. Exceptions and Timeouts <ul><li>Web service requests </li></ul><ul><ul><li>Set Content-Type to “ application/json; charset=utf-8 ” </li></ul></ul><ul><ul><li>In case of error, the response contains a jsonerror header </li></ul></ul><ul><li>Process results of the call using onSucceeded callback </li></ul><ul><li>Exceptions on the server caught and exposed to client code via onFailed callback </li></ul><ul><ul><li>Default failure callback defined: pops up a message box </li></ul></ul><ul><li>Timeout supported </li></ul><ul><ul><li>Set it through client timeout property </li></ul></ul>// Method can't take longer than 3 secs function runOutOfTime() { IntroAjax.WebServices.MyDataService .set_timeout(3000); IntroAjax.WebServices.MyDataService .VeryLengthyTask(methodCompleted, methodError, &quot; runOutOfTime() &quot;); }
  16. 16. Page Methods <ul><li>Page methods are similar to Web service method except that they are defined in code-behind class </li></ul><ul><li>Add a method to the page’s class and decorate it with the WebMethod attribute </li></ul><ul><ul><li>Also works if method is defined inline in a text/C# block </li></ul></ul><ul><li>The page acts as a Web service </li></ul><ul><li>Set EnablePageMethods to true in the script manager </li></ul><ul><li>Public methods of the class wrapped up in a proxy </li></ul><ul><ul><li>Injected inline in the client page </li></ul></ul><ul><ul><li>No registration required </li></ul></ul>
  17. 17. Defining a Page Method <ul><li>Public and static method </li></ul><ul><ul><li>Add the WebMethod attribute </li></ul></ul><ul><ul><li>No access to controls in the page </li></ul></ul><ul><ul><li>Just a way to expose pieces of “business” logic </li></ul></ul><ul><ul><li>Parameters and return values JSON-serialized </li></ul></ul><ul><ul><li>Necessary type definition injected in the client page </li></ul></ul>public partial class Samples_Ch07_CallPageMethod : System.Web.UI.Page { : [WebMethod] public static DateTime GetTime() { return DateTime.Now; } } Sample page method Can be any .NET type, including custom types
  18. 18. Invoking a Page Method <ul><li>Script manager commands the creation of a proxy class </li></ul><ul><ul><li>Named PageMethods defined inline </li></ul></ul><ul><ul><li>As many methods as there are static WebMethod s in the class </li></ul></ul><ul><ul><li>Same prototype as for Web service methods </li></ul></ul>< script type =&quot;text/javascript&quot;> function getTime() { PageMethods .GetTime(onMethodComplete); } function onMethodComplete(results, context, methodName) { // Format the date-time object to a more readable string var displayString = results.format(&quot; ddd, dd MMMM yyyy &quot;); $get (&quot; Label1 &quot;).innerHTML = displayString; } </ script > < asp:ScriptManager runat=&quot;server&quot; ID =&quot;ScriptManager1&quot; EnablePageMethods =&quot;true&quot; /> < h2 >What time is it on the server?</ h2 > < input type =&quot;button&quot; value =&quot;Get Time&quot; onclick =&quot;getTime()&quot; />
  19. 19. DEMO <ul><li>Invoking a page method </li></ul><ul><li>Accessing session state from the client </li></ul>
  20. 20. Web services vs. Page methods <ul><li>Web service methods </li></ul><ul><ul><li>Callable from any pages and reusable </li></ul></ul><ul><ul><li>Publicly exposed over the Web and publicly callable </li></ul></ul><ul><li>Page methods </li></ul><ul><ul><li>Have client callable server code without developing a Web service </li></ul></ul><ul><ul><li>No page context associated with the call </li></ul></ul><ul><li>Can’t control who’s calling </li></ul><ul><ul><li>Do not use for critical BLL </li></ul></ul><ul><ul><li>Only for UI-level logic </li></ul></ul>
  21. 21. Bridging External Services <ul><li>Web services you can call must be local to the application </li></ul><ul><ul><li>What if you want to call an external service? </li></ul></ul><ul><ul><li>Different application OR different machine/network </li></ul></ul><ul><li>Client AJAX calls into an external service (i.e., Amazon) </li></ul><ul><ul><li>Can’t make assumptions on the Web server </li></ul></ul><ul><li>Client AJAX calls into an ASP.NET service </li></ul><ul><ul><li>Some browsers prohibit cross-site calls from the client </li></ul></ul><ul><li>The bottom line </li></ul><ul><ul><li>Client calls its own server </li></ul></ul><ul><ul><li>Server places a server-to-server call to the Web service </li></ul></ul>
  22. 22. Server-to-Server <ul><li>Manual implementation </li></ul><ul><ul><li>Invoke a server method that, in turn, call the Web service </li></ul></ul><ul><ul><li>Updatable panel or page method </li></ul></ul><ul><li>ASP.NET AJAX assisted implementation </li></ul><ul><ul><li>The bridge technology </li></ul></ul><ul><ul><li>Enables developers to create programmatic gateways to Web services on the Internet </li></ul></ul><ul><ul><li>Chief enabling technology for building mash-ups </li></ul></ul>
  23. 23. DEMO <ul><li>Stock-watching demo (using Yahoo) </li></ul><ul><ul><li>UpdatePanel with a grid </li></ul></ul><ul><ul><li>Timer control to refresh periodically </li></ul></ul><ul><ul><li>A homemade service class to get stock quotes </li></ul></ul><ul><ul><li>UI code to bind the grid </li></ul></ul>
  24. 24. Summary <ul><li>In ASP.NET AJAX, Web services are a way to execute server-side code in response to a client action </li></ul><ul><li>Local Web services or page methods </li></ul><ul><li>JSON serialization </li></ul><ul><li>JavaScript callbacks to merge results with the page </li></ul><ul><li>Server-to-server calls to external services </li></ul>
  25. 25. References <ul><li>For more information, refer to </li></ul><ul><ul><li>Introducing Microsoft ASP.NET 2.0 AJAX Extensions </li></ul></ul><ul><ul><ul><li>Microsoft Press, June 2007 </li></ul></ul></ul>