Views
2 years ago

DNDJ 3-6 June.indd - sys-con.com's archive of magazines - SYS ...

DNDJ 3-6 June.indd - sys-con.com's archive of magazines - SYS ...

ASP.NET Web

ASP.NET Web ServicesAsynchronous Web ServicesDon’t just call Web services, make them call you back!BY AARON REEDsince their conception,Web services haveevolved into a corecomponent ofsoftware architectures worldwide.The ability to easily distributeprocessing, allow access via theInternet, and componentizearchitectures makes Webservices a compelling choice forinteroperability among systems.Another convincing argumentfor the implementation of Webservices is the fact that withthe current development toolsavailable, they are easy to createand they integrate virtuallyseamlessly into most systems.However, the fact that Webservices are easy to create,coupled with the reality that .NETessentially walks you through theprocess of including Web servicesin a Windows or Web application is,in a way, both a positive as well as anegative. The positive is, obviously,that many developers gain accessto the power of Web services withlittle training or research required.The negative, however, is thatmany of those developers fail tolook deeper into the capabilities ofWeb services and miss out on someof the richer technology that liesbeneath the surface.One such technology that isoften overlooked is the ability tocall Web services asynchronously.The simplest way to call a Webservice method is to create aninstance of your Web service classand then merely call the method.This may work great in many cases,but it is inherently inefficient. Thattype of a Web service call is knownas a synchronous call, whichmeans that when you call the Webservice method, the executionof the calling program is paused(and appears frozen) until the Webservice returns with results or timesout. At that point, the executionof the calling program picks upwhere it left off. Asynchronouscalls to Web service methods allowyou to call the Web service andthen continue processing and/orgathering information via a UIwhile the Web service does itsthing.Because of the real-time natureof Windows applications theyare a great place to implementasynchronous calls. If you’ve evertried using Web services with aWindows application, you mayhave abandoned that idea basedon the slightly less real-time aspectof Web services (there is a slightdelay with each Web service callyou make). Asynchronous callscan help alleviate that problemand make Web service callsperform in a much more real-timeenvironment.For example, let’s say you havea search screen in an applicationwhich pulls data via a searchmethod from a Web service. Witha synchronous call, you’d probablywant to have the users enter theirsearch criteria and then hit abutton to start the search on theWeb service. You’d do this becausewhile the search is running on theWeb service, the client applicationis essentially frozen, waiting for theresults.With an asynchronous call, youcould trap the key press in each ofthe search fields and immediatelybegin a search on the Web servicewith the current data in thosefields. The user can continue tomodify the search criteria while theWeb service is churning becausethe application is not frozen. Eachtime the user presses a new key, theprevious call to the Web service, ifit’s still running, is cancelled and anew search is called with the newdata from the search screen. Withthis technique, the user will see thesearch results as he or she is typing– providing a much more realtimefeel to your application. Inaddition, for you usability activists,an extra mouse click has beenremoved from the search screenbecause the user no longer has toclick a button to begin a search.So just how does all thishappen? It’s surprisingly easyto implement. Let’s say we havecreated a Web service that searchesa database for users based on somesearch criteria (for this exercise,we’ll just use first and last name).My synchronous call would looksomething like Listing 1.While synchronous callscan seem fairly straightforward,asynchronous calls are a bit morecomplex. There are a number oftechniques you can use to makeasynchronous calls to Web servicemethods and each has a certainbenefit in different situations. Forthe situation described here, you’dprobably want to use the callbacktechnique. The callback techniqueof asynchronous Web service callsallows your application to haveidle time while the Web service isworking. This allows the user tointeract with the GUI and, in thiscase, to refine search criteria.The callback techniqueprovides a way for your clientapplication to call the Web servicemethod and move on to whateverelse it needs to do (or in our case,move into an idle state and let theuser keep typing). When the Webservice finishes, a callback methodin your client application is calledwhere you then can get the resultsfrom the Web service call and dowhatever processing you need (likefill your list of users that matchedthe search criterion).So the first thing to do is definea callback method in the codefor your client application (in ourcase, a Windows application).The method has to have the38June 2005 • dotnetdevelopersjournal.com

