Creating Web Services





Creating Web Services

To better understand Web services, you should be familiar with both sides of the conversation. In this section, you'll learn how to create a Web service by using the tools built into ASP.NET.

Creating a Web Service Project

To create a Web service, you can build an ASP.NET project in Visual Studio .NET.

NOTE

Web Server Required You need to have an IIS Web server available to you to complete the examples and exercises in this chapter that create Web services and Web applications. You get IIS as a part of the Windows 2000 Professional, Windows XP Professional, and Windows Server operating systems.


STEP BY STEP

4.2 Creating a Web Service

  1. Create a new project in Visual Studio .NET. Select the ASP.NET Web Service template and name the new project StringProc, as shown in Figure. (substituting your own Web server name for localhost, if the Web server is not on your local machine).

    4. The New Project dialog box enables you to create a new Web service project in the Visual Studio .NET IDE.

    graphics/04fig04.jpg

  2. Right-click the Service1.asmx file in Solution Explorer and rename it Strings.asmx. Open the form in code view and change all occurrences of Service1 to refer to Strings instead.

  3. Click the hyperlink on the Strings.asmx design surface to switch to the code view. Add the following attribute before the Strings class definition:

    
    [WebService(
    
      Namespace="http://NetExam.org/StringProc")]
    
    public class Strings : System.Web.Services.WebService
    
    
  4. Enter the following methods in the class definition:

    
    [WebMethod()]
    
    public String ToUpper(String inputString)
    
    {
    
       return inputString.ToUpper();
    
    }
    
    
    
    [WebMethod()]
    
    public String ToLower(String inputString)
    
    {
    
        return inputString.ToLower();
    
    }
    
    
  5. Save the project.

  6. Select Build, Build Solution to create the Web service on the server.

You now have a functioning Web service on your Web server. Congratulations! Although lots of plumbing is involved in properly hooking up a Web service, Visual Studio .NET protects you from having to set up any of it. Instead, you have to do only three things:

  • Build the project from the ASP.NET Web Service template.

  • Mark the classes that should be available via the Web service by using the WebService attribute.

  • Mark the methods that should be available via the Web service by using the WebMethod attribute.

EXAM TIP

