Previous section   Next section

16.2 Building a Web Service

To illustrate the techniques used to implement a web service in Visual Basic .NET using the services classes of the .NET Framework, you will build a simple calculator and then make use of its functions over the Web.

Begin by specifying the web service. To do so, define a class that inherits from System.Web.Services.WebService. The easiest way to create this class is to open Visual Studio and create a new ASP.NET Web Service project. The default name that Visual Studio provides is WebService1, but you might want to choose something more appropriate.

Visual Studio .NET creates a skeleton web service and even provides a .NET Web Service example method for you to replace with your own code, as shown in Example 16-1.

Example 16-1. Skeleton web class generated by Visual Studio .NET
Option Strict On
Imports System

Imports System.Web.Services

<WebService(Namespace := "http://tempuri.org/")> _
Public Class Service1
    Inherits System.Web.Services.WebService

#Region " Web Services Designer Generated Code "

    Public Sub New( )
        MyBase.New( )

        'This call is required by the Web Services Designer.
        InitializeComponent( )

        'Add your own initialization code after the InitializeComponent( ) call

    End Sub

    'Required by the Web Services Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Web Services Designer
    'It can be modified using the Web Services Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough( )> Private Sub InitializeComponent( )
        components = New System.ComponentModel.Container( )
    End Sub

    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        'CODEGEN: This procedure is required by the Web Services Designer
        'Do not modify it using the code editor.
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose( )
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

#End Region

    ' WEB SERVICE EXAMPLE
    ' The HelloWorld( ) example service returns the string Hello World.
    ' To build, uncomment the following lines then save and build the project.
    ' To test this web service, ensure that the .asmx file is the start page
    ' and press F5.
    '
    '<WebMethod( )> Public Function HelloWorld( ) As String
    '    HelloWorld = "Hello World"
    ' End Function

End Class

Create five methods: Add( ), Sub( ), Mult( ), Div( ), and Pow( ). Each takes two parameters of type Double, performs the requested operation, and then returns a value of the same type. For example, here is the code for raising a number to some specified power:

Function Pow(ByVal x As Double, ByVal y As Double) As Double 
    Dim retVal As Double = x 
    Dim i As Integer 
    For i = 0 To (y - 1) - 1 
        retVal *= x 
    Next i 
    Return retVal 
End Function 'Pow

To expose each method as a web service, you simply add the <WebMethod> attribute before each method declaration (attributes are discussed in Chapter 8). You are not required to expose all the methods of your class as web methods. You can pick and choose, adding the <WebMethod> attribute only to those methods you want to expose.

That's all you need to do; .NET takes care of the rest.

WSDL and Namespaces

Your web service will use a Web Service Description Language (WSDL) XML document to describe the web-callable end points. Within any WSDL document, an XML namespace must be used to ensure that the end points have unique names. The default XML namespace is http://tempuri.org, but you will want to modify this before making your web service publicly available.

You can change the XML namespace by using the WebService attribute:

<WebService(Namespace := _
    "http://www.LibertyAssociates.com/webServices/")>

You can read about attributes in detail in Chapter 8.

Example 16-2 shows the complete source code for the Calculator web service.

Example 16-2. Calculator web service program
Option Strict On
Imports System
Imports System.Web.Services

<WebService(Namespace := "http://tempuri.org/")> _
Public Class Service1
    Inherits System.Web.Services.WebService

#Region " Web Services Designer Generated Code "
#End Region
    <WebMethod(Description:="Add two numbers")> Public _
    Function Add(ByVal x As Double, ByVal y As Double) As Double
        Return x + y
    End Function 'Add

    <WebMethod(Description:="Subtract two numbers")> Public _
    Function Subtract(ByVal x As Double, ByVal y As Double) As Double
        Return x - y
    End Function 'Sub

    <WebMethod(Description:="Multiply two numbers")> Public _
    Function Mult(ByVal x As Double, ByVal y As Double) As Double
        Return x * y
    End Function 'Mult

    <WebMethod(Description:="Divide two numbers")> Public _
    Function Div(ByVal x As Double, ByVal y As Double) As Double
        Return x / y
    End Function 'Div

    <WebMethod(Description:="Raise a number to a power")> Public _
        Function Pow(ByVal x As Double, ByVal y As Double) As Double
        Dim retVal As Double = x
        Dim i As Integer
        For i = 0 To (y - 1) - 1
            retVal *= x
        Next i
        Return retVal
    End Function 'Pow

End Class

When you build this project with Visual Studio .NET, a DLL is created in the appropriate subdirectory of your Internet server (e.g., c:\InetPub\wwwroot\VBWSCals\bin\). A quick check of the base directory reveals that a .vsdisco file has also been added.

There is nothing magical about using Visual Studio .NET; you can create your server in Notepad if you like. Visual Studio .NET simply saves you the work of creating the directories, creating the .vsdisco file, and so forth. Visual Studio .NET is particularly helpful when creating the client files, as you'll see shortly.

16.2.1 Testing Your Web Service

If you open a browser to your web service's URL (or invoke the browser by running the program in Visual Studio .NET), you get an automatically generated, server-side web page that describes the web service, as shown in Figure 16-1. Test pages such as this offer a good way to test your web service. (The next section illuminates the seeming hocus-pocus that produces these pages.)

Figure 16-1. The web service web page
figs/pvn2_1601.gif

Notice that the description that you added to the WebMethod attribute is used here to provide a description of each method. Clicking a method brings you to a page that allows you to invoke it by typing in parameters and pressing the Invoke button. Figure 16-2 illustrates.

Figure 16-2. Test page for a web service method
figs/pvn2_1602.gif

If you type 38 into the first value field and 4 into the second field, you will have asked the web service to raise 38 to the power of 4. The result is an XML page describing the output, as shown in Figure 16-3.

Figure 16-3. XML output for a web service method
figs/pvn2_1603.gif

Notice that the URL encodes the parameters of 38 and 4, and the output XML shows the result of 2085136 (38 x 38 x 38 x 38 = 2085136).

16.2.2 Viewing the WSDL Contract

A lot of work is being done for you automatically. HTML pages describing your web service and its methods are generated, and these pages include links to pages in which the methods can be tested. How is this done?

As noted earlier, the web service is described in WSDL. You can see the WSDL document by appending ?wsdl to the web service URL, like this:

http://localhost/ProgrammingVBNET/VBWSCalc/Service1.asmx?wsdl

The browser displays the WSDL document, as shown in Figure 16-4.

Figure 16-4. Sample WSDL output for calculator web service
figs/pvn2_1604.gif

The details of the WSDL document are beyond the scope of this book, but you can see that each method is fully described in a structured XML format. This is the information used by SOAP to allow the client browser to invoke your web service methods on the server.


  Previous section   Next section
Top