same signature as the one in Listing 2.Notice the code inside the callback. TheIAsyncResult parameter in the methodsignature contains an AsyncStateproperty which is actually an instanceof the Web service that was called. Thatinstance is the one that holds the keyto retrieve the results from your Webservice method. Cast it to an object ofyour Web service type and assign it to avariable of that type. Then notice that toget the results of our GetUsers method,you call the method EndGetUsers(remember, the name of our Web servicemethod was GetUsers) while passing itagain the IAsyncResult object from themethod signature.You’ve now implemented the codethat will retrieve the results to your Webmethod call once it has been made. Nowall that’s left to do is to actually make thecall. Notice that when you retrieved theresults of the call to GetUsers, you usedthe EndGetUsers method. Similarly, we’lluse a different call to invoke the GetUsersmethod. We’ll use the BeginGetUsers callas outlined in Listing 3.There are a number of things tonotice in Listing 3. First, in the secondline of code, we are creating an objectof type AsyncCallback. We pass thename of our callback method to theobject’s constructor. This object willtie our invoked Web service methodto our callback method in our clientapplication (defined in Listing 2).Next, we make the actual callto BeginGetUsers in the third line.Here it’s important to note that whilethe GetUsers method required twoparameters (a first name string and alast name string), the BeginGetUsersmethod requires those as well, butinserts two other parameters in additionto those. The first of the two additionalparameters is the object created in theprevious line, the callback method object(type AsyncCallback). This lets the Webservice know which method to call whenit is finished with its work. The secondadditional parameter is the instance ofthe Web service. This is the object typeto be used in the IAsyncResult object’sAsyncState property (see Listing 2) whenthe Web service results are ready toretrieve. We want that property to holdan object of the type of our Web service,so we pass in the instance of our Webservice (MyUsers) here.Your Web service is now ready to becalled asynchronously. That wasn’t sobad, was it? One final thing to note isthat you may want to capture the resultfrom the BeginMethodName call. InListing 3 I captured the result to myBeginGetUsers call in an object calledMyResult of type IAsyncResult. It’simportant to note that this result objectwill not contain the results from yourWeb service’s Web method. Instead thisobject will contain information aboutthe specific Web service call that iscurrently being processed. Specifically,if you need to abort that call, this is theobject you would use to do that. SeeListing 4 to look at the code that wouldabort that call.As discussed earlier, if you wantedto allow the users to enter searchcriteria and with every key press startan asynchronous Web service callto get more real-time search results,you can do that with the callbacktechnique. One thing you’d need toremember to do, however, is witheach key press, abort the previouscall before you call the BeginGetUsersmethod again. Otherwise, you’d haveas many active searches as you havekey presses and the Web server wouldquickly become overloaded. In Listing4, we see that to abort the Web methodcall, you simply cast the IAsyncResultobject (this object is the return valuefrom our BeginGetUsers method) as aWebClientAsyncResult object (you’llneed a using statement for System.Web.Services.Protocols for this) and callAbort( ) on it. Your Web service call willthen have been cancelled and you canthen call it again with the new data inthe search criteria fields.You’ve now seen exactly how to calla Web service method asynchronouslywith the callback technique. One otherpopular way of calling asynchronousWeb service methods is the WaitHandletechnique. To do this, you must firstadd a using statement for the System.Threading namespace. See the code forthe WaitHandle approach in Listing 5.As you can see here, the callbacktechnique and the WaitHandletechnique are fairly similar. Onething to notice is that when we callBeginGetUsers with the WaitHandletechnique, we simply pass in null tothe additional parameters (the lasttwo parameters). Also notice thatwe use the MyResult object of typeIAsyncResult to capture the return valuefrom BeginGetUsers and that we thenuse that same object to call WaitOne() to wait for our Web service call tobe finished. Finally, we use that sameobject to pass into the EndGetUsersmethod to fetch our results.The WaitOne call will blockexecution of the current thread (theclient app) until the WaitHandle receivesa signal (meaning that our Web servicecall has completed). At that pointwe can pull the results from our Webservice object and continue. You are stillable to abort your asynchronous call thesame way as before at any time beforeyou call WaitOne( ) (see Listing 4).There are a number of othertechniques for calling Web servicesasynchronously. You can loop inyour client application and call theIAsyncResult object’s IsCompletedproperty. You can also simply call theEndMethodName call whenever yourapplication is ready for the results.The trick is identifying the differencesbetween the techniques and selectingthe one that best fits your application.For example, with the callbacktechnique, your client application isnotified by the Web service when thecall is completed. This is nice becauseyou don’t ever have to “freeze” yourapplication while waiting for results.However, in order for your applicationto ever accept that signal from the Webservice, your application requires idletime. Essentially, this means that ifyour client application calls the Web“Asynchronous calls to Web service methods allow you to callthe Web service and then continue processing and/or gatheringinformation via a UI while the Web service does its thing”dotnetdevelopersjournal.com • June 200539

DNDJ 6-3 web.indd - sys-con.com's archive of magazines - SYS ...
DNDJ 6-3WEB.indd - sys-con.com's archive of magazines - SYS ...
DNDJ 3-11 Nov.indd - sys-con.com's archive of magazines - SYS ...
DNDJ 4-9.indd - sys-con.com's archive of magazines - SYS-CON ...
JDJ 10-10.indd - sys-con.com's archive of magazines - SYS-CON ...
DNDJ 1-12 Dec.(NEWCONF - sys-con.com's archive of magazines ...
DNDJ 6-4 web.indd - sys-con.com's archive of magazines - SYS ...
DNDJ 3-7 July.indd - sys-con.com's archive of magazines - SYS ...
Figure 1 - sys-con.com's archive of magazines - SYS-CON Media
JDJ 10-3.indd - sys-con.com's archive of magazines - SYS-CON Media
DNDJ 2-2.qxd - sys-con.com's archive of magazines - SYS-CON ...
jdjedge conference & expo - sys-con.com's archive of magazines ...
Download - sys-con.com's archive of magazines - SYS-CON Media
Download - sys-con.com's archive of magazines - SYS-CON Media
JDJ 10-6.indd - sys-con.com's archive of magazines - SYS-CON Media
issue 6 - sys-con.com's archive of magazines - SYS-CON Media
SCOTT McNEALY - sys-con.com's archive of magazines - SYS-CON ...
Conclusion - sys-con.com's archive of magazines
DNDJ February 3-2.indd - sys-con.com's archive of magazines ...
WEB SERVICES EDGE 2002 - sys-con.com's archive of magazines ...
Web Designer'sJournal Developer's - sys-con.com's archive of ...
issue 11 - sys-con.com's archive of magazines - SYS-CON Media
WSJ 4-2 February... - sys-con.com's archive of magazines - SYS ...
DNDJ 4-8.indd - sys-con.com's archive of magazines - SYS-CON ...
JDJ 11-1 Jan.indd - sys-con.com's archive of magazines - SYS-CON ...
LinuxWorld.com - sys-con.com's archive of magazines - SYS-CON ...
JAVA Vol 3 Issue4 - sys-con.com's archive of magazines
JDJ 9-11.indd - sys-con.com's archive of magazines - SYS-CON Media
Java - sys-con.com's archive of magazines
Wireless - sys-con.com's archive of magazines - SYS-CON Media