The Web Service Namespace The WebService attribute requires you to supply a value for the Namespace property. This value (http://NetExam.org/StringProc in Step-by-Step 4.2) is purely arbitrary. It doesn't have to resolve to an actual Web site. This string is just a unique identifier for your Web service. If you leave the default value instead of changing it, you get a warning from Visual Studio .NET.


The methods marked with the WebMethod attribute are also known as Web methods.

Testing the Web Service Project

Visual Studio .NET includes built-in tools, hosted on an HTML test page, for testing a Web service project without building any client applications for the Web service. Step-by-Step 4.3 shows you how to use these tools, which can save you time when you're debugging a Web service.

STEP BY STEP

4.3 Testing a Web Service

  1. Run the Web Service project from Step-by-Step 4.2. Run the project. A browser is launched that shows the test page shown in Figure.

    5. When you view a Web service in a browser, a Web service test page with hyperlinks to Web methods is displayed.

    graphics/04fig05.jpg

  2. Click the Service Description link on the test page. This lets you view the WSDL for this Web service. Click the Back button in the browser to return to the test page.

  3. Click the ToUpper link on the test page. This opens a page for testing the ToUpper() method, as shown in Figure.

    Figure. The Web method test page allows you to test the Web method by using the HTTP GET protocol.

    graphics/04fig06.jpg

  4. The Web method test page shows the SOAP messages and other messages that the Web service understands. It also contains a form that allows you to test the Web method.

  5. Enter a string with mixed uppercase and lowercase characters at the inputString prompt.

  6. Click the Invoke button. A second browser window opens, as shown in Figure, with the XML message that the Web service sends back when you call the ToUpper() method on the test string.

    7. The Web service returns the results in the XML format.

    graphics/04fig07.jpg

  7. Experiment with the ToLower() method in the same way you experimented with the ToUpper() method. When you click the Invoke button, the test page constructs the appropriate XML message and passes it to the Web service, which returns the results.

REVIEW BREAK

  • Visual Studio .NET includes an ASP.NET Web Service template that you can use to build your own Web services.

  • To make a class available via a Web service, you mark the class with the WebService attribute.

  • To make a method available via a Web service, you mark the method with the WebMethod attribute.

  • To test a Web service, run the project in the Visual Studio .NET IDE.

GUIDED PRACTICE EXERCISE 4.1

In this exercise, you are required to create a Web service to allow the client applications to perform database lookup for a SQL Server database.

Specifically, you need to perform these tasks:

  1. Build a Web service that exposes a single class named Customer. The Customer class should expose a Web method named GetCustomers(). The GetCustomers() Web method should accept a country name and return a DataSet object that contains all the customers from that country. You should use the data from the Customers table of the Northwind sample database.

  2. Build a client application that uses the Web service from step 1. The user should be able to enter a country name and see all the customers from that country.

How would you accomplish these tasks?

You should try working through this problem on your own first. If you are stuck, or if you'd like to see one possible solution, follow these steps:

  1. Create a new project in Visual Studio .NET. Select the ASP.NET Web Service template and name the new project Northwind.

  2. Right-click the Service1.asmx file in Solution Explorer and rename it Customer.asmx. Open the form in code view and change all occurrences of Service1 to refer to Customer instead.

  3. Add the following using directive:

    
    using System.Data.SqlClient;
    
    
  4. Enter this code to create the GetCustomers() Web method:

    
    [WebMethod()]
    
    public DataSet GetCustomers(String Country)
    
    {
    
        // Create a SqlConnection
    
        SqlConnection cnn = new SqlConnection(
    
        "Data Source=(local);" +
    
        "Initial Catalog=Northwind;" +
    
        "Integrated Security=SSPI");
    
        // Create a SqlCommand
    
        SqlCommand cmd = cnn.CreateCommand();
    
        cmd.CommandType = CommandType.Text;
    
        cmd.CommandText = "SELECT * FROM Customers " +
    
           " WHERE Country = '" + Country + "'";
    
        // Set up the DataAdapter and
    
        // fill the Dataset object
    
        SqlDataAdapter da = new SqlDataAdapter();
    
        da.SelectCommand = cmd;
    
        DataSet ds = new DataSet();
    
        da.Fill(ds, "Customers");
    
        // And return it to the client
    
        return ds;
    
    }
    
    
  5. Select Build, Build Solution to create the Web service on the server.

  6. Build the client application. Open your Windows application for this chapter and add a new form to the project.

  7. Place a Label control, a TextBox control (txtCountry), a Button control (btnGetCustomers), and a DataGrid control (dgCustomers) on the form. Figure shows a possible design of the form.

    8. You can test the Web methods that return complex objects through a Windows form.

    graphics/04fig08.jpg

  8. Right-click the References folder in Solution Explorer and select Add Web Reference. The Add Web reference dialog box appears.

  9. Type http://localhost/Northwind/Customer.asmx (substituting your own Web server name for localhost, if the Web server is not on your local machine) in the Address bar of the Add Web Reference dialog box, and press Enter. You are then connected to the server, where you can and download the information about the Northwind Web service.

  10. Click the Add Reference button.

  11. Switch to the code view of the form. Add the following using directives:

    
    using System.Data;
    
    using System.Data.SqlClient;
    
    
  12. Double-click the Button control on the form. Enter the following code to handle the button's Click event (replace localhost with the name of your own Web server, if localhost is not applicable):

    
    private void btnGetCustomers_Click
    
       (object sender, System.EventArgs e)
    
    {
    
        // Create a DataSet object
    
        // to hold the customers of interest
    
        DataSet dsCustomers;
    
        // Connect to the Web service
    
        // and retrieve customers
    
        localhost.Customer cust =
    
           new localhost.Customer();
    
        dsCustomers = cust.GetCustomers(txtCountry.Text);
    
        // Bind the results to the user interface
    
        dgCustomers.DataSource = dsCustomers;
    
        dgCustomers.DataMember = "Customers";
    
    }
    
    
  13. Insert the Main() method to launch the form. Set the form as the startup object for the project.

  14. Run the project and enter a country name (such as France). Click the Get Customers button. After a brief delay while the project contacts the Web service, the DataGrid control fills with data, as shown in Figure.

    Figure. The Web form displaying the contents of the DataSet object returned by the GetCustomers() Web method.

    graphics/04fig09.jpg

As this exercise shows, you can return complex objects from a Web service as easily as you can return simple types. The Web service takes care of all the details of converting the DataSet object to an XML representation, wrapping it in a SOAP message, sending it to the client, and reconstituting the DataSet object there.

If you have difficulty following this exercise, review the sections "Invoking Your First Web Service" and "Creating a Web Service Project" earlier in this chapter. Also, review the section "Running Queries" in Chapter 1, "Creating and Manipulating DataSets." After doing that review, try this exercise again.


     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows