Creating a Client for the Simple XML Web Service


Now it is time to create a client for the QuotableQuotes XML Web service. Start out by creating a new Smart Device Application. Design the UI to match the UI in Figure 9.2. The code to call the XML Web service will be placed in the button-clicked handler on the button labeled Get Quote . First add a reference to the XML Web service into the Smart Device Application project.

Figure 9.2. The user interface for the QuotableQuotes client application.

graphics/09fig02.jpg

Adding a Web Reference to a Client Application

Now, a Web reference to service needs to be added to the client project. To do this, go to the Solution Explorer, right-click the Reference node, and select the Add Web References . . . menu item. This will bring up the Add Web Reference dialog (see Figure 9.3).

Figure 9.3. The Add Web Reference dialog.

graphics/09fig03.jpg

The Add Web Reference dialog helps to locate online Web Services and use them in an application. The dialog displays four links. One link allows you to view all of the XML Web services on the local machine. The other three links browse three UDDI servers/directories. The "Browse UDDI Servers on the local machine" link allows you to browse the UDDI servers on the local network. The other two links are labeled UDDI Directory and the Test Microsoft UDDI Directory provide access to services that have registered with Microsoft. The "UDDI Directory" link browses the UDDI business registry to find companies and production Web services. The "Test Microsoft UDDI Directory" link locates test XML Web services that are meant to be used during development.

In this sample the QuotableQuotes XML Web service will not be registered with a UDDI. Instead of registering the QuotableQuotes XML Web service with a UDDI, the address to the QuoteService.aspx page will be entered into the Add Web Reference dialog. Enter the following URL, http://localhost/QuotableQuotesWebService/QuoteService.asmx , into the Address text box and then press Enter or click the Go button.

The dialog will then download the WSDL file for the QuoteService Web service. Once the download is complete, click the Add Reference button.

Viewing the Proxy Class

When the Add Reference button is clicked, Microsoft Visual Studio.NET generates a proxy class that will manage the interaction between the application and the QuotableQuotes Web service. In some cases the proxy class file may need to be viewed or modified, but by default the Solution Explorer does not display the proxy class file. This can be changed by clicking the Show All Files button in the Solution Explorer. Now expand the Web References node and the Reference.map node underneath. This will reveal a node labeled Reference.cs. Double-clicking this node will display the code for the proxy class.

There are a few things that should be called out in the proxy class. First, the proxy class gives the client code the ability to specify which URL to use when contacting with the XML Web service. The proxy class has the URL property of type String that represents the URL to the .aspx page of the XML Web service. Since the Windows CE and Pocket PC emulators have a different IP address than the computer they are running, you will not be able to locate the XML Web service by using the default URL in the proxy that uses localhost as the server name. Instead, use the server's name or IP address. This book recommends using the IP address to avoid problems with resolving the server's name .

Second, in the proxy class file, there exists a class named Quote . This class corresponds to the Quote class created on the server-side to hold quote data. Listing 9.4 contains the declaration of the Quote class from the proxy class code file.

Listing 9.4
 C# [System.Xml.Serialization.XmlTypeAttribute( Namespace="http://netcfkickstart/QuoteService")] public class Quote {   /// <remarks/>   public string String;   /// <remarks/>   public string Author;   /// <remarks/>   public string Date; } VB <System.Xml.Serialization.XmlTypeAttribute _   ([Namespace]:="http://netcfkickstart/QuoteService")> _ _ Public Class Quote   '<remarks/>   Public Str As String   '<remarks/>   Public Author As String   '<remarks/>   Public Data As String End Class 

The System.Xml.Serialization.XmlTypeAttribute attribute tells the client-side XML Web service architecture to use the http://netcfkickstart/QuoteService namespace when serializing an object of this type. The Quote class must be declared in the proxy so that the client and servers can use the same data structures when interacting. All custom data structures that are exposed via an XML Web service will be declared for use by the client in the proxy class code file.

Consuming the QuotableQuotes Web Service

Now that a reference is added to the client project and a proxy class has been generated, the XML Web service can be consumed by the client application. Open the designer for the client UI, and double-click the Get Quote button. This will bring up the code for the button-clicked handler. Before implementing this method, the namespace of the proxy class needs to be added to Form1.cs . The proxy class that was generated is placed in its own namespace under the namespace of the client. Add the following using directive under to Form1.cs :

 
 C# using QuotableQuotesClient.QuoteServiceWebReference; VB Imports QuotableQuotesClientVB.localhost 

The handler simply needs to create an instance of the proxy class, invoke the GetQuote method, and display the quote data in the UI. Implement the handler by using the code in Listing 9.5.

Listing 9.5
 C# private void btnGetQuote_Click(object sender, System.EventArgs e) {   QuoteService qs = new QuoteService();   Quote quote = qs.GetQuote();   if(null == quote)   {     MessageBox.Show("An error occurred retrieving a quote");     Return;   }   UpdateQuoteUI(quote); } VB Private Sub btnGetQuote_Click(ByVal sender As System.Object,         ByVal e As System.EventArgs) Handles Button1.Click    Dim qs As New QuoteService    Dim quote As Quote    quote = qs.GetQuote()    If quote Is Nothing Then       MessageBox.Show("An error occurred retrieving a quote")     Return   End If   UpdateQuoteUI(quote) End Sub 

The UpdateQuoteUI is a simple helper method that extracts the data from a Quote object and updates the application's UI. Listing 9.6 contains the code for the UpdateQuoteUI method.

