Consuming Web Services

Snoops

   

 
Migrating to .NET: A Pragmatic Path to Visual Basic .NET, Visual C++ .NET, and ASP.NET
By Dhananjay Katre, Prashant Halari, Narayana Rao Surapaneni, Manu Gupta, Meghana Deshpande

Table of Contents
Chapter 11.  Exposing Legacy Components as Web Services


We can use traditional clients such as Visual Basic or ASP to consume the Web service. The SOAPClient object is used to access the Web service in these applications.

When writing a client using any of the Microsoft .NET-compliant languages such as Visual Basic, Visual C, C#, and JScript, the WSDL file has to be converted to a proxy class enclosing the Web service methods . This proxy object is then instantiated to access the methods. Command-line tools that come shipped along with the .NET Framework SDK help create the proxy class. These will be discussed in the following sections.

Using SOAPClient

SOAPClient is initialized using the service description file. After being initialized , the SOAPClient can be used as a COM object. In the Web application CodeSamples , the ASP file usingSOAP.asp demonstrates this:

 graphics/icon01.gif <script language=vbscript runat=server>     Dim objSoapClient     Dim path     Set objSoapClient = _     server.CreateObject("MSSOAP.SoapClient")     path = server.MapPath("WSDLfromCOM.wsdl")     objSoapClient.mssoapinit(path)     Response.Write (objSoapClient.getMessage())  </script> 

This code can be used to access the Web service from a Visual Basic application after making few modifications such as replacing Response.Write with MsgBox . To obtain the same functionality in ASP.NET, we have to add a reference to the Microsoft SOAP Type Library in the Web application. The SOAPClient can then be created and its methods can be accessed as follows . The Web application CodeSamples contains an ASP.NET file usingSOAP.aspx that demonstrates this.

 graphics/icon01.gif <%@ Page Language="vb" %>     <html>     <head>        <title>usingSOAP</title>        <script runat=server>        Sub useSOAP()           Dim objSOAPClient as MSSOAPLib.SoapClient           Dim path as String           objSOAPClient = new MSSOAPLib.SoapClient()           path = server.MapPath("WSDLfromCOM.wsdl")           objSoapClient.mssoapinit(path)           Response.Write(objSoapClient.getMessage())        End Sub        </script>     </head>     <Body >        <% Call useSOAP()%>     </body>     </html> 

Using .NET Client

The communication between a client and a Web service over the network is carried out using SOAP messages, which encapsulate the in and out parameters as XML. Under the .NET Framework, a proxy class handles the work of mapping parameters to XML elements and then sending the SOAP message over the network.

A proxy class can be generated from a service description using the command-line tool wsdl.exe , present under the Program Files/Microsoft Visual Studio .NET/FrameworkSDK/Bin directory of the install root. A client can then invoke methods of the proxy class, which in turn communicate with the Web service over the network by processing the SOAP messages sent to and from a Web service.

To generate a proxy class, type the following line at the command prompt:

 C:\>wsdl /l:VB /n:TestService /out:Service1.vb http://local- host/codeSamples/WSDLfromCOM.wsdl 

The wsdl.exe requires at least one parameter specifying the location of the service description file. In the preceding command /l: represents language; it specifies the language in which the proxy class should be generated. The default language is C#. The example specifies language as Visual Basic. /n: stands for namespace for the generated proxy class and /out: represents file name for the proxy class. The default communication protocol for the proxy class is SOAP over HTTP. We can change the protocol in wsdl.exe using an argument /protocol .

