Web Services


The information about Web services in this chapter is divided into two subsections:

  • "Exposing Web Services," which concerns writing Web services and placing them on Web Servers.

  • "Consuming Web Services," which concerns using the services you design on a client.

Exposing Web Services

Web services are exposed by placing code either directly into .asmx files or by referencing Web service classes from these files. As with ASP.NET pages, creating a Web service in Visual Studio .NET uses the latter method, and you will too for demonstration purposes.

Create a Web service project (via File New Web Site...) in the C:\ProCSharp\Chapter28 directory and call it PCSWebService1 (see Figure 28-1). Creating a Web service project generates a similar set of files as creating a Web application project, and you have the same location options for creating the project. In fact, the only difference is that instead of a file called Default.aspx, a file called Service.asmx is created, with code-behind in App_Code/Service.cs.

image from book
Figure 28-1

The code in Service.asmx is as follows:

 <%@ WebService Language="C#" CodeBehind="~/App_Code/Service.cs"  %> 

This references the code file /App_Code/Service.cs. The following listing shows the generated code:

 using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Service : System.Web.Services.WebService { public Service() { } [WebMethod] public string HelloWorld() { return "Hello World"; } } 

This code contains several standard namespace references, and defines the Web service class Service (which is referenced in Service.asmx), which inherits from System.Web.Services.WebService. The WebService attribute specifies the namespace for the web service, which enables client applications to differentiate between web service methods with the same name, but on different web services. The WebServiceBinding attribute relates to Web service interoperability, as defined in the WS-I Basic Profile 1.1 specification. Put simply, this attribute can declare that a Web service supports a standard WSDL description for one or more of its Web methods, or, as is the case here, defines a new set of WSDL definitions. It is now up to you to provide additional methods on this Web service class.

Adding a method accessible through the Web service simply requires defining the method as public and giving it the WebMethod attribute. This attribute simply labels the methods you want to be accessible through the Web service. You look at the types you can use for the return type and parameters shortly, but for now replace the autogenerated HelloWorld() method with the following one:

 [WebMethod] public string CanWeFixIt() { return "Yes we can!";  } 

Now compile the project.

To see whether everything works, run the application with Ctrl+F5 and you'll be taken straight to the test interface for the Web service, as shown in Figure 28-2.

image from book
Figure 28-2

Most of the text shown in the browser concerns the fact that the Web service namespace is set to http://tempuri.org/. This isn't a problem during development, although (as the text says) it should be changed later on. This can be done using the WebService attribute as shown. For now, though, you'll leave things as they are.

