Building JScript .NET Web Service and Clients

This week’s tutorial walks you through creating a Web Service and three types of client applications that use it: a Windows Forms based client, and Internet Explorer-based client, and an ASP.NET client application.

What is a Web Service?

A Web Service is an application that allows its functionality to be called though the Internet using an industry standard system-to-system messaging protocol (SOAP – Simple Object Access Protocol – an XML vocabulary). Web Services allow you to use an application without regard to where it resides, how it is implemented, or how it prefers to be called – all your application does to use a Web Service is issue a call using SOAP, something that’s really easy to do using the .NET Framework. When the Web Service responds, it sends its response using XML, which makes it easy to use.

Web Services usually play a role where they work with data you provide, perform some processing for you, or act as a front end for some type of database. If you think of a Web Service as a means of distributing an application’s logic and processing (CPU time) across the Internet, you’ll have a firm grasp of the types of applications that are suitable for Web Services.

Creating a Web Service using JScript .NET

The Web Service I’ll walk you through determines if a number you provide to it is a prime number. A prime number is a number that’s divisible only by itself and one. For example 139 and 197 are prime numbers because they are (evenly) divisible by themselves and one where as 4 is not prime because you can (evenly) divide it by one, two, and four. In other words, a prime number is a number that’s not a product of (multiplying) two smaller numbers.

Prime numbers are useful in many practical applications, including encryption (applying a mathematical transformation to information to render it useless to an observer because it is difficult to reverse the transformation without knowing a shared secret). Consider the number 28. You can split 28 into smaller positive integers that, when multiplied together result in the original value (28 in this example). The smaller integers are called factors – the factors of 28 are 1, 2, 4, 7, 14, and 28 (you can check this by dividing 28 by each factor; it should divide evenly – without having a remainder). You can go a step further and attempt to find the prime factors of a number – for example the prime factors 77 are 7 and 11, both of which are prime numbers (77 and 1 are the other, non-prime, factors). Cryptography (the science of encryption) relies, in part, on the fact that it is easy to multiply two prime numbers, but difficult to go backwards (determine its factors) – this is especially true for large numbers.

The Web Service we’ll create performs a test to determine if a given number is a prime number. Testing pro prime numbers is a science in itself and there are many ways of determining if a number is prime. I want to focus on the Web Service instead of getting into advanced number theory; as a result, the test the Web Service performs is limited to small numbers (numbers less than 999,999).

What makes a Web Service different from an ASP.NET page is it’s extension – a Web Service resides in a file with an “.asmx” extension. The next attribute that distinguishes a Web Service from other types of files is the first line in the file, as shown below:

<%@ WebService Language="JScript" Class="PrimeNumbers" %>

The line represents a page-level directive that informs ASP.NET that the contents of the file represent a Web Service written in JScript .NET whose code resides in a class called PrimeNumbers. Once you have the page level directive in place, creating a Web Service is as easy as creating a class and adding methods to it. Here’s a JScript class that performs the test to determine if a given number is a prime number:

public class PrimeNumbers
{
  public function IsPrime(n:int) : int
  {
    var i:int;

      if (n % 2 == 0)
        return (n == 2);
      if (n % 3 == 0)
        return (n==3);
      if (n % 5 == 0)
        return (n==5);
      for (i=7; i*i <= n; i+=2)
        if (n % i == 0)
          return 0;
      return 1;
  }
}

The class is called PrimeNumbers and has a single method, IsPrime. At the moment, the class does not represent a Web Service. Here’s what you need to do to convert the class into a Web Service:

  1. Import the System.Web.Services namespace
  2. Derive the class from the .NET Class Library’s WebService class
  3. For each method you want to expose as a Web Service method, add the attribute WebMethodAttribute to the beginning of the method’s declaration

That’s it! Here’s the same class converted into a Web Service:

import System.Web.Services;

public class PrimeNumbers extends WebService
{
  WebMethodAttribute public function IsPrime(n:int) : int
  {
    // implementation identical to previous listing...
  }
}

Having a Web Service is great, but Web Services aren’t all that useful by themselves. The .NET Framework includes some code that makes it easy to test your Web Service directly; however, the interface is very basic and is not intended to serve as a primary interface.

Creating Web Service Clients

Web Service clients do not use a Web Service directly. Client applications usually use an intermediary, called a proxy, to make it easy to work with a Web Service. A proxy handles the details of communicating with the Web Service by sending a request, waiting for a response, and presenting the response to your application. I mentioned that Web Services use XML to communicate – the proxy even converts the XML into data that you can use directly through simple variables in your application.

So where does the proxy come from? The .NET Framework includes a utility that you can use to automatically generate the proxy’s code in whatever language the .NET Framework supports. We’re getting ahead of ourselves, though. The first client I want to demonstrate is one that invokes the Web Service directly through Internet Explorer.

Using a Web Service directly through Internet Explorer

I mentioned that Web Service clients use a proxy to interact with a Web Service. Microsoft provides a generic proxy that you can use with Internet Explorer 5.0 and later to call a Web Service using some client side scripting code. The file you need is called ‘webservice.htc’ – it contains about 51 K of code that makes interacting with a Web Service as simple as writing a few lines of client-side code.

The distribution for this article includes a sample HTML page that interacts with the PrimeNumber Web Service. The page includes a directive that loads the ‘webservice.htc’ file, as shown:

<DIV id="myWebService" style="BEHAVIOR:url(http://.../webservice.htc)">

The address in the above DIV tag refers to the location on where the ‘webservice.htc’ file actually resides. Once you have the HTC file, you can write some JScript code to interact with it and have it call the Web Service for you, as shown:

