Chapter 21. Building XML Web Services

In this chapter, you are introduced to XML Web services in the ASP.NET Framework. You will learn how to create and consume Web services that expose simple data, database data, and custom objects.

In this chapter, you will learn

  • How to create a Web service that returns a random fortune

  • How to create a Web service that exposes the contents of the Products database table

  • How to create an Invoice Web service that exposes instances of a custom class

  • How to improve the performance of a Web service by caching Web service data

  • How to take advantage of dynamic discovery when building Web services

What Is a Web Service?

The primary function of a Web service is to enable application-to-application communication. You can use a Web service to transmit a variety of different types of data across a network, including documents, DataSets, custom objects, and binary data. The network can be a local network or it can be the Internet.

In this chapter, we’ll focus on using Web services to transmit information from one Web server to another. However, Web services can also be used to transmit information from a Web server to a desktop application or from one desktop application to another desktop application.

The following are some examples of how Web services can be used:

  • Product Catalog Web Service—Your company creates a set of products that are sold through several partner Web sites. Different partners sell different subsets of your catalog of products. You want to enable your partners to automatically keep their Web sites updated with your latest product information.

    If you expose the product catalog through a Web service, your partners can automatically query the Web service to show the latest product information on their Web pages.

  • Credit Card Authorization Web Service—You need to authorize credit cards in real-time to authorize purchases at your Web site. In that case, you could use a credit card authentication Web service. The Web service would enable you to send a purchase amount, credit card number, and credit card expiration date, and you receive an authentication code.

  • Driving Directions Web Service—You want to supply customers with driving directions to your business at your Web site. You want customers to be able to enter their home address and get detailed driving directions to your place of business. In that case, you can take advantage of a Web service that returns driving directions. Microsoft already has a Web service like this called MapPoint .NET (see msdn.microsoft.com).

  • Security Web Service—You want to maintain a single database of usernames and passwords used for logging into any of the Web applications maintained by your business. In that case, you can create a Web service that validates usernames and passwords. This Web service can be used by different applications, even when the applications are hosted at different locations.

One thing that you need to keep in mind while reading this chapter is that Web services are still a very new technology. At this date in time, there are not a lot of useful Web services out there. However, it is expected that eventually there will be a huge market in business-to-business and business-to-consumer Web services.

Tip

Visit uddi.microsoft.com or www.xmethods.com for a directory of existing Web services.

It’s also important to understand that XML Web services are not a Microsoft technology. If they were, the technology would fail. Web services are supported by several Web application technologies including Java, Cold Fusion, and Delphi.

One of the big promises of Web services is that they will enable communication between different applications running on different platforms. Most large organizations use a variety of technologies (.NET and Java, for example). Web services have the promise of enabling applications written on different platforms to seamlessly communicate.

Web services work by sending XML using the HTTP protocol. This is important because it means that a Web service will work in all the same situations as a Web page. In other words, if you can access a Web page from a Web server, you can access a Web service. Web services do not have the same firewall issues as other remote invocation technologies.

ASP.NET Web Services

An ASP.NET Web service is Microsoft’s implementation of Web services in the .NET Framework. An ASP.NET Web service is a .NET class that has certain methods and properties that can be accessed across a network.

You create an ASP.NET Web service by marking certain methods and properties of a class with the WebMethod attribute. That’s all you have to do. After you have marked a method as a Web method, the method can be invoked over the network. If the Web server is on the Internet, the method can be invoked from anywhere in the known universe.

For example, suppose that you want to create a Fortune Web service. This Web service will randomly return your fortune. You can implement this Web service with the following class:

C#

using System;
using System.Web.Services;

namespace myApp
{
  public class FortuneService
  {

    [WebMethod]
    public string GetFortune()
    {
      Random objRand = new Random();
      switch (objRand.Next(3))
      {
        case 0:
          return "Things look bad!";
    case 1:
      return "Things look good!";
    default:
      return "Stay home and hide!";
      }
    }

  }
}

VB.NET

Imports System.Web.Service

Public Class FortuneService
    Inherits System.Web.Services.WebService

    <WebMethod()> Public Function GetFortune() As String
        Dim objRand As New Random()
        Select Case objRand.Next(3)
            Case 0
                Return "Things look bad!"
            Case 1
                Return "Things look good!"
            Case Else
                Return "Stay home and hide!"
        End Select
    End Function

End Class

Notice that all that you need to do to implement the Fortune Service is to create a .NET class. This class has one method exposed as a Web method—GetFortune(). All the rest of the work of getting Web services to function is taken care of behind the scenes by the .NET Framework.

