Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#

.pdf
Скачиваний:
127
Добавлен:
12.02.2016
Размер:
7.64 Mб
Скачать

Relatively speaking, SOAP is still a young technology, and although it has been submitted to the W3C as a note, the specification has not made it through the W3C's standardization process as of yet. Rest assured, though, that the major vendors driving and implementing SOAP will keep pace with any changes that occur through the standards process and hopefully be able to insulate developers from the subtle changes that may occur.

Chapter 25: Building a Web Service

Overview

In this chapter, you will learn how to build a simple Web service using Visual Basic .NET and C#. We will go step by step through the process of creating a Web service that converts given temperatures between Fahrenheit, Celsius, Kelvin, and Rankine. Along the way, this chapter describes some of the implementation details and options available to you related to building Web services.

The Temperature Conversion Web Service

Before we begin building your first Web service, let's take a moment to briefly describe the service we intend to build. The first thing you will notice when you begin building this Web service is its simplicity. This has been done deliberately in order to focus more on the big picture of the various architectural elements of ASP.NET Web services than the details of the algorithm implemented by the code.

With this in mind, we will be building a simple, but useful Web service that converts temperature values between various numeric units.

The temperature conversion Web service will convert specified temperature values from Fahrenheit or Celsius to any one of Fahrenheit, Celsius, Kelvin, or Rankine. Each of these unit conversions is defined by a well-known arithmetic formula that can be easily represented in any programming language and does not require a lot of code.

Temperature conversion formulas

Table 25-1 shows the conversions that will be supported by the service and the corresponding formulas used to perform the conversion.

Table 25-1: Temperature conversion formulas

From/To

 

Fahrenheit

 

Celsius

 

Kelvin

 

Rankine

 

 

(F)

 

(C)

 

(K)

 

(R)

 

 

 

 

 

 

 

 

 

Celsius

 

((C * 9) / 5)

 

N/A

 

C +

 

F +

 

 

+ 32

 

 

 

273.15

 

459.67

 

 

 

 

 

 

 

 

 

Fahrenheit

 

N/A

 

((F - 32)

 

C +

 

F +

 

 

 

 

* 5) / 9

 

273.15

 

459.67

As you can see from the table, some of the conversions are specified assuming an initial conversion to another unit. For example, to convert a Celsius temperature to Rankine, the temperature value is first converted to Fahrenheit and then the remaining conversion rules are applied.

Finally, in keeping with the goal of code simplicity and brevity, the service will only support temperature conversions from Celsius or Fahrenheit to any of the other applicable units.

Method description

The temperature conversion Web service will support a single method named CTemp, which is modeled along the lines of the classic Visual Basic type conversion functions such as CBool, CLng, CDbl, and so forth. The obvious difference, of course, being that we are converting to other numeric units instead of converting to other data types.

Method arguments

The temperature conversion method will accept three arguments, summarized in Table 25-2.

Table 25-2: Temperature conversion method arguments

Argument Name

 

Data

 

Comments

 

 

Type

 

 

 

 

 

 

 

Temperature

 

Decimal

 

Any

 

 

 

 

 

 

 

numeric

 

 

 

 

value that

 

 

 

 

can be

 

 

 

 

specified by

 

 

 

 

the Decimal

 

 

 

 

data type

 

 

 

 

 

FromUnits

 

String

 

Valid

 

 

 

values are

 

 

 

 

 

 

 

 

C for

 

 

 

 

Celsius or

 

 

 

 

F for

 

 

 

 

Fahrenheit

 

 

 

 

 

ToUnits

 

String

 

Valid

 

 

 

values are

 

 

 

 

 

 

 

 

C for

 

 

 

 

Celsius, F

 

 

 

 

for

 

 

 

 

Fahrenheit,

 

 

 

 

K for

 

 

 

 

Kelvin, and

 

 

 

 

R for

 

 

 

 

Rankine

The method will return a Decimal result, which is the value of the conversion to the units specified in the ToUnits argument.

Method behavior

If the FromUnits and ToUnits arguments are the same, the method call will be successful and the Temperature argument will be returned unchanged. If the FromUnits and/or ToUnits do not specify valid unit identifiers, an ArgumentException exception will be thrown. Likewise, if the conversion specified by the FromUnits and ToUnits arguments is not supported, an ArgumentException exception will be thrown.

Creating the Web Service

Although the Visual Studio Integrated Development Environment (IDE) is a highly productive tool for building ASP.NET Web services, it is not a required tool. The .NET Framework itself comes bundled with the Visual Basic .NET and C# command-line compilers as well as other tools that you can use to build ASP.NET Web services.

ASP.NET Web services require a Web-addressable entry point file, an assembly that implements the functionality of the service, a Web Service Description (WSDL)

document an optional Discovery (DISCO) document, and an optional UDDI registration. In this chapter, you will learn how to create and properly format the files required to implement a Web service.

