Section 15.3. Creating a Simple Web Service

15.3. Creating a Simple Web Service

Though a web service has no user interface and no visual component, the architecture and files used to create a web service are similar to those used to create a web page, which are described in detail in previous chapters. Some of these similarities include the following:

  • Full implementation of the .NET Framework and Common Language Runtime (CLR), including the object-oriented architecture, all the base class libraries, and features such as caching, state, and data access

  • Nearly identical file and code structures

  • All source code files in plain text, which can be created in any text editor

  • Full support by VS2005, with all its productivity features, including IntelliSense, code completion, and integrated debugging

  • Configurable on a global or application-wide basis using plain-text configuration files and the Web Site Administration Tool in VS2005

That said, web pages and web services are conceptually very different. A web page entails an interface designed for interaction with a person sitting at a web browser. A web service, on the other hand, consists only of methods , some of which are available for remote calls by client applications.

A web service can be coded in-line, in a single file with an extension of .asmx . Alternatively, the application logic of the web service can be segregated into a code-behind file, which is the default behavior of VS2005. One in-line example will be shown here, to aid in your understanding of how web services work, but all the other examples will be done using code-behind from within VS2005.

Code-Behind in Web Services

The rationale for code-behind is that it provides a clean separation between the presentation and programmatic portions of an application. Though this is extremely useful in the development of web pages, it is irrelevant to web services. However, since code-behind is the default coding technique for VS2005 (which offers so many productivity enhancements), code-behind becomes the de facto preferred technique.

In addition, code-behind will confer a performance advantage over in-line code the first time the web service app is run, if the web service class is manually compiled and placed in the bin directory under the virtual root, because the .asmx file is compiled into a class every time it is run. You won't see this advantage, by default, when using ASP.NET Version 2.0, which places the class source code in the App_Code directory and compiles on first use under all circumstances.

You can manually compile the class file and place it in the bin directory. Manual compilation and deployment issues will be covered in Chapter 19.


Whether using an inline or code-behind architecture, the .asmx file is the target entered into the browser for testing, or referenced by the utilities that create the proxy dll . (Recall from a previous section, "How Web Services Work," that the client application actually makes calls to a proxy dll . Creation of this proxy dll will be described in detail in the next chapter.)

As a first step in understanding how web services work, you will create a simple web service twice, the first called StockTickerInLine , using any favorite text editor. As the name implies, this example will use the in-line coding model. This is the only web service example in this book using that coding model and the only example made outside of VS2005. Then you will create essentially the same example, called StockTickerSimple , in VS2005.

This example web service will expose two web methods:



GetName

Expects a stock symbol as an argument and returns a string containing the name of the stock



GetPrice

Expects a stock symbol as an argument and returns a number containing the current price of the stock

If this web service were an actual production program, the data returned would be fetched from a live database. To keep web service issues and data access issues separate, for this example, the data will be stored in a two-dimensional array of strings. For a complete discussion of accessing a database, see Chapters 9 and 10.

15.3.1. In-Line with a Text Editor

In any text editor (Notepad works fine), open a new file called StockTickerInLine.asmx . Locate the file in a virtual directory somewhere on your machine. (To create an IIS virtual directory, go to Computer Management by right-clicking My Computer and selecting Manage, then drill down to Default Web Site under Internet Information Services, and right-click to create a new virtual directory.)

Enter the code shown in Example 15-1.