The proxy class is created in a single file specified in the /out parameter of the command. The proxy class created in the example is available in the WebServices folder.

 graphics/icon01.gif Option Strict Off  Option Explicit On  Imports System  Imports System.ComponentModel  Imports System.Diagnostics  Imports System.Web.Services  Imports System.Web.Services.Protocols  Imports System.Xml.Serialization  '  'This source code was auto-generated by wsdl, Ver_  sion=1.0.3705.0.  '  Namespace TestService      '<remarks/>      'CODEGEN: The optional WSDL extension element 'binding'       from namespace 'http://schemas.microsoft.com/soap-      toolkit/wsdl-extension' was not handled.      <System.Diagnostics.DebuggerStepThroughAttribute(),  _       System.ComponentModel.       DesignerCategoryAttribute("code"),_       System.Web.Services.  WebServiceBindingAttribute(Name:="MyClassSoapBinding",  [Namespace]:="http://tempuri.org/wsdl/")>  _      Public Class WSDLfromCOM          Inherits System.Web.Services._          Protocols.SoapHttpClientProtocol          '<remarks/>          Public Sub New()              MyBase.New              Me.Url =              "http://localhost/CodeSamples/WSDLfromCOM.wsdl"          End Sub          '<remarks/>          <System.Web.Services.Protocols.         SoapRpcMethodAttribute_         ("http://tempuri.org/action/MyClass.GetMessage", Re         questNamespace:="http://tempuri.org/message/", Re         sponseNamespace:="http://tempuri.org/message/")>  _          Public Function GetMessage() As <Sys _          tem.Xml.Serialization.          SoapElementAttribute("Result")> String              Dim results() As Object =_              Me.Invoke("GetMessage", New Object(-1) {})              Return CType(results(0),String)          End Function          '<remarks/>          Public Function BeginGetMessage(ByVal callback As          System.AsyncCallback, ByVal asyncState As Object)           As System.IAsyncResult              Return Me.BeginInvoke("GetMessage", New Ob              ject(-1) {}, callback, asyncState)          End Function          '<remarks/>          Public Function EndGetMessage(ByVal asyncResult As          System.IAsyncResult) As String              Dim results() As Object = _              Me.EndInvoke(asyncResult)              Return CType(results(0),String)          End Function      End Class  End Namespace 

The proxy class generates synchronous and asynchronous methods for each of the methods of a Web service. For the Web service method GetMessage , the preceding proxy class shows two asynchronous methods, BeginGetMessage and EndGetMessage . This proxy class has to be compiled into an assembly to make it available to a .NET client. Notice that the proxy class contains references to several namespaces within the .NET Framework. Because the proxy class is created in Visual Basic, we use the Visual Basic compiler vbc.exe . If proxy class is created in C#, use the C# compiler csc.exe . To compile the proxy class, type the following at the command prompt:

 vbc /t:library /r:System.Web.dll /r:System.Web.Services.dll  /r:System.Xml.dll Service1.vb 

Because we want to create an assembly corresponding to the proxy class, we specify the target as library in the parameter /t: in the command. We then add references to each of the namespaces included in the proxy class under the /r: parameter. Finally, we specify the file name of the proxy class to be compiled into an assembly. The output of the above command is the assembly Service1.dll .

This assembly can be placed in the /bin directory of any .NET application, and methods of the Web service can be accessed through the proxy class. The following example, TestWebService.aspx in Web application CodeSamples , demonstrates this:

 graphics/icon01.gif <%@ Page Language="vb" %>  <%@ Import Namespace="TestService" %>     <html>     <head>     <title>TestWebService</title>        <script runat="server">         Sub TestWS()           Dim objWS As TestService.Service1           objWS = New TestService.Service1()           Response.Write(objWS.GetMessage())        End Sub        </script>     </head>     <body>        <% Call TestWS() %>     </body>     </html> 

Thus, we have seen how to use the SOAP ToolKit to create the service description files and then use these to initialize the SOAPClient . The SOAPClient object can then access methods of the Web service. The command-line tool wsdl.exe uses the service description file to create a proxy class, which can then be used in a client written in any of the Microsoft .NET-compliant languages such as Visual Basic, Visual C, C#, and JScript.

With Visual Studio .NET, creating and accessing Web services is simplified. In Visual Studio .NET, creating a Web service doesn't require you to build a separate listener application. When accessing a Web service, proxies are automatically created that make working with a Web service look just like accessing any other object.

.NET Web Services

In this section we will create a Web service using Visual Studio .NET and consume the service in an ASP.NET client.

CREATING A WEB SERVICE USING VISUAL STUDIO .NET

