Building Web Services with C


Building Web Services with C#

Because Web services are so widely accepted across the industry, you can use a large list of programming languages to build them. This chapter focuses on using both C# and Java to build some Web services. Later I will show you how to consume these same services.

Building an XML Web service means that you are interested in exposing some information or logic to another entity either within your organization, to a partner, or to your customers. In a more granular sense, building a Web service means that you, as a developer, simply make one or more methods from a class you create that is enabled for SOAP communication.

When building C# Web services using the .NET Framework, you can use the main IDE for Microsoft development, Visual Studio, or you can even go as far to use Notepad for your Web services development.

Note 

Note that the examples in this chapter are using Visual Studio 2005 based upon the .NET Framework 2.0.

The first step is to actually create a new Web site by choosing File image from book New image from book Web Site from the Visual Studio menu (depending on your version). This launches the New Web Site dialog. Select ASP.NET Web Service, as shown in Figure 19-1. Building a Web service means that you are interested in exposing some information or logic to another entity either within your organization, to a partner, or to your customers. In a more granular sense, building a Web service means that you, as a developer, simply make one or more methods from a class you create enabled for SOAP communication.

image from book
Figure 19-1

Visual Studio creates a few files you can use to get started. In the Solution Explorer of Visual Studio (see Figure 19-2) you find a single Web service file named Service.asmx; its code-behind file, Service.cs, is located in the App_Code folder.

image from book
Figure 19-2

For this example, you expose as a Web service the Customers table from the sample Northwind database found in SQL Server 2000. For this example, delete the Service.asmx and Service.cs files and then right-click the project and select Add New Item from the provided menu. Add a new Web service and give it the name of Customers.asmx.

Adding this new Web services to your project actually produces a couple of file. The first is the Web service file-Customers.asmx. The second file for this Web service is the code-behind file which you find in the App_Code folder of the solution. The name of this file is Customers.asmx.cs (or Customers.asmx.vb if you are using Visual Basic).

If you open the Customers.asmx file in Visual Studio, you see that the file contains only the @WebService page directive, as illustrated in Listing 19-4.

Listing 19-4: Contents of the Customers.asmx file

image from book
      <%@ WebService Language="C#" CodeBehind="~/App_Code/Customers.cs"           %> 
image from book

You use the @WebService directive instead of the @Page directive.

The simple WebService directive has only four possible attributes. The following list explains these attributes:

  • q Class-Required. It specifies the class used to define the methods and data types visible to the Web service clients.

  • q CodeBehind-Required only when you are working with a Web service file using the code- behind model. It enables you to work with Web services in two separate and more manageable pieces instead of a single file. The CodeBehind attribute takes a string value that represents the physical location of the second piece of the Web service-the class file containing all the Web service logic. In ASP.NET 2.0, it is best to place the code-behind files in the App_Code folder, starting with the default Web service created by Visual Studio when you initially opened the Web service project.

  • q Debug-Optional. It takes a setting of either True or False. If the Debug attribute is set to True, the Web service is compiled with debug symbols in place; setting the value to False ensures that the Web service is compiled without the debug symbols in place.

  • q Language-Required. It specifies the programming language that is used for the Web service.

Next, for this Web service, you only need to expose a single method-GetCustomers(). This is illustrated in Listing 19-5.

Listing 19-5: Exposing the Customers table from the Northwind database in SQL Server

image from book
      using System;      using System.Web;      using System.Web.Services;      using System.Web.Services.Protocols;      using System.Data;      using System.Data.SqlClient;      [WebService(Namespace = "http://www.wrox.com/")]      [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]      public class Customers : System.Web.Services.WebService      {          public Customers () {          }          [WebMethod]          public DataSet GetCustomers()          {              SqlConnection conn;              SqlDataAdapter myDataAdapter;              DataSet myDataSet;              string cmdString = "Select * From Customers";              conn = new                 SqlConnection("Server=localhost;uid=sa;pwd=;database=Northwind");              myDataAdapter = new SqlDataAdapter(cmdString, conn);              myDataSet = new DataSet();              myDataAdapter.Fill(myDataSet, "Customers");              return myDataSet;          }      } 
image from book

For .NET-based Web services, you should pay attention to a couple of things. Note that you are notifying .NET that this is a Web service in a couple of ways. The first is by using the Web service file extension of .asmx. The second thing of note is illustrated in Listing 19-5. The Customers class is turned into a Web service through the use of the [WebService] attribute directly preceding the class.

      [WebService(Namespace = "http://www.wrox.com/")] 

In this case, not only is the WebService attribute applied to the class, but the Namespace property is also assigned a value (always a good idea). Another possible property to assign within the WebService attribute is Description. Using this property applies a description of the Web service in the WSDL file and might make it easier for developers to understand what the Web service provides.