Creating a Simple ASP.NET Web Service

In this section, we’ll build a simple Web service and test the service from the browser. We’ll create a Math Service that adds two numbers together.

You should think of creating a Web service in the same way as you would think of creating a class in a class library. Although you can add a Web service directly to an existing ASP.NET Web application, you’ll typically need to package the Web service in a separate project so that you can reuse the same Web service in multiple projects. Consequently, the first step in creating the Math Service is to add a new ASP.NET Web Service project to our solution:

  1. Select New from the File menu and select Project.

  2. In the New Project dialog, select ASP.NET Web Service. In the location text box, name the new project myServices and click OK.

Next, we need to create the actual Web service:

  1. Right-click the myServices project in the Solution Explorer window and select Add, Add Web Service.

  2. Enter the name MathService for the new Web service and click Open.

  3. Double-click the Designer surface to switch to the Code Editor and enter the following method in the body of the class declaration:

    C#

    [WebMethod]
    public int AddNumbers(int val1, int val2)
    {
      return val1 + val2;
    }
    

    VB.NET

    <WebMethod()> Function AddNumbers(ByVal val1 As Integer, ByVal val2 As Integer) As Integer
      Return val1 + val2
    End Function
    
  4. Right-click the MathService.asmx service in the Solution Explorer window and select Build and Browse.

    When the MathService.asmx Web service opens in the browser, you’ll get something called the Web Service Help Page (see Figure 21.1). The ASP.NET Framework automatically generates the Web Service Help Page. It lists all the Web methods available in a Web service.

    The Web Service Help Page.

    Figure 21.1. The Web Service Help Page.

Tip

You can customize the appearance of the Web Service Help Page by modifying the DefaultWsdlHelpGenerator.aspx file that you can find in the WINNTMicrosoft.NETFrameworkFramework VersionCONFIG directory.

You can test any of the Web methods listed in the Web Service Help page. For example, if you click the AddNumbers link, you can test the Web method. You should get a form that enables you to enter two numbers. If you click the Invoke button, you’ll get the XML file in Figure 21.2.

The XML file returned by invoking AddNumbers.

Figure 21.2. The XML file returned by invoking AddNumbers.

There’s one other thing that you should notice about the Web Service Help page. If you return to the main page, you should notice a link labeled Service Description. If you click this link, the Web Services Description Language (WSDL) file is opened (see Figure 21.3).

The Web Services Description Language file.

Figure 21.3. The Web Services Description Language file.

The WSDL file is an XML file that contains the public interface for the Web service. For example, it lists all the Web methods of the Web service, the data types of all its parameters, and the Web method return types. You’ll need to use the WSDL file when communicating with the Web service. For now, you should notice that you always get the WSDL file for an ASP.NET Web service by entering the URL followed by ?WSDL as in the following:

http://localhost/myApp/MathService.asmx?WSDL

Invoking a Web Service from a Web Form Page

As you saw in the previous section, creating a Web service is very easy. Just create a class and decorate certain methods and properties with the WebMethod attribute.

In this section, you’ll learn how to invoke a Web service. Visual Studio .NET also makes this process very easy. The development environment takes care of all the messy details of generating the necessary code to communicate with the Web service across the network for you.

When reading this section, it helps to pretend that we are trying to communicate with a Web service in Australia (if you happen to live in Australia, think of New Jersey). Suppose that you want to invoke the Math Service from a Web Form Page to add two numbers together. To do this, the only information that you need from the Australian Web service is the WSDL file. Remember that you can always retrieve the WSDL file for an ASP.NET Web service by appending the query string ?WSDL to the URL for the Web service.

Let’s go ahead and do this in Visual Studio .NET:

  1. Create a new ASP.NET Web Application project named TestMyServices by right-clicking the name of your Solution in the Solution Explorer window and selecting Add, Add New Project.

  2. Right-click the References folder in the Solution Explorer window and select Add Web Reference. Doing this will open the Add Web Reference dialog box (see Figure 21.4).

    The Add Web Reference dialog box.

    Figure 21.4. The Add Web Reference dialog box.

  3. Enter the following URL in the address bar:

    http://localhost/myServices/MathService.asmx?WSDL
    
  4. Click the Add Reference Button.

When you complete these steps, Visual Studio .NET will automatically retrieve the WSDL file from the Math Service and generate something called a Web service proxy class. The Web service proxy class acts as a local representation of the remote Web service class.