function init()
{
  myWebService.useService(".../isPrime.asmx?WSDL",
                          "isPrimeNumberWebService");
}
function isPrimeNumber()
{
  myWebService.isPrimeNumberWebService.callService(
    isPrimeNumberResult,"IsPrime",testValue.value);
}

function isPrimeNumberResult(result)
{
  theResult.value=(result.value ? "Yes" : "No");
}

The page’s body tag’s onLoad handler calls the init function (above) to associate the HTC file’s implementation with the location of the Web Service (the address in the first parameter to the useService method) and a symbolic name for the instance (isPrimeNumberWebService).

The HTML page includes two input boxes: one that accepts a number from the user (testValue) and another that displays the result of the prime number test (theResult). When the user clicks on a button on the page, the isPrimeNunber function invokes the callService method, passing in the name of a function that handles the Web Service’s result, the name of the method to call on the Web Service, and the parameter to pass to the Web Service’s method.

The Web Service executes asynchronously from the code in the HTML page. When the Web Service is ready to provide its result to the HTML page, the HTC implementation calls the function you passed to the callService method (the isPrimeNumberResult function). The function simply converts the result into a “Yes” or “No” string, that’s shown in the theResult text box.

I added some code to the page to make it easy for you to see the transition of events as the Web Service gets invoked, executes, and returns the result to the HTML page. There is a status indicator that provides details of what’s happening as the page’s code executes.

Creating a Proxy for the Web Service

Client applications that you create using Windows Forms and ASP.NET work through a proxy that you can generate using a tool that’s part of the .NET Framework, called WSDL.EXE. WSDL takes a Web Service’s description and transforms it into a proxy using the programming language you specify on the command line. The sample code includes a build program that generates the proxy for you; however, working with WSDL is easy.

Suppose that the prime number Web Service’s asmx file is in a virtual directory called “WebServiceSample” on your system’s local Web server. You can generate the proxy code, in JScript .NET using the following command (note: the command must appear on a single line):

wsdl /L:js /NAMESPACE:primeProxy
  /OUT:sampleProxy.js http://localhost/WebServiceSample/IsPrime.asmx

The /L option specifies what programming language WSDL should use for the proxy’s code (JScript .NET in this example). The /NAMESPACE option puts the code into a JScript .NET package, making it easier to reuse and work with the proxy code. The /OUT option specifies the name of the output file to store the code that wsdl generates – if you don’t use the /OUT option wsdl bases the name of the proxy on the name of the Web Service. The last option that wsdl takes is the location of the asmx file. Actually, wsdl queries the asmx file for the Web Service’s description; as a result, wsdl can interoperate with any Web Service as long as it describes itself using standard WDSL (which, by the way, is an XML vocabulary – you don’t need to know the details unless you plan to create Web Services on other platforms).

Once the proxy code is ready, you can compile it using jsc – the JScript .NET compiler. Here’s the command to compile the code:

jsc /t:library sampleProxy.js

The command creates a library (a DLL) that houses the proxy code. Put the library in the same folder as the application that requires the proxy to make it easy to manage. If you want to move or change the location of the Web Service, you must re-generate the proxy code and compile it again since your client applications rely on the proxy to interoperate with the Web Service.

Now you’re ready to create Windows Forms and ASP.NET based client applications.

Using a Web Service through Windows Forms Application

The Windows Forms-based client application has some more functionality than the Internet Explorer-based client. Figure 1 shows what the application looks like after it tests a prime number.

Figure 1 – Windows Forms-based client using the Prime Number Web Service

To keep the listings in this article to the point, I’m going to zoom in on the code that interoperates with the Web Service. If you’re not familiar with Windows Forms, I discussed that in detail in the last article in this series; you can also review the sample’s source code to get an idea of how to work with the Windows Forms classes.

The first thing you need to do is import the proxy’s namespace (package) using the import statement, as shown:

import primeProxy;

When you’re ready to interact with the Web Service, invoke it as shown:

var numberIsPrime : boolean;

var proxy : primeProxy.PrimeNumbers;

proxy = new PrimeNumbers();
numberIsPrime  = Convert.ToBoolean( proxy.IsPrime( numberToTest ) );

When the Web Service evaluates a number as being a prime number it returns the number one, otherwise it returns zero. The Windows Forms client expects the result to be a boolean value, so it converts the result using the Convert class’s ToBoolean method.

Compile the Windows Forms code by referencing the proxy library code on the JScript .NET compiler’s command line, as shown:

jsc /t:winexe /r:sampleProxy.dll primeCalcForm.js

Using the Web Service through ASP.NET

The ASP.NET client provides functionality that’s similar to the Windows Forms client. The code that interacts with the Web Service is identical to that of the Windows Forms client, in fact, I just pasted the code into the ASP.NET page and it worked. I had to make some modifications to the rest of the code that manages the page’s display, but those changes are minor.

Working with the sample code

You can work with the Internet Explorer and ASP.NET clients at my live samples site – click here to try out the samples right now (opens a new window).

The source code distribution includes the code and build file for the Web Service and all three clients. Extract the contents of the ZIP file to a new folder on a system that has the .NET Framework (SDK or Visual Studio .NET) installed on it, and enable Web sharing on that folder. Build the sample using the command:

build [address of Web Service]

Specify the address of the Web Service without the http:// prefix and the name of the asmx file. The program generates the proxy code and compiles it, and compiles the Windows Forms client. Type build on the command line, without any parameters, for help on using the command and for information on how to bind to the sample Web Service on my Web site.


Essam Ahmed is the author of “JScript .NET Programming
(ISBN 0764548689, Published by Hungry Minds September 2001), many
articles (including some at CodeGuru.com) and book reviews (also
available at CodeGuru.com).
Contact Essam at essam@designs2solutions.com,
or at his Web site



More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read