Create the Web service using the following steps:

  1. Open Visual Studio .NET and click File New New Project. Select ASP.NET Web service under Visual Basic Projects. Click OK. See Figure 11-5.

    Figure 11-5. Create New Project as an ASP.NET Web service.

    graphics/11fig05.gif

  2. The Web service contains a file Service1.asmx by default. The file contains a WebMethod HelloWorld by default. We add a method to convert temperature in Celsius to Fahrenheit:

     graphics/icon01.gif <WebMethod(Description:="This method converts a temperature in  degrees Fahrenheit to a temperature in degrees Celsius.")> _     Public Function ConvertTemperature(ByVal dFahrenheit As     Double) As Double        ConvertTemperature = ((dFahrenheit - 32) * 5) / 9     End Function 
  3. Click on Build Build Solution to create the Web service.

If you visit the Service1.asmx page in the browser, you will see that the methods present in file are listed. In this case, GetMessage is displayed on the browser. To view the service description for the Web service, click on the link service description next to the method name. The WSDL file for the newly created Web service appears in the browser as shown in Figure 11-6.

Figure 11-6. Service description of web service.

graphics/11fig06.gif

In the browser click on File Save As and save the file at a convenient location with the file extension .wsdl. In this case, we save the file as Service1.wsdl . Now that the WSDL file is available, we can use wsdl.exe to create a proxy class for the Web service and then compile the proxy class to form the corresponding assembly to be used in the client application as described earlier.

CONSUMING WEB SERVICES USING VISUAL STUDIO .NET

In this example we use the Web application CodeSamples as the client application for consuming the Web service.

  1. In the solution explorer of the Web application, right-click on Web References and click on Add Web Reference. In the address bar, type the URL of the .asmx file as shown in Figure 11-7. Alternatively, you can also point to the WSDL file of the Web service by specifying the query string with the URL as was mentioned earlier.

    Figure 11-7. Selecting required service.

    graphics/11fig07.jpg

  2. Click on Add Reference. A reference to the Web service appears under Web References in the solution explorer for the Web application. If the Web service is on the same machine, as in this case, the proxy under Web References appears as localhost . We have renamed the proxy name from localhost to MyService in the solution explorer as shown in Figure 11-8.

    Figure 11-8. Solution Explorer of Web application after adding Web Reference.

    graphics/11fig08.gif

  3. The Web service can now be accessed through the proxy from any ASP.NET client.

The ASP.NET file Client.aspx in Web application CodeSamples provides a client for the Web service. The ASP.NET page accepts temperature in Fahrenheit and returns temperature in Celsius.

 graphics/icon01.gif <%@ Page Language="vb"  %>     <HTML>     <script language="VB" runat="server">     Public Sub Submit_Click(Sender As Object, E As Even_     tArgs)        Dim tempF As Single = 0        Dim Service As CodeSamples.MyService.Service1        tempF = Single.Parse(Temp.Text)        Service = New CodeSamples.MyService.Service1()        Select (CType(sender,Control).ID)        Case "Convert" :           Result.Text = "<b>" & Ser_           vice.ConvertTemperature(tempF).ToString() & "</b>"        End Select     End Sub     </script>     <body >     <h4>Temperature Conversion Service</h4>     <form runat="server">     <div style="BORDER-RIGHT:black 1px solid;PADDING-    RIGHT:15px;BORDER-TOP:black 1px solid;PADDING-    LEFT:15px;PADDING-BOTTOM:15px;BORDER-LEFT:black 1px     solid;WIDTH:300px;PADDING-TOP:15px;BORDER-BOTTOM:black     1px solid;BACKGROUND-COLOR:beige">        Temperature in Fahrenheit     <br>     <asp:TextBox id="Temp" runat="server" /><br>     <input type="submit" id="Convert" value="Convert" On_     ServerClick="Submit_Click" runat="server">     <p>        Temperature in Celsius :        <asp:Label id="Result" runat="server" />     </p>     </div>     </form>     </body>     </HTML> 

Snoops

   
Top


Migrating to. NET. A Pragmatic Path to Visual Basic. NET, Visual C++. NET, and ASP. NET
Migrating to. NET. A Pragmatic Path to Visual Basic. NET, Visual C++. NET, and ASP. NET
ISBN: 131009621
EAN: N/A
Year: 2001
Pages: 149

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