After you retrieve the WSDL file, you should see a new folder named Web References in the Solution Explorer window. There should be a Web reference named localhost in this folder. This Web reference contains the proxy class for the Math Service.

You can view the contents of the proxy class itself by selecting Show All Files from the Project menu, expanding localhost in the Solution Explorer window, and expanding the Reference.map file. Hiding behind the Reference.map file, you’ll discover a file named Reference.cs or Reference.vb. This is the Web service proxy class. Double-click it to view its contents.

The Math Service proxy class has the following three methods:

  • AddNumbersCall this method to synchronously invoke the AddNumbers method on the remote Web service.

  • BeginAddNumbersCall this method to asynchronously invoke the AddNumbers method onWeb services the remote Web service.

  • EndAddNumbersThis method is called when a response is returned from calling the BeginAddNumbers method.

The easiest method of invoking the remote AddNumbers method of the Math Service is by simply calling the AddNumbers method of the proxy class. You’ll use the other two methods only when you need to interact with a Web service asynchronously (asynchronous Web services are not discussed in this book).

Let’s go ahead and add the proxy class to a Web Form Page:

  1. Add a new Web Form Page to the TestMyServices project named testMathService.aspx.

  2. Add two TextBox controls and a Button and Web Forms Label control to the TestMathService.aspx page.

  3. Double-click the Button control to switch to the Code Editor.

  4. Enter the following code for the Button1_Click handler:

    C#

    private void Button1_Click(object sender, System.EventArgs e)
    {
      localhost.MathService objService = new localhost.MathService();
      Label1.Text = objService.AddNumbers
        (
          Int32.Parse(TextBox1.Text),
          Int32.Parse(TextBox2.Text)
        ).ToString();
    }
    

    VB.NET

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    VB.NET Handles Button1.Click
      Dim objService As New localhost.MathService()
    
      Label1.Text = objService.AddNumbers(TextBox1.Text, TextBox2.Text)
    End Sub
    
  5. Right-click the TestMathService.aspx page and select Build and Browse.

If you enter numeric values into the two TextBox controls and click the button, the values are passed to the remote Web service. The response from the Web service is displayed in the Label control.

Web Services and Namespaces

When you create a Web service, you should supply it with a unique namespace. That way, if two companies create a Web service with the same name (for example, two Web services named MathService.asmx), there is still a way to distinguish between them.

You can supply any string for a namespace. However, it is a good idea to use the URL for your company as the namespace because you know that this URL will be unique.

You add a namespace to a Web service class by using the WebService attribute before the class declaration as in the following:

C#

[WebService(Namespace="http://yourDomain.com/webservices/")]
public class MathService
{
  ...
}

VB.NET

<WebService(Namespace:="http://yourDomain.com/webservices/")> Public Class MathServicea
  ...
End Class

Exposing Database Data Through a Web Service

You’ll remember from our discussion of DataSets in Chapter 8, “Overview of ADO.NET,” that you can seamlessly convert a DataSet to and from XML. Because a DataSet can be easily converted into XML, this means that you can pass a DataSet both to and from a Web service.

Warning

You cannot use DataReaders with a Web service. A DataReader, unlike a DataSet, requires an open database connection. A DataReader, therefore, cannot be persisted to a static XML representation.

In this section, we’ll create a Product Web service that exposes the contents of the Products database table. We’ll create the Web service so that it accepts a parameter that represents the product category. That way, people can query the Product Web service for different subsets of products.

First, we need to create the Products Web service itself:

  1. Add a new Web service to the myServices project named ProductService.asmx.

  2. Drag the Products database table from beneath the Northwind database in the Server Explorer window onto the Designer surface. This will add an SqlConnection and SqlDataAdapter to the Designer.

  3. Add an Untyped DataSet to the Designer by dragging the DataSet from the Toolbox.

  4. Select the SqlDataAdapter in the Properties window, expand the SelectCommand property and assign the following SQL SELECT statement to the CommandText property:

    SELECT Products.* FROM Products
    INNER JOIN Categories
    ON Products.CategoryID = Categories.CategoryID
    WHERE (Categories.CategoryName = @CategoryName)
    
  5. Double-click the Designer surface to switch to the Code Editor.

  6. Enter the following GetProducts() method in the body of the class:

    C#

    [WebMethod]
    public DataSet GetProducts(string Category)
    {
      sqlDataAdapter1.SelectCommand.Parameters[ "@CategoryName" ].Value = Category;
      sqlDataAdapter1.Fill( dataSet1);
      return dataSet1;
    }
    

    VB.NET

    <WebMethod()> Function GetProducts(ByVal Category As String) As DataSet
      SqlDataAdapter1.SelectCommand.Parameters("@CategoryName").Value = Category
      SqlDataAdapter1.Fill(DataSet1)
      Return DataSet1
    End Function
    
  7. Right-click the ProductService.asmx file in the Solution Explorer window and select Build and Browse.