Example 15-1. StockTickerInLine.asmx
  <%@ WebService Language="C#" Class="ProgAspNet.StockTickerInLine" %>  using System; using System.Web.Services; namespace ProgAspNet {    public class StockTickerInLine  :   System.Web.Services.WebService  {         //  Construct and fill an array of stock symbols and prices.         //  Note: the stock prices are as of 5/1/05.       string[,] stocks =       {          {"MSFT","Microsoft","25.30"},          {"DELL","Dell Computers","34.83"},          {"HPQ","Hewlett Packard","20.47"},          {"YHOO","Yahoo!","34.50"},          {"GE","General Electric","36.20"},          {"IBM","International Business Machine","76.38"},          {"GM","General Motors","26.68"},          {"F","Ford Motor Company","9.11"}       };  [WebMethod]  public double GetPrice(string StockSymbol)       //  Given a stock symbol, return the price.       {          //  Iterate through the array, looking for the symbol.          for (int i = 0; i < stocks.GetLength(0); i++)          {             //  Do a case-insensitive string compare.             if (String.Compare(StockSymbol, stocks[i,0], true) == 0)                return Convert.ToDouble(stocks[i,2]);          }          return 0;       }  [WebMethod]  public string GetName(string StockSymbol)       //  Given a stock symbol, return the name.       {          //  Iterate through the array, looking for the symbol.          for (int i = 0; i < stocks.GetLength(0); i++)          {             //  Do a case-insensitive string compare.             if (String.Compare(StockSymbol, stocks[i,0], true) == 0)                return stocks[i,1];          }          return "Symbol not found.";       }    } } 

This .asmx file contains the entire web service in-line. It defines a namespace called ProgAspNet and creates a class called StockTickerInLine . The class instantiates and fills an array to contain the stock data and then creates the two WebMethods that comprise the public aspects of the web service.

If you're familiar with web page code, you may notice in Example 15-1 that the code for a web service is almost identical to the code in a code-behind page for an equivalent web page. There are some differences, however, which are highlighted in the code example.

The first difference is in the use of a WebService directive at the top of the file rather than a Page directive. As with Page directives (covered in detail in Chapter 6), the WebService directive provides the compiler with necessary information. In this example, it specifies the language in use and the name of the web service class.

The next difference is that the web service class inherits from System.Web.Services.WebService , rather than the Page class. Though this is not a strict requirement, it generally makes your life as the developer much easier. This issue will be covered in detail later in this chapter.

The final difference is that any method that is to be made available as part of the web service, called web methods, is decorated with the WebMethod attribute.

If you locate the file in a virtual directory, say one called websites (which is physically located at c:\WebSites ), you can enter the following URL in a browser to see the web service test page shown in Figure 15-2.

 http://localhost/websites/StockTickerInLine.asmx 

15.3.2. Code-Behind with Visual Studio 2005

VS2005 offers the programmer several advantages over a plain-text editor in addition to automating the creation of code-behind. Among them are color -coding of the source code, integrated debugging, IntelliSense, integrated compiling, and full integration with the development environment. Chapter 2 covers VS2005 in detail.

To create a web service equivalent to the previous example in VS2005, open a new web site. From the list of Visual Studio Installed Templates in the New Web Site dialog, select ASP.NET Web Service. The Location selection will default to File System. Your choice here has the same ramifications as for web pages, described in Chapter 2. Name the web site StockTickerSimple .

As with a normal web site, several files and directories will be created, though the specifics are different for web services. The web service file, called Service.asmx by default (though it is probably a good idea to change it to something more meaningful) is created in the application root directory. It consists of a single line of code, shown in Example 15-2, containing the WebService directive, described in the next section.

Example 15-2. Service.asmx
 <%@ WebService Language="C#" CodeBehind="~/App_Code/Service.cs"     Class="Service" %> 

The code-behind file is created in a subdirectory called App_Code .

Version 1.x ASP.NET required that the web service class be compiled and placed in a bin directory under the virtual root if the code-behind model was used, as was default for Visual Studio. This is still supported in Version 2.0, to provide for backward compatibility and maximum performance.

However, the new deployment model in Version 2.0, which will be covered in detail in Chapter 19, requires only that any code files requiring compilation be placed in the \App_Code directory under the virtual root, and those files will be compiled automatically by the .NET Framework at runtime. This is all handled automatically by Visual Studio 2005.


The default code-behind file created by VS2005, listed in Example 15-3 (with one of the long lines wrapped for readability), is your basic Hello World type of program.

Example 15-3. Default web service code-behind fileApp_Code\Service.cs
 using System.Web; using System.Web.Services; using System.Web.Services.Protocols; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1,    EmitConformanceClaims = true)] public class Service : System.Web.Services.WebService {     [WebMethod]     public string HelloWorld(  ) {         return "Hello World";     } } 

The code-behind file contains a class, named after the web service file, which derives from the System.Web.Services.WebService class. This class has two attributes, WebService and WebServiceBinding , both of which will be described shortly.

You can rename a web service file in the Solution Explorer in VS2005 (just as you can rename a web page file) using the same techniques as in Windows Explorer: right-click on the file and select Rename, or highlight the file and press F2. Unlike web pages, renaming the .asmx will not automatically rename the code-behind file, nor will it rename the WebService class or change the Class attribute of the WebService directive.


Within the class Service , there is a boilerplate method called HelloWorld , which returns a string. This method is decorated with the WebMethod attribute, which identifies this method as available to consuming applications. The WebMethod attribute will be covered in detail shortly.

This boilerplate code comprises a fully functional, if limited, web service. You can see this by pressing F5 to run the web service app, which will produce a standard test page, similar to one shown in Figure 15-2.

To complete the simple web service example, replace the code within the class definition in Example 15-3 with the code highlighted in Example 15-4. This is exactly the same as the code within the class definition in the in-line example from Example 15-1.

Example 15-4. StockTickerSimple web service code-behind fileApp_Code\Service.cs
 using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System;      //  necessary for String class [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1,    EmitConformanceClaims = true)] public class Service : System.Web.Services.WebService {  //  Construct and fill an array of stock symbols and prices.    //  Note: the stock prices are as of 5/1/05.    string[,] stocks =       {          {"MSFT","Microsoft","25.30"},          {"DELL","Dell Computers","34.83"},          {"HPQ","Hewlett Packard","20.47"},          {"YHOO","Yahoo!","34.50"},          {"GE","General Electric","36.20"},          {"IBM","International Business Machine","76.38"},          {"GM","General Motors","26.68"},          {"F","Ford Motor Company","9.11"}       };    [WebMethod]    public double GetPrice(string StockSymbol)    //  Given a stock symbol, return the price.    {       //  Iterate through the array, looking for the symbol.       for (int i = 0; i < stocks.GetLength(0); i++)       {          //  Do a case-insensitive string compare.          if (String.Compare(StockSymbol, stocks[i, 0], true) == 0)             return Convert.ToDouble(stocks[i, 2]);       }       return 0;    }    [WebMethod]    public string GetName(string StockSymbol)    //  Given a stock symbol, return the name.    {       //  Iterate through the array, looking for the symbol.       for (int i = 0; i < stocks.GetLength(0); i++)       {          //  Do a case-insensitive string compare.          if (String.Compare(StockSymbol, stocks[i, 0], true) == 0)             return stocks[i, 1];       }       return "Symbol not found.";    }  } 

Running the web service app will again produce a standard web service test page, as shown in Figure 15-2.

In the following sections, you will learn about the WebService directive and various attributes used in Examples 15-3 and 15-4, as well as all the other attributes available.

Before proceeding, copy the previous example, StockTickerSimple , to a new web service called StockTickerComplete . In each of the next sections, you will add more features to the code listed in Example 15-4, eventually ending up with StockTickerComplete . At the end of this series of sections, the complete source code for StockTickerComplete is listed in Example 15-18.




Programming ASP. NET
Programming ASP.NET 3.5
ISBN: 0596529562
EAN: 2147483647
Year: 2003
Pages: 173

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