Web services built with the .NET Framework leverage the ASP.NET infrastructure, tools, and runtime. Of course, ASP.NET itself is built upon the foundation of the .NET Framework and the Common Language Runtime (CLR), providing all the benefits of these technologies to your Web service implementation.

These relationships are also important because they affect the physical structure of Web services on the .NET platform. The power of this model is quite evident as you begin to dissect the various pieces of a Web service on the .NET platform and gain an understanding of the features that are provided by these technologies. We will cover this as we work our way through the temperature conversion Web service implementation.

Getting started

Before you start working with the .NET Framework to build a Web service application, you must consider a few environmental factors related to your software and network configuration. These considerations will directly affect how you build, debug, and deploy your ASP.NET Web services.

ASP.NET Web service development requirements

The typical development environment for an ASP.NET Web service application usually consists of the following elements:

§A personal workstation with the.NET Framework SDK installed

§A development Web server that is configured to host and run a development (nonrelease) version of your Web service

§A production Web server that is configured to host the final run-time (release) version of your Web service

Often, the personal workstation and development Web server are combined on a single computer. This makes design, implementation, and debugging easier during the early development stages of your Web service. This is the development environment we will use in creating and building the CTemp Web service in this chapter.

Note If you intend to develop Web services using this configuration, you must be running Windows 2000 or later as your operating system.

If you prefer to develop Web services on a remote Web server, you should make sure that at least the runtime portion of the .NET Framework is installed and configured. With this configuration, you only need worry about copying your Web service implementation files to an appropriately configured virtual directory on the Web server.

Creating the Web service application

ASP.NET Web services are ASP.NET applications. Good practice dictates that ASP.NET applications have a Web server virtual directory defined for them. This allows more flexibility in configuring and customizing the Web service from a Web application perspective. Therefore, we will create a virtual directory for our CTemp Web service. Follow these steps:

1.Create a directory under the Web server root directory (typically inetpub/ wwwroot) named CTemp.

2.From the Microsoft Windows 2000 Start menu, choose Settings Control Panel.

3.Double-click the Administrative Tools icon.

4.Within the Administrative Tools group, double-click the Internet Services Manager icon. This will display the Internet Information

Services window.

5. In the Internet Information Services window, drill down to the default Web site on your local computer. You should see a list of virtual directories similar to that shown in Figure 25-1.

Figure 25-1: Internet Information Services window

6. From the Action menu, choose New Virtual Directory. This displays the Virtual Directory Creation Wizard, shown in Figure 25-2.

Figure 25-2: Virtual Directory Creation Wizard

7.Click the Next button to continue. This displays the Virtual Directory Alias panel.

8.Enter "CTemp" as the name for your virtual directory in the text box, as shown in Figure 25-3.

Figure 25-3: Virtual Directory Alias panel

9.Click the Next button to continue. This displays the Web Site Content Directory panel.

10.Enter in the text box the physical path to the CTemp directory you created earlier, as shown in Figure 25-4.

Figure 25-4: Web Site Content Directory panel

11.Click the Next button to continue. This displays the Access Permissions panel, shown in Figure 25-5.

Figure 25-5: Access Permissions panel

12.This panel controls the type of access permitted to users of files referenced by the virtual directory. You can enable one or a

combination of choices from the list by toggling the checkbox next to each option. The choices are as follows:

§Read: Enables read access to all files in the virtual directory

§Run scripts (such as ASP): Enables scripts to be executed from the virtual directory

§Execute (such as ISAPI applications or CGI): Enables executable files to be run from the virtual directory

§Write: Enables files to be uploaded to the virtual directory

§Browse: Enables files to be listed (or enumerated) in the virtual directory

Keep the default settings as shown in the permissions panel and click Next to continue. This displays the completion panel, shown in Figure 25-6.

Figure 25-6: Final step of the Virtual Directory Creation Wizard

13.Click the Finish button to complete the Virtual Directory Creation Wizard.

This process will create a Web server virtual directory named CTemp in the default Web site of your Web server.

Now that we have a directory into which to place our Web service application files, as well as a Web server virtual directory to govern how the Web server treats our application, we are ready to begin creating our first Web service.

Declaring the Web service

The first step in building the temperature conversion Web service outlined in the beginning of this chapter is to create the Web service entry point file (CTemp.asmx) in our application directory.

Note You can use any text editor to create the ASMX file, such as Windows Notepad.

The ASMX file serves as the Web-addressable entry point for your Web service and defines the class that implements the functionality of the Web service. The Web service declaration can specify that the class implementation is contained in the ASMX file itself (referred to as "inline") or that the class is contained in an external assembly. This latter type of declaration is also called a code behind file and is the type of Web service implementation created by Visual Studio.

Many of these files are optional. A minimal ASP.NET Web service only requires the ASMX file.