Clicking the method name gives you information about the SOAP request and response, as well as examples of how the request and response will look using the HTTP GET and HTTP POST methods. You can also test the method by clicking the Invoke button. If the method requires simple parameters, you can enter these on this form as well (for more complex parameters this form won't allow you to test the method in this way). If you do this you, will see the XML returned by the method call:

 <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/">Yes we can!</string> 

This demonstrates that your method is working perfectly.

Following the Service Description link from the browser screen shown in Figure 28-2 allows you to view the WSDL description of the Web service. The most important part is the description of the element types for requests and responses:

 <wsdl:types> <s:schema elementFormDefault="qualified" targetNamespace="http://tempuri.org/"> <s:element name="CanWeFixIt"> <s:complexType /> </s:element> <s:element name="CanWeFixItResponse"> <s:complexType> <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="CanWeFixItResult" type="s:string" /> </s:sequence> </s:complexType> </s:element> </s:schema> </wsdl:types> 

The description also contains descriptions of the types required for requests and responses, as well as various bindings for the service, making it quite a long file.

Types available for Web services

Web services can be used to exchange any of the following types:

String

Char

Byte

Boolean

Int16

Int32

Int64

UInt16

UInt32

UInt64

Single

Double

Guid

Decimal

DateTime

XmlQualifiedName

Class

struct

XmlNode

DataSet

enum

Arrays of all these types are also allowed, as are generic collection types such as List<string>. Note also that only public properties and fields of Class and struct types are marshaled.

Consuming Web Services

Now that you know how to create Web services, in this section you look at how to use them. To do this, you need to generate a proxy class in your code that knows how to communicate with a given Web service. Any calls from your code to the Web service will go through this proxy, which looks identical to the Web service, giving your code the illusion that you have a local copy of it. In actual fact there is a lot of HTTP communication going on, but you are shielded from the details. There are two ways of doing this. You can either use the WSDL.exe command line tool or the Add Web Reference menu option in Visual Studio .NET.

Using WSDL.exe from the command line generates a .cs file containing a proxy class, based on the WSDL description of the Web service. You specify this using the URL of the Web service, for example:

WSDL http://localhost:61968/PCSWebService1/Service.asmx?WSDL
Note

Note that both here and in the example that follows you are using the default file system hosting for Web applications. In order for the preceding URL to work the Visual Web Developer Web Server for the Web service must be running. There is also no guarantee that the port number for the Web service (in this case 61968) will stay the same. While this is fine for illustration, typically you will want your Web services to reside on a fixed Web server such as IIS — otherwise you'll have to continually remake proxy classes. One way to make sure the Web service is available for testing is to include multiple Web sites in one solution.

This generates a proxy class for the example from the previous section in a file called Service.cs. The class will be named after the Web service, in this case Service, and contain methods that call identically named methods of the service. To use this class you simply add the .cs file generated to a project and use code along the lines of:

 Service myService = new Service();  string result = myService.CanWeFixIt(); 

By default, the class generated is placed in the root namespace, so no using statement is necessary, but you can specify a different namespace to use with the /n:<namespace> command-line option of WSDL.exe.

This technique works fine but can be annoying to continually redo if the service is being developed and changing continuously. Of course, it could be executed in the build options for a project in order to automatically update the generated proxy before each compile, but there is a better way.

This better way is illustrated by creating a client for the example in the previous section, in a new Web site called PCSWebClient1 (in the C:\ProCSharp\Chapter 28 directory). Create this project now and add the following code to Default.aspx:

<form  runat="server">   <div> <asp:Label Runat="server"  /> <br /> <asp:Button Runat="server"  Text="Invoke CanWeFixIt()" OnClick="triggerButton_Click" />   </div> </form>

You'll bind the button-click event handler to the Web service shortly. First, you must add a reference to the Web service to your project. To do this, right-click the new client project in the Solution Explorer and select the Add Web Reference... option. In the window that appears, type the URL of the Web service Service.asmx file, or use the "Web services on the local machine" link to find it automatically, as shown in Figure 28-3.

image from book
Figure 28-3

From here you can add a reference with the Add Reference button. First, though, change the default entry for Web reference name from localhost to myWebService. Pressing the Add Reference button now adds myWebService to the WebReferences folder of the project in Solution Explorer. If you examine this folder in the Solution Explorer widow, you can see that the files Service.disco, Service.discomap, and Service.wsdl have been added to the project.

The Web reference name, myWebService, is also the namespace you need to reference to use the proxy class that has been created for you. Add the following using statement to your code in Default. aspx.cs:

 using myWebService; 

Now you can use the service in your class without fully qualifying its name.

Add an event handler to the button on the form with the following code:

 protected void triggerButton_Click(object sender, EventArgs e) { Service myService = new Service(); resultLabel.Text = myService.CanWeFixIt(); } 

Running the application and clicking the button displays the result of CanWeFixIt() in the browser window.

Note

Note that if you are using the ASP.NET Development Server (that is, your web applications are hosted on the local file system not IIS) you may get a 401: Unauthorized error. This is because this server is configured to require NTLM authentication by default. To fix this you can either disable this setting by unchecking the NTLM Authentication box on the Start Options page of the property pages for PCSWebService1 or pass default credentials when calling the web service method. This latter option requires the code myService.Credentials = System.Net.CredentialCache.Default Credentials;.

This Web service might change later, but with this method you can simply right-click the WebReference folder in the Server Explorer and select Update Web Reference. This generates a new proxy class foryou to use.




Professional C# 2005
Pro Visual C++ 2005 for C# Developers
ISBN: 1590596080
EAN: 2147483647
Year: 2005
Pages: 351
Authors: Dean C. Wills

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