After the Web Service Help Page opens, you can test the Product Web service by clicking the GetProducts() link. For example, you can enter the category Seafood when invoking the Web service to retrieve all the seafood products. Invoking the Web service returns an XML file that represents the DataSet returned by the Web service (see Figure 21.5).

The Products DataSet as XML.

Figure 21.5. The Products DataSet as XML.

Next, we need to create a Web Form Page to test the Product service. First, we need to add the Web reference:

  1. Right-click the References folder in the TestMyServices project and select Add Web Reference.

  2. Enter the following URL in the address bar:

    http://localhost/myServices/ProductService.asmx?WSDL
    
  3. Click Add Reference.

Now, we are finally ready to create the Web Form Page. We’ll create a page that displays the DataSet returned from the Product service in a DataGrid:

  1. Add a new Web Form Page to the TestMyServices project named TestProductService.aspx.

  2. Add TextBox, Button, and DataGrid controls to the page.

  3. Double-click the Button control and enter the following code for the Button1_Click handler:

    C#

    private void Button1_Click(object sender, System.EventArgs e)
    {
      localhost1.ProductService objService = new localhost1.ProductService();
      DataGrid1.DataSource = objService.GetProducts(TextBox1.Text);
      DataGrid1.DataBind();
    }
    

    VB.NET

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    VB.NET Handles Button1.Click
      Dim objService As New localhost1.ProductService()
    
      DataGrid1.DataSource = objService.GetProducts(TextBox1.Text)
      DataGrid1.DataBind()
    End Sub
    
  4. Right-click the TestProductService.aspx page in the Solution Explorer window and select Build and Browse.

Note

The Web service proxy class is declared in the TestMyServices page using localhost1.ProductService. The localhost1 prefix refers to the namespace. If this is the first Web reference that you have added to the TestMyServices project, the correct namespace would be localhost. If this is the second Web reference, the correct namespace would be localhost1, and so on.

After the TestProductService.aspx page opens, you can enter different categories of products (for example, Seafood, Beverages, or Produce) in the text box and click the button to display matching products in the DataGrid (see Figure 21.6).

The TestProductService.aspx page.

Figure 21.6. The TestProductService.aspx page.

Exposing a Custom Object Through a Web Service

You can expose custom objects through a Web service. This is useful when you need to represent structured information, such as invoices, job descriptions, resumes, and product orders with a Web service.

In this section, we’ll create a simple Invoice Web service that exposes instances of a custom Invoice class. This Web service could be used, for example, to pass invoices between different offices in a company.

Let’s start by creating the Invoice class itself:

Procedure 21.1. C# Steps

  1. Add a new class to the myServices project named Invoice.cs.

  2. Enter the following code for the Invoice.cs class:

    using System;
    
    namespace myServices
    {
      public class Invoice
      {
        public DataTime Date;
        public Decimal Amount;
        public string Description;
      }
    }
    

Procedure 21.2. VB.NET Steps

  1. Add a new class to the myServices project named Invoice.vb.

  2. Enter the following code for the Invoice.vb class:

    Public Class Invoice
        Public [Date] As DateTime
        Public Amount As Decimal
        Public Description As String
    End Class
    

Our Invoice class has three properties—Date, Amount, and Description.

The next step is to expose an instance of this class through a Web service:

  1. Add a new Web service named InvoiceService.asmx to the myServices project.

  2. Double-click the Designer to switch to the Code Editor and enter the following Web method:

    C#

    [WebMethod]
    public Invoice GetInvoice()
    {
      Invoice objInvoice = new Invoice();
    
      objInvoice.Date = DateTime.Now;
      objInvoice.Amount = 1322.34m;
      objInvoice.Description = "Dell Laptop";
    
      return objInvoice;
    }
    

    VB.NET

    <WebMethod()> Function GetInvoice() As Invoice
      Dim objInvoice As New Invoice()
    
      objInvoice.Date = DateTime.Now
      objInvoice.Amount = 1322.34
      objInvoice.Description = "Dell Laptop"
    
      Return objInvoice
    End Function
    
  3. Right-click the InvoiceService.asmx file in the Solution Explorer window and select Build and Browse.