Something that is new the .NET Framework 2.0 release is the new [WebServiceBinding] attribute. It builds the Web service responses so that they conform to the WS-I Basic Profile 1.0 release (found at http://www.ws-i.org/Profiles/BasicProfile-1.0-2004-04-16.html).

Besides the attributes that are applied to the Customers class, you can also see (from Listing 19-5) that this class inherits from the System.Web.Services.WebService class. The only method doing anything in this class is the GetCustomers() method, which basically dishes out everything contained in the Customers table from the Northwind database in a single response. Your Web service class (Customers) can contain as many methods as you deem necessary, but only the methods that are marked with the [WebMethod] attribute are actually exposed out to any consumer. This is only done for the GetCustomers() method-also known as a WebMethod.

Using the Microsoft Web Services Test Page

One nice feature provided by the Microsoft Web services development environment is a developer testing page (or a potential consumer testing page as well) for Web services. Pulling up the .asmx file in the browser produces the visual test page for the Web service that is being exposed. Remember, usually each Web service is URL-accessible; so to view the visual representation of the Web service, you simply type in the URL of the Web service. An example of this is http://www.localhost:1364/Wrox1/Customers.asmx. The visual test page for the Web services is presented in Figure 19-3.

image from book
Figure 19-3

This Web interface to your Web service provides the user with the name of your service as well as a list of all the available WebMethods that the consumer can utilize from the Web service. From the preceding figure, you can see that the name of the Web service is provided in the dark blue band at the top of the page (Customers) and that the GetCustomers() WebMethod is the only method exposed from this Web service.

The other item of importance on the page is a link to the WSDL document for the Web service. This link is provided between the Web service title in the blue band and the list of available WebMethods on the page. Again, the WSDL document is a description of the interface to the Web service. Clicking the link Service Description pulls up a new page in the browser that shows you the complete WSDL document (as shown in Figure 19-4).

image from book
Figure 19-4

With this WSDL document, the consumer (or the consumer's IDE) can learn how to consume the Web service. Note that a .NET-based Web service does not have an actual .wsdl file in the project that can be referenced directly in the browser. Instead, the WSDL file is invoked by referencing the name of the file which holds the Web service and tacking on a ?WSDL at the end.

http://www.localhost:1364/Wrox1/Customers.asmx?WSDL

Instead of having an actual file in the system, ASP.NET creates one for you dynamically. This doesn't mean that you can't create your own WSDL files. You can do so, but most users stick with the dynamically created WSDL files to represent the interface of their Web services.

Testing the WebMethod

Besides the link to the Web service's WSDL file and a list of methods from the service, the ASP.NET Web service test page also provides consumers with the capability to test actual WebMethods directly in the browser. If a consumer clicks the WebMethod link (GetCustomers) in the browser, he is taken to a page where he can test the WebMethod to see how it performs. The GetCustomers() WebMethod page is shown in Figure 19-5.

image from book
Figure 19-5

The WebMethod test page enables the consumer to actually test the exposed method. If the method requires parameters, he can find text boxes on the test page in addition to the Invoke button which is shown in Figure 19-5. Because the GetCustomers() WebMethod doesn't require any input parameters to invoke the service, you will not find these text boxes in the figure-just the Invoke button.

In addition to an HTTP-POST form that allows you to invoke WebMethod, you also find some visual documentation that shows the developer what kind of SOAP structure is required to invoke the service as well as the SOAP response the consumer can expect in return. When building Web services in .NET 2.0, you also find documentation for SOAP 1.2 and HTTP-POST requests as well.

Clicking the Invoke button on the page causes the test page to send an HTTP-POST request to the WebMethod. You then see the following response in a new browser instance (shown in Figure 19-6).

image from book
Figure 19-6

Altering the Protocols Used by the Web Service

By default in .NET 2.0, SOAP and HTTP-POST requests are allowed to any Web services on the platform. .NET 1.0 did allow for HTTP-GET requests, but this feature was removed in the default installation starting with .NET 1.1.

To enable HTTP-GET, make changes to your web.config file as shown in Listing 19-6.

Listing 19-6: Enabling HTTP-GET in your Web service applications

image from book
      <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">         <system.web>            <webServices>               <protocols>                  <add name="HttpGet"/>               </protocols>            </webServices>         </system.web>      </configuration> 
image from book

Creating a <protocols> section in your web.config file enables you to add or remove protocol communications. For example, you can add missing protocols (such as HTTP-GET) by using the syntax shown previously, or you can remove protocols as the following example shows:

      <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">         <system.web>            <webServices>               <protocols>                  <remove name="HttpGet"/>                  <remove name="HttpPost"/>                  <remove name="HttpSoap"/>                  <remove name="Documentation"/>               </protocols>            </webServices>         </system.web>      </configuration> 

You don't want to remove everything shown in this code because that would leave your Web service with basically no capability to communicate; but you can see the construction required for any of the protocols that you do want to remove. The node removing Documentation is interesting because it can eliminate the capability to invoke the Web services interface test page if you don't want to make that page available for any reason.




Professional XML
Professional XML (Programmer to Programmer)
ISBN: 0471777773
EAN: 2147483647
Year: 2004
Pages: 215

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