To declare a Web service with an inline implementation class, add an ASP.NET WebService directive at the top of the CTemp.asmx file, specifying the class implementing the Web Service and the programming language used for the implementation code. The following Web service declaration illustrates how this is done.

VB.NET:

<%@ WebService Language="VB" Class="TempConverter" %>

C#:

<%@ WebService Language="C#" Class="TempConverter" %>

To declare a Web service with an implementation that resides in a code behind file, add an ASP.NET WebService directive at the top of the CTemp.asmx file, specifying the class implementing the Web Service, the programming language used in the implementation, and, optionally, the assembly containing the implementation or the name of the code behind file. The following Web service declaration shows how this is done.

VB.NET:

<%@ WebService Language="VB" Codebehind="CTemp.vb"

Class="TempConverter" %>

C#:

<%@ WebService Language="C#" Codebehind="CTemp.cs"

Class="TempConverter" %>

Note If you do not specify an assembly within the WebService directive, then ASP.NET searches through the list of assemblies in the \bin directory of the Web application hosting the Web Service.

For our CTemp Web service, we will specify an inline implementation class. We will put all of this together (the declaration and the implementation class) in the next section. When you have finished building and testing your Web service, features of the .NET Framework make it easy to deploy your Web service to a production Web server. We will discuss this in more detail in Chapter 26, "Deploying and Publishing Web Services." Lastly, the complete path to your new Web service is http://localhost/CTemp/CTemp.asmx . This is the path that consumers of your Web service will use when calling your service (at least while it is under development).

Web service files

The simplest of ASP.NET Web services can be built using only an ASMX file in a Web application directory. However, more sophisticated and flexible Web services can be built by leveraging features of ASP.NET and the .NET Framework. In this case, you will need to include additional files in the application folder of your Web service implementation. Table 25-3 lists the various files that may be used by an ASP.NET Web service, along with their purpose.

Tip

Table 25-3: ASP.NET Web service files

Project File

Service name.asmx

Description

Serves as the Webaccessible entry point for the Web service. It contains the

Table 25-3: ASP.NET Web service files

Project File

Service name.asmx.vb or

Service name.asmx.cs

Web.config

Global.asax

Global.asax.vb

Description

Web service processing directive, which declares information about the implementat ion of the Web service.

Contains the code behind class that implements the functionality of the Web service. This file is referenced by the

Service name.asmx file in its Web service processing directive, if code behind is used.

Contains ASP.NET application configuratio n information for the Web service.

Responsible for handling ASP.NET applicationlevel events.

Contains the code behind class that handles the ASP.NET applicationlevel events. This file is referenced by the Global.asax

Table 25-3: ASP.NET Web service files

Project File

Service name.vsdisco

Bin\service name.dll

Description

file in its ASP.NET application directive, if code behind is used.

Contains the links (URLs) to the discovery (DISCO) file information that is available for the Web service.

The assembly package for the class(es) that implements the functionality of the Web service. This is the location of the compiled version of the Web service code behind file.

Implementing the Web service

We are now ready to write the code that will implement our Web service. Recall that in the last section we decided to use an embedded class declaration and implementation. Thus, we will be adding our implementation code to the CTemp.asmx file. This is very much like the technique used to code ASP.NET pages.

First, let's begin by adding the Web service declaration and class definition in the CTemp.asmx file as follows.

VB.NET:

<%@ WebService Language="VB" Class="TempConverter" %>

Imports System

Imports System.Web.Services

Public Class TempConverter

...

End Class

C#:

<%@ WebService Language="C#" Class="TempConverter" %>

using System;

using System.Web.Services;

public class TempConverter : WebService{

...

}

In this code, we have added the ASP.NET WebService directive that declares the Web service, and the class definition that declares the class containing our Web service implementation code.

The WebService directive specifies the language used to implement the Web service as well as the name of the class containing the functionality of the Web service. These two pieces of information give ASP.NET essential information that it needs to identify the Web service implementation.

The class definition, as you can see, is a normal class declaration. This is one of the great features of ASP.NET Web services — writing code for Web services is essentially like writing traditional object-oriented code using the built-in support provided by the host language (in this case, VB.NET or C#).

Lastly, note the references to the System and System.Web.Services namespaces. The System namespace enables us to use exceptions in our method implementation, and the System.Web.Services namespace, of course, provides us access to the Web services features of ASP.NET.

The WebService attribute

The WebService attribute is an optional attribute that can be added to the Web service class declaration to configure various properties for the class. The WebService attribute can be added to the front of the class declaration as follows:

<WebService()> Public Class TempConverter

Table 25-4 lists the properties that you can add to the WebService attribute.

Table 25-4: WebService attribute properties

Property Name

Description

Namespace

Description

Provides a brief description of the functionality of the Web service as a whole.

Used to provide a unique XML namespace for the WSDL document that describes the capabilities of the Web service.

Соседние файлы в папке c#