If you test the Invoice service by clicking the GetInvoice link in the Web Services Help Page, an XML representation of the Invoice class is returned.

The final step is to invoke the Invoice service from a Web Form Page. Perform the following steps to add a Web reference to the Invoice service:

  1. Right-click the References folder in the TestMyServices project and select Add Web Reference.

  2. Enter the following URL in the address bar:

    http://localhost/myServices/InvoiceService.asmx?WSDL
    

Perform the following steps to create a Web Form Page that displays the properties of an invoice:

  1. Add a new Web Form Page to the TestMyServices project named TestInvoiceService.aspx.

  2. Add a Label control to the TestInvoiceService.aspx page.

  3. Double-click the Designer surface to switch to the Code Editor.

  4. Enter the following code for the Page_Load handler:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
      localhost2.Invoice objInvoice;
      localhost2.InvoiceService objService = new localhost2.InvoiceService();
    
      objInvoice = objService.GetInvoice();
      Label1.Text = "<li> Invoice Date: ";
      Label1.Text += objInvoice.Date.ToString("D");
      Label1.Text += <li> Invoice Amount: ";
      Label1.Text += objInvoice.Amount.ToString( "c" );
      Label1.Text += "<li> Invoice Description: ";
      Label1.Text += objInvoice.Description;
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
      Dim objInvoice As localhost2.Invoice
      Dim objService As New localhost2.InvoiceService()
      objInvoice = objService.GetInvoice()
      Label1.Text = "<li> Invoice Date: "
      Label1.Text &= objInvoice.Date.ToString("D")
      Label1.Text &= "<li> Invoice Amount: "
      Label1.Text &= objInvoice.Amount.ToString("c")
      Label1.Text &= "<li> Invoice Description: "
      Label1.Text &= objInvoice.Description
    End Sub
    
  5. Right-click the TestInvoiceService.aspx page in the Solution Explorer window and select Build and Browse.

After you complete these steps, the invoice passed by the Invoice service is displayed in the Label control (see Figure 21.7).

The custom Invoice object displayed in a Label control.

Figure 21.7. The custom Invoice object displayed in a Label control.

You should notice that we never declared the Invoice class in the TestMyServices project. The definition of the Invoice class is included in the WSDL file for the Invoice service.

Advanced Web Service Topics

In this section, we’ll tackle three advanced Web service topics. First, you’ll learn how to gracefully handle errors when calling a Web method. Next, you’ll learn how to take advantage of caching when working with a Web service. Finally, you’ll learn how to use dynamic discovery to add a single Web reference that represents multiple Web services.

Handling Errors When Calling Web Methods

You might be wondering about what happens when you attempt to call a Web method from a Web service and the Web service is unavailable. In that case, by default, your Web Form Page will wait 90 seconds for the Web method to timeout and then the Web Form Page will display a “This operation has timed out” error message.

90 seconds is a long time to keep a user waiting for a response. You can change the timeout period for a Web service proxy by modifying the value of the Timeout property as follows:

C#

localhost1.HelloService objService = new localhost1.HelloService();

objService.Timeout = 10000;

try
{
  Label1.Text = objService.SayHello();
}
catch
{
  Label1.Text = "Web service unavailable!";
}

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
VB.NET MyBase.Load
  Dim objService As New superexpert.HelloService()

  objService.Timeout = 10000
  Try
    Label1.Text = objService.SayHello()
  Catch
    Label1.Text = "Web service unavailable!"
  End Try
End Sub

The Timeout property accepts a value in milliseconds. In this code, the Web service proxy class is set to timeout after 10 seconds (10,000 milliseconds).

Caching the Output of Web Methods

Most likely, if you are using a Web service to publish a catalog of products, your list will not change very often. In that case, you should take advantage of caching to reduce the load on your Web server.

There are two ways that you can cache the data returned by a Web method. You can use the WebMethod attribute to enable caching for a particular Web method. Alternatively, you can use the Cache object.

The WebMethod attribute has a property called CacheDuration. You can use the CacheDuration property to cache the output generated by a WebMethod for a certain number of seconds. The following is an example of how this property can be used with a Web method that returns the current time:

C#

[WebMethod(CacheDuration=30)]
public string GetTime()
{
  return DateTime.Now.ToString( "T" );
}

VB.NET

<WebMethod(CacheDuration:=30)> Function GetTime() As String
  Return DateTime.Now.ToString("T")
End Function

The GetTime() Web method in this case will cache its output for 30 seconds.