Listing 9.6
 C# private void UpdateQuoteUI(Quote quote) {   lblQuote.Text = quote.String;   lblAuthor.Text = "- " + quote.Author;   lblDate.Text = ( quote.Date == "Unknown" ) ?     string.Empty :     quote.Date; } VB Private Sub UpdateQuoteUI(ByVal quote As Quote)   Me.Label1.Text = quote.Str   Me.Label2.Text = "= " & quote.Author   If quote.Data = "Unknown" Then     Me.Label3.Text = String.Empty   Else     Me.Label3.Text = quote.Data   End If End Sub 

Asynchronous Consumption of the Simple Web Service

So far the QuotableQuotes XML Web service has been used in a synchronous manner. The proxy object is created, and the GetQuote Web method is called. The code then blocks waiting for the GetQuote method to return. While this does get the job done, it is not always the desired behavior. For instance, imagine the client is invoking an XML Web service that batches process order requests . The client application would queue up a certain amount of orders and then send the orders to the server at some specified time, such as the end of the day or when the user clicks a Send Orders button. Assume it is a requirement that the application remains responsive and able to create new orders while the orders are being sent to the server. This scenario cries for asynchronous usage of XML Web services. The .NET Compact Framework provides this functionality while demanding very little code to be written by the developer.

The proxy class provides two methods for handling asynchronous Web XML service calls: Begin WebMethod and End WebMethod . In each case replace WebMethod with the name of the Web method. For example, the QuoteService proxy creates the BeginGetQuote and EndGetQuote methods.

The Begin WebMethod method takes two parameters in addition to the parameters the WebMethod takes. Since GetQuote does not accept any parameters, BeginGetQuote accepts only two parameters. The first addition parameter is of type System.AsyncCallback . This represents the method that will be called once the WebMethod has completed. The second addition parameter is of type object and can be anything that you want that represents the state of the WebMethod call.

To create an asynchronous client start by creating a stub callback function on the client. The method must be public and static. It must also have no return value and accept one parameter of type System.IAsyncResult . This parameter represents the result of the async call. It also allows access to the state object you passed to Begin WebMethod . Add the following method stub to the client:

 
 C# public static void GetQuoteCallBack(IAsyncResult ar) {   MessageBox.Show("GetQuote completed"); } VB Shared Sub GetQuoteCallBack(ByVal ar As IAsyncResult)   MessageBox.Show("GetQuote completed") End Sub 

Now change the implementation of the button handler to call the XML Web service asynchronously. Just replace the current implementation of the button handler with the implementation from Listing 9.7.

Listing 9.7
 C# private void btnGetQuote_Click(object sender, System.EventArgs e) {   QuoteService qs = new QuoteService();   // Set the url of the proxy to the proper url of the web service   AsyncCallback getQuoteCB = new AsyncCallback(     QuotableQuotesClient.Form1.GetQuoteCallBack);   object[] callBackState = {qs, this};   qs.BeginGetQuote(getQuoteCB, callBackState); } VB Private Sub Button1_Click(ByVal sender As System.Object,         ByVal e As System.EventArgs) Handles Button1.Click   Dim qs As New QuoteService   Dim quote As Quote   Dim getQuoteCB As New AsyncCallback(AddressOf Form1.GetQuoteCallBack)   Dim callBackState(2) As Object   callBackState(0) = qs   callBackState(1) = Me   qs.BeginGetQuote(getQuoteCB, callBackState) End Sub 

The preceding code first creates an instance of the Web service. An AsycnCallback object is created that represents a pointer GetQuoteCallBack method on the client. Finally, the Web service call is started by using the BeginGetQuote method. This method returns before the Web method call has completed. Note, an array is passed as the second parameter of the BeginGetQuote method. This array contains two elements: a reference to the Web service proxy and a reference to the client application. These objects will be used to retrieve the return value once the Web method completes.

The GetQuoteCallBack stub needs a proper implementation. In the callback, two actions need to be performed:

  • Retrieving the quote data from the Web method call

  • Filling the UI with the quote data

Listing 9.8 contains the complete implementation of the GetQuoteCallBack method.

Listing 9.8
 C# public static void GetQuoteCallBack(IAsyncResult ar) {    object[] callBackState = (object[])ar.AsyncState;   QuoteService qs = (QuoteService)callBackState[0];   Form1 app = (Form1)callBackState[1];   Quote quote = qs.EndGetQuote(ar);   if(null == quote)   {     MessageBox.Show("No quote object received.");     return;   }   app.UpdateQuoteUI(quote); } VB Shared Sub GetQuoteCallBack(ByVal ar As IAsyncResult)   Dim callBackState() = CType(ar.AsyncState, Object())   Dim qs As New QuoteService   Dim app As Form1   Dim quote As Quote   quote = qs.EndGetQuote(ar)   If quote Is Nothing Then     MessageBox.Show("No quote object received.")     Return   End If   app = CType(callBackState(1), Form1)   app.UpdateQuoteUI(quote) End Sub 

The array that was passed as the state object to the BeginGetQuote method provides access to the quote data. That array can be retrieved by accessing the AsyncState property on the IAsyncResult object. The reference to the proxy is the first element in the array. The proxy's EndGetQuote method returns the Quote object returned by the Web service. Finally, the Quote data structure is used to fill the application UI. Notice, the GetQuoteCallBack function is a static method. So, there is no way to call UpdateQuoteUI without an instance of the application. This is why an instance of the application was stored in the array passed to BeginGetQuote method. This instance is used to call UpdateQuoteUI .



Microsoft.NET Compact Framework Kick Start
Microsoft .NET Compact Framework Kick Start
ISBN: 0672325705
EAN: 2147483647
Year: 2003
Pages: 206

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net