JavaScript EditorFreeware JavaScript Editor     Ajax Tutorials 



Main Page

Previous Page
Next Page

Creating a Windows Web Service

Now it's time to move away from the specifications and theories to create a simple web service. The web service described in this section uses document-style SOAP requests and responses to implement the Math service described in the WSDL file earlier in this chapter. Note that this process uses free tools available from Microsoft, which involve a little more work than if you were to use, say, Visual Studio .NET. However, the extra work you'll do in this section will aid in your understanding of web services and could pay handsome dividends later in your development career should anything go wrong with an auto-generated service.

System Requirements

To create this service, you will need three minimum requirements:

  • A Windows machine running IIS 5 or greater. This comes as standard on all XP Professional machines and on all servers from Windows 2000 onwards.

  • The .NET Framework must be installed on the machine running IIS. You will also need the .NET Software Development Kit (SDK) on the machine you are developing on. For the purposes of this example, it is assumed that you are developing on the machine that is running IIS. (You can download both the .NET Framework and the SDK from http://msdn.microsoft.com/netframework/downloads/updates/default.aspx.)

  • A text editor to write the code. This can simply be Notepad, which is standard on all Windows machines and is more than adequate for the purposes of this example (although for serious development an editor that supports syntax highlighting is preferable).

Configuring IIS

The first task is to create a home for your service. Go to StartAdministrative Tools and select Internet Information Services. (Alternatively, enter %SystemRoot%\System32\inetsrv\iis.msc in the StartRun box and click the OK button.) Expand the tree on the left to show the Default Web Site node, and then right-click and choose NewVirtual Directory, as shown in Figure 6-1. This will bring up the Virtual Directory Creation Wizard, where you choose the name of the web service folder as seen by the client (see Figure 6-2).

Image from book
Figure 6-1
Image from book
Figure 6-2

Name the folder Math, and then click Next. On the next screen, browse to the standard IIS directory of C:\InetPub\wwwroot. Create a new folder, also named Math, directly below this folder. Accept the defaults for the remaining screens of the wizard. When this is done, use Windows Explorer to create a new folder underneath Math named bin, which will hold the DLL once the service is built. Your folder hierarchy should now look like Figure 6-3.

Image from book
Figure 6-3

Coding the Web Service

The web service you are creating is quite simple. Its name is Math, and it implements the four basic arithmetic operations: addition, subtraction, multiplication, and division. These four operations each accept two parameters, defined as floats, and return a float as the result. The class itself will be coded in C#, and the web service will be published in ASP.NET.

Create a new file in your favorite text editor and add the following three lines:

using System;
using System.Web;
using System.Web.Services;

This code doesn't add any extra functionality, but it does save you from having to type fully qualified class names. Since you will be using several classes from these namespaces, it saves space to reference them here.

Next, create a namespace called Wrox.Services and a class called Math that inherits from System.Web.Services.WebService:

namespace Wrox.Services
{
  [WebService (Description = "Contains a number of simple arithmetical functions",
               Namespace = "http://www.wrox.com/services/math")]
  public class Math : System.Web.Services.WebService
  {
    //class code here
  }

}

The namespace keyword is used to in a similar way as namespaces in XML; it means the full name of the Math class is Wrox.Services.Math. Immediately inside the namespace definition is an attribute called WebService, which marks the class on the following line as a web service. Doing this enables extra functionality for the class, such as generating a WSDL file. You will also notice that a Description parameter is included (and will also appear in the WSDL file).

Then comes the class name, Math, which inherits from the base class of System.Web.Services.WebService. Inheriting from this class means that you don't need to worry about any specific code for writing web services; the base class handles all of this. You can simply focus on writing the methods that will be published as part of the web service.

Defining a method to be used in a web service is as easy as writing a regular method and tagging it with the special WebMethod attribute:

[WebMethod(Description = "Returns the sum of two floats as a float")]
public float add(float op1, float op2)
{
  return op1 + op2;
}

Once again, the code is very simple. (What could be simpler than an addition operation?) Any method that has a WebMethod attribute preceding it is considered part of the web service. The Description parameter will become part of the generated WSDL file. Although you can write as many methods as you'd like, here is the complete code for this example, including the four arithmetic methods:

using System;
using System.Web;
using System.Web.Services;

namespace Wrox.Services
{
  [WebService (Description = "Contains a number of simple arithmetical  functions",
               Namespace = "http://www.wrox.com/services/math")]
   public class Math : System.Web.Services.WebService
   {

   [WebMethod(Description = "Returns the sum of two floats as a float")]
   public float add(float op1, float op2)
   {
     return op1 + op2;

    }

    [WebMethod(Description = "Returns the difference of two floats as a float")]
    public float subtract(float op1, float op2)
    {
      return op1 - op2;
    }

    [WebMethod(Description = "Returns the product of two floats as a float")]
    public float multiply(float op1, float op2)
    {
      return op1 * op2;
    }

    [WebMethod(Description = "Returns the quotient of two floats as a float")]
    public float divide(float op1, float op2)
    {
      return op1 / op2;
    }
  }
}

Save this file in the Math directory and name it Math.asmx.cs.

Create another text file and enter the following line:

<%@WebService Language=" c#" Codebehind=" Math.asmx.cs" Class=" Wrox.Services.Math" %>

This is the ASP.NET file that uses the Math class you just created. The @WebService directive tells the page to act like a web service. The meaning of the other attributes should be fairly obvious: Language specifies the language of the code to use; Codebehind specifies the name of the file that the code exists in; and Class specifies the fully qualified name of the class to use. Save this file in Math directory as well, with the name Math.asmx.

Creating the Assembly

After you have created these two files, you can proceed with the next stage: compiling the source code into an assembly that will be housed in a DLL. To do this, you can use the C# compiler that comes with the .NET SDK. This will be in your Windows directory below the Microsoft.Net\Framework\ <version number> folder (for example, C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\).

The easiest way to compile and debug the code is to create a batch file. Create another text file and enter the following (it should all be on one line despite the formatting of the book):

C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\csc.exe /r:System.dll
/r:System.Web.dll
/r:System.Web.Services.dll /t:library /out:bin\Math.dll Math.asmx.cs

Remember to modify the path to csc.exe if necessary and save it to the Math folder as MakeService.bat.

Important

If you are using Notepad, be careful using the Save As dialog box. Make sure that the File Type box is set to All Files, or else enclose the file name in double quotes. Otherwise, Notepad adds a .txt extension to your file.

Next, you need to compile the DLL. Open a command prompt from StartRun and type cmd. Now navigate to the Math folder by typing cd \inetpub\wwwroot\Math. Finally, run the following batch file:

C:\inetpub\wwwroot\Math\MakeService.bat

If all is well, you should be greeted with the compiler displaying some version and copyright information, and then a blank line. This is good news and indicates that the compilation was successful. (If there were any errors, they will be outputted to the console. Check the lines indicated and correct any syntax or spelling mistakes.)

Assuming the DLL has compiled, you are ready to test the service. One of the joys of .NET web services is that a whole test harness is created automatically for you. Open your web browser and navigate to http://localhost/Math/math.asmx. You should soon see a page similar to the one displayed in Figure 6-4.

Image from book
Figure 6-4

You have the choice to try any of the four methods or you can view the generated WSDL file by clicking the Service Description link. This reveals a WSDL file similar to the example earlier in the chapter, but this will have entries for all four methods.

Important

Another way of viewing the WSDL file is to add ?WSDL to the web service URL, such as http://localhost/Math/math.asmx?WSDL.

Since you have probably had enough of the add method, try the divide method. Clicking the link from the previous screen should display the page in Figure 6-5.

Image from book
Figure 6-5

Below the divide heading is the description you used with the WebMethod attribute, and below that is a small test form. If you enter two numbers, such as 22 and 7, you'll receive a response such as the one displayed in Figure 6-6.

Image from book
Figure 6-6

In a production environment, you can now remove the Math.asmx.cs file, as it is no longer needed. The Math.asmx simply passes on all requests directly to the DLL.

This test harness does not use SOAP for the request and response. Instead, it passes the two operands as a POST request; the details of how to do this are shown at the bottom of the divide page in Figure 6-5. Now that you have a web service defined, it's time to use Ajax to call it.


Previous Page
Next Page

Веб Технологии 



JavaScript EditorAjax Editor     Ajax Validator


©