As an alternative to using the CacheDuration property, you can use the Cache object. (To learn more about the Cache object see Chapter 14, “Improving Application Performance with Caching.”) The advantage of using the Cache object is it can be used to cache the same data across multiple Web methods.

The following shows how you can use the Cache object in a Web method:

C#

[WebMethod]
public DataSet GetCachedProducts()
{
  DataSet dstProducts =
    (DataSet)Context.Cache[ "Products" ];
  if (dstProducts == null)
  {
    dstProducts = new DataSet();
    sqlDataAdapter1.Fill( dstProducts );
    Context.Cache[ "Products" ] = dstProducts;
  }
  return dstProducts;
}

VB.NET

<WebMethod()> Function GetCachedProducts() As DataSet
  Dim dstProducts As DataSet

  dstProducts = Context.Cache("Products")
  If dstProducts Is Nothing Then
    dstProducts = New DataSet()
    SqlDataAdapter1.Fill(dstProducts)
    Context.Cache("Products") = dstProducts
  End If
  Return dstProducts
End Function

The GetCachedProducts Web method caches the products database table in memory so that the database is not hit each and every time the Web method is called. Notice that you must refer to the Cache object within a Web method by using Context.Cache.

Using Dynamic Discovery

When you add a reference to a standard class library to a project, you only need to add a single reference. You don’t need to add a reference for each and every class contained in the library.

When adding a reference to a Web service, on the other hand, we’ve had to add a separate reference for each Web service. This is true even though all the Web services are collected together in the same project.

We’ve been adding references to Web services by referring to the WSDL file for a Web service. There’s an alternative. Instead of adding a reference to a WSDL file, you can add a reference to a .vsdisco file.

Whenever you create a new project in Visual Studio .NET, a .vsdisco file is automatically added to your project. The .vsdisco file is the dynamic discovery file. When you request a project’s dynamic discovery file, the ASP.NET Framework automatically searches for all the Web services contained in the project and displays them. If you enter the path to a project .vsdisco file when adding a Web reference, you get a proxy class that represents all the Web services in a project.

For security reasons, dynamic discovery is disabled by default. You can enable dynamic discovery by editing the Machine.Config file located in the WINNITMicrosoft.NETFrameworkFramework VersionConfig folder.

Open the Machine.Config file in Notepad, find the <httpHandlers> section, and remove the comments around the .vsdisco handler.

If you don’t want to modify the Machine.Config file (or you don’t have access to this file), you can also enable dynamic discovery for a ASP.NET Web Service project by adding the following section to the <system.web> section of the project root Web.Config file:

<httpHandlers>
  <add verb="*" path="*.vsdisco"
    type="System.Web.Services.Discovery.DiscoveryRequestHandler, System.Web.Services,
Using Dynamic Discovery Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="false"/>
</httpHandlers>

Warning

Dynamic discovery will not work unless you provide the Web services in a project with a proper namespace by supplying a value for the WebService attribute’s Namespace property. See the earlier section in this chapter, “Web Services and Namespaces.”

After you complete these steps to enable dynamic discovery, you can replace all the individual Web references that you previously added with a single Web reference. Right-click the References folder and select Add Web Reference. In the address bar of the Add Web Reference dialog box, enter the path to the dynamic discovery file:

http://localhost/myServices/myServices.vsdisco

After you click Add Reference, you’ll have a single reference for all the Web services in the myServices project.

For example, to invoke the AddNumbers() method of the Math Service from a Web Form Page, you would use code like the following:

C#

localhost.MathServiceSoap objService =
    new localhost.MathServiceSoap();
Label1.Text = objService.AddNumbers(1,2).ToString();

VB.NET

Dim objService As New localhost.MathServiceSoap()
Label1.Text = objService.AddNumbers(1, 2)

Notice that you refer to the Math Service as MathServiceSoap instead of MathService. The expression Soap is automatically appended to the name of each of the Web service proxy classes when the Web reference is generated.

Summary

In this chapter, you learned how to build Web services in the ASP.NET Framework. In the first section, you were given a quick overview of Web services. You learned that, within the ASP.NET Framework, a Web service is nothing more than a class that has certain methods and properties marked with the WebMethod attribute.

Next, we walked through the steps necessary for creating several Web services. We created a Web service that exposes database data. We also created a Web service that exposes a custom object.

Finally, we examined some advanced issues that you’ll encounter when building Web services. We discussed how you can control the timeout value for a Web service, how you can improve the performance of a Web service through caching, and how you can create one Web reference that represents many Web services.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset