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

C# ПІДРУЧНИКИ / c# / Hungry Minds - C# Bible

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

 

 

Table 26-7: Font Class Properties

 

 

 

Property

 

Description

 

 

 

Unit

 

Gets the unit of measure for this Font object

 

 

 

Summary

GDI+ offers a robust array of classes that enable you to write any type of graphics support into your applications. This chapter presented an overview of the capabilities of GDI+, but you can do much more with the System.Drawing and System. Drawing.Drawing2D namespaces than can be covered in a single chapter.

To manipulate or create graphics using GDI+, you first need to create a Graphics object which gives you the surface with which you paint objects on. After your Graphics object is created, you then use pens, brushes, bitmaps, or fonts to render the type of image you are looking for.

Chapter 27: Building Web Services

In This Chapter

Web services are arguably the most exciting and innovative feature of Microsoft's .NET initiative, and they are likely to profoundly affect the way businesses interact using computer applications. So, what exactly is a Web service? From 10,000 feet, a Web service is simply a server-side component that can be invoked over the Internet. Such a server-side component would typically perform a core business service, such as user authentication, credit card validation, pricing a derivatives security, placing a purchase order for a stock, or pricing a same-day shipment. Obviously, the list of possible Web services is as varied as the list of possible business opportunities. Web services enable applications to invoke business services using a standards-based mechanism (using XML and HTTP), and as you will learn in this chapter, how this is realized represents a significant breakthrough in application interoperability. XML is the basic building block for many of the standards used when creating Web Services. If you are not familiar with XML, you can find a brief primer on it in this book's appendix.

In this chapter, you learn which XML-based standards govern defining and using of Web services, Then you create a Web service using Visual Studio .NET. Finally, you use this newly created Web service in a second Visual Studio .NET project.

Understanding How Web Services Work

Two optional technologies are involved in defining Web services: the discovery mechanism and the service description. These two technologies can be bypassed by using other means of communications; for example, if there is a dialogue (e.g., phone calls) between the developers of the Web service and the developers of the client that will be accessing the Web service.

The discovery mechanism uses an XML document on the server to enable client applications to detect that a Web service exists and to find the detailed description of that service. Initially, Microsoft was proposing to use DISCO (discovery of Web services) for this discovery mechanism, but UDDI (Universal Description, Discovery and Integration) has since become

the de facto standard for discovery. You can find out more about UDDI at http://www.uddi.org. The service description describes the inputs and outputs of the Web service. Service descriptions use the Web Service Description Language (WSDL) standard, described later in this chapter. UDDI (or DISCO, its now deprecated predecessor) and WSDL are essential building blocks that can be used to create precise documentation about how to invoke the Web service. And because these technologies are standardized, the descriptions are also readable by applications. However, after a client has been implemented, there may be no need to use the discovery mechanism or to refer to the service description. The use of these technologies is not essential to create or use Web services that are geared to a specific application.

Three technologies are involved during the actual invocation of a Web service: the wire protocol, the message format and the invocation mechanism. Only the former two are specified in the Web service standards. The wire protocol is the transport mechanism used to communicate between the client and the server. Typically, this is HTTP, the TCP/IP-based Internet protocol. The message format is the format used to invoke a Web service. A Web service can be invoked by using raw HTTP or by using an XML message in a specific format called Simple Object Access Protocol (SOAP). The third technology, which governs the way in which the server-side components gets invoked, is not specified by the Web service standards. That is an implementation detail left to the discretion of the implementer of the Web service. In other words, the programmer building the Web service chooses the technology used to call the business code on the server: a Visual Basic developer may use COM+ to invoke a COM object, a Java developer may use RMI to invoke a Java object, and so on.

The two sides of a Web service can be described as the creator (client) and the consumer (server). The creator develops the server-side component and exposes this service to the appropriate audience. For example, a financial institution develops a credit card validation system and exposes this to online vendors. Exposing a Web service means publishing the URL that users need to invoke the Web service. The consumer can use the exposed service by sending a SOAP request message to the published URL. Upon receiving the SOAP request message written in XML, the server-side component behind the Web service is invoked on the creator's server. The results from this invocation are formatted into a SOAP response message and are sent back to the service consumer. Figure 27-1 shows the parties involved in a Web service.

Figure 27-1: Web services have two sides: za consumer and a creator.

Web services use a set of standards to define how the interaction between client and server is realized. These standards define the transport mechanism to be used and both the format and

content of the interaction. At the Transport level, the ubiquitous HTTP Internet protocol is used. The server and client communicate with each other using XML messages. The content of these messages is also standardized and must conform to the rules of SOAP (more about these rules follows later in this chapter). The nature of the services available in a Web service can be described in an XML file whose content conforms to the rules of the Web Service Description Language (WSDL). Finally, a client can dynamically discover which Web Services are exposed on a site by retrieving the XML file whose content conforms to the rules of DISCO.

Note that no mention has been made yet about any company-specific technologies. Nowhere has there been any assumption about the operating system running on the client or the server, the programming language used to write the server-side component, or the mechanism used to invoke the server-side component. These choices are irrelevant to a Web service. A client written in C# running on Windows XP, for example, can invoke a Web service written in Java running on Sun Solaris. In fact, a client has no way of knowing what technologies are used to expose the Web service.

The implications of Web services are far-reaching. Microsoft jump-started component-based programming with the introduction of OLE controls (OCXs), a refinement of the groundbreaking concepts introduced by Visual Basic Controls (VBXs). OCXs are based on Microsoft's Component Object Model (COM), and work well. However, COM and its distributed counterpart, Distributed Component Object Model (DCOM), are limited in their reach. Aside from the Windows family of operating systems, there is limited support for COM/DCOM. In addition, although on the desktop the Windows family is widely used, on the server-side a greater variety of operating systems are in use. For example, several varieties of the UNIX operating system, such as Solaris and Linux, have a significant presence. Web services eliminate the need to choose which operating system runs on the server when integrating two Web-based applications. Using Web services, you can now assemble a Webbased application using components from other sites. For example, you could use a Web service from a credit card company to validate the credit card, a Web service from a shipping company to determine the shipping charge, and so on. This is the both the essence and the promise of Web services: the next generation of component-based programming for the next generation of distributed applications.

Web Services and Visual Studio .NET

If Web services are platform-independent, what does Microsoft hope to gain from them? The answer is simple: Microsoft has publicly stated that it will strive to make Windows the best operating system to host Web services, and Visual Studio .NET the best development environment to create Web services. Because this programming book is about C#, the focus of this discussion about Web services is on C# and its integrated development environment. In the hands-on section later in this chapter, you will be able to judge for yourself how flexible and easy to use the Visual Studio .NET development environment is.

Visual Studio .NET does a wonderful job of simplifying the creation and consumption of Web services. Much of the programmer-unfriendly stuff (creating all the XML-based documents, for example) happens automatically, without much effort on the programmer's side. All you have to do when programming is declare your intention to expose a piece of code as a Web service, and the tool does most of the work. In fact, the tool does such a fantastic job that you may never see any XML at all when building a Web service and a Web service consumer. In

fact, this is exactly what you do in this chapter. Before you begin, however, take a quick look at the concept that makes all this automation possible. It's called attribute-based programming.

Attribute-based programming is a powerful concept that enables Visual Studio .NET to automate a lot of programmer-unfriendly tasks (such as creating a WSDL document for a Web service). You simply mark a piece of code, such as a class or method, in a special way to denote what you intend to do with it. As a result of this, Visual Studio .NET generates the necessary files to implement your intention. A short example shows how this works in the context of transforming a class into a Web service.

Listing 27-1 illustrates how you might implement a simple game. Granted, this game isn't very fair (the player always loses), but this chapter is concerned with Web service programming, not game programming. Take a quick look at what's involved in turning this piece of code into a Web service and what Visual Studio .NET generates for you during this process. The main point of this exercise is to give you an idea of the amount of work involved when turning a piece of finished code into a Web service using Visual Studio .NET.

Listing 27-1: A Simple Game

namespace MyFirstWebService

{

public class GameWS

{

//SIMPLE GAME EXAMPLE

//The example game returns the string "Sorry, you

lose!"

// To test this game, press F5

public string Play(string opponentName)

{

return "Sorry " + opponentName + ", you lose!";

}

}

}

Your first step to turn this piece of code into a Web service is to save the code in a new file called GameWS.asmx. Then, perform the following four steps:

1.Add a header indicating three things: that the file contains a Web service, the language used, and the class that contains the implementation:

<%@ WebService Language="c#" Class="MyFirstWebService.GameWS" %>

2. Add a System.Web.Service directive just below the Web service header:

using System.Web.Services;

3.Mark the class as a Web service and choose the XML namespace associated with the Web service:

4.[WebService(Namespace="http://www.boutquin.com/GameWS/")]

public class GameWS : System.Web.Services.WebService

5.Mark the methods within the class as being accessible from the Web:

6.[WebMethod]

7.public string Play(string opponentName)

Listing 27-2 shows the final result. The comments have also been changed to reflect the changes made to the original code.

Listing 27-2: A Simple Game Exposed as a Web Service

<%@ WebService Language="c#" Class="MyFirstWebService.GameWS" %>

using System.Web.Services;

namespace MyFirstWebService

{

[WebService(Namespace="http://www.boutquin.com/GameWS/")] public class GameWS : System.Web.Services.WebService

{

//WEB SERVICE EXAMPLE

//The Play() method returns the string "Sorry, you

lose!"

// To test this web service, press F5 [WebMethod]

public string Play(string opponentName)

{

return "Sorry " + opponentName + ", you lose!";

}

}

}

When you build a Web services project in Visual Studio, a service description file that describes the Web service is automatically created. This file is an XML dialect called Web Service Description Language (WSDL). A WSDL file looks like the following:

<?xml version="1.0" encoding="UTF-8"?>

<methods href='http://www22.brinkster.com/boutquin/GameWS.asmx'> <method name='Play' href='Play'>

<request>

<param dt='string'>opponentName</param> </request>

<response dt='string'/> </method>

</methods>

The WSDL describes the functions that are exposed (the format shown is actually a simplification of the actual format, but the concept remains the same). You can call the service through a URL (www22.brinkster.com/boutquin/GameWS.asmx/ Play?opponentName=Pierre, in this case) or send a properly formatted XML message to the URL (via an HTTP post or get statement). Such an XML message would be a SOAP message like the following:

<?xml version="1.0" encoding="utf-8"?> <soap:Envelope

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

<soap:Body>

<Play xmlns="http://www.boutquin.com/GameWS/"> <opponentName>Pierre</opponentName>

</Play>

</soap:Body>

</soap:Envelope>

Invoking the service, either through the URL or by posting a SOAP message, results in an XML response such as the following:

<?xml version="1.0" encoding="UTF-8"?>

<string xmlns="http://www.boutquin.com/GameWS/">Sorry Pierre, you lose!</string>

The following sections examine the essentials of SOAP and WSDL, after which you dive into the details of Web service creation and invocation.

Understanding the Web Service Description Language (WSDL)

WSDL is the XML vocabulary used to describe Web services. This description includes information about how to access them. The .NET Framework takes care of generating these Web services for you, so you do not need to know much about WSDL to use Web services. To see what the WSDL for a service looks like, you can add ?wsdl to its URL and see the result in a XML-capable browser; for example, www22.brinkster.com/boutquin/GameWS.asmx?wsdl.

This section briefly describes this XML vocabulary.

WSDL uses a default namespace, xmlns="http://schemas.xmlsoap.org/wsdl/". It uses a root element called definitions and contains several sections. One of these sections is the service section, where - you guessed it! - services are described. The following snippet is a skeleton of a WSDL file. An actual WSDL file uses several namespace declarations, which are omitted here for simplicity's sake:

<?xml version="1.0" encoding="UTF-8"?>

<definitions xmlns='http://schemas.xmlsoap.org/wsdl/'>

<service name="GameWS" >

<!-- Service is described here -->

</service>

</definitions>

The first attribute in a service description defines the location from which you can call the service. This is described in the address element inside a port element. (Element and attribute are XML terms, as you can learn in the appendix.) The following example illustrates the binding attribute:

<?xml version="1.0" encoding="UTF-8"?>

<definitions xmlns='http://schemas.xmlsoap.org/wsdl/'>

<service name="GameWS" >

<port name="GameWSSoap" binding="s0:GameWSSoap"> <soap:address

location="http://www22.brinkster.com/boutquin/GameWS.asmx" /> </port>

</service>

</definitions>

If a Web service is exposed through an HTTP post or get statement, its location is stored in an http:address element:

<port name="GameWSHttpPost" binding="s0:GameWSHttpPost">

<http:address location="http://www22.brinkster.com/boutquin/GameWS.asmx" />

</port>

Next, you need to define the input and output parameters. You accomplish this action through message elements. In such an element, you give each message a name; and within a message, you describe each parameter (name and data type):

<message name ="PlayInput" >

<part name="opponentName" element='xsd:string'/>

</message>

<message name ="PlayOutput" >

<part name='Result' type=''xsd:string"/>

</message>

You can then associate the messages with the port using a portType element. In the portType, you use the name you assigned to this port in the port element; and for each of the Web services, you create an operation tag containing an input and output element that use the message as the attribute:

<portType name="GameWSSoap"> <operation name="Play">

<input message="PlayInput" /> <output message="PlayOutput" />

</operation>

</portType>

Finally, the binding element describes the specifics relevant to the transport mechanism used. A SOAP binding, for example, needs to specify the SOAP action:

<binding name="GameWSSoap" type="s0:GameWSSoap"> <soap:binding

transport="http://schemas.xmlsoap.org/soap/http" style="document" />

<operation name="Play"> <soap:operation

soapAction="http://www.boutquin.com/GameWS/Play" style="document" />

<input>

<soap:body use="literal" /> </input>

<output>

<soap:body use="literal" /> </output>

</operation>

</binding>

Using Simple Object Access Protocol (SOAP)

SOAP is the XML dialect used by Web services. It specifies which server-side action you want to invoke to pass the information (that is, the parameters) to the Web service. SOAP also specifies how the information is returned from the Web service (both return values and exceptions).

SOAP messages follow a standard format: an outer envelope that identifies the message as being a SOAP message, a body section that contains the main payload, and an optional header section for additional information about the message. You can use the header section to pass information that is not per se part of the server-side invocation. You can, for example, pass the date and time of the request, or user authentication in this header. The body contains an element whose name matches the name of the server-side method being called. The children of this element are elements whose names match the names of the parameters:

<?xml version="1.0" encoding="utf-8"?> <soap:Envelope

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header>

<!-- Optional information goes here -->

</soap:Header>

<soap:Body>

<MethodName>

<Param1Name>value1</Param1Name>

<Param2Name>value2</Param2Name> <!-- etc. -->

</MethodName>

</soap:Body>

</soap:Envelope>

The same format is used to send back a response. The parameter names (here Param1Name and Param2Name) in the response are, of course, the output parameters; or "return" when the method only returns one value (e.g., <return>value</return>).

When errors occur, the error information is sent back in a fault section. The fault section is found in the SOAP body:

<soap:Fault>

<faultcode>x00</faultcode>

<faultstring>description<faultstring>

<runcode>Yes<runcode>

</soap:Fault>

Creating Web Services Using Visual Studio .NET

Creating (and, in the following section, accessing) a Web service using Visual Studio .NET is deceptively simple. You don't even need to be aware that XML is used.

The Web service you will build in this section will simply retrieve and display a list of books. This simulates the catalog function of a Web-based commerce site, although in reality you probably would want to introduce categories to avoid returning a huge list of books. Since the focus in this chapter is on what's required to build a Web service, the business aspect is being simplified.

The sample you build here uses one table and one stored procedure. The code to create this is shown in the following example (you may also want to put some sample data in the Books table):

CREATE TABLE [Books] (

[ISBN] [char] (14) NOT NULL , [Title] [varchar] (150) NOT NULL , [Price] [money] NOT NULL

)

GO

ALTER TABLE [dbo].[Books] WITH NOCHECK ADD CONSTRAINT [PK_Books] PRIMARY KEY CLUSTERED

(

[ISBN] ) ON [PRIMARY]

GO

CREATE PROCEDURE [pc_getBooks] AS

SELECT [ISBN], [Title], [Price]

FROM [Books] GO

Now you are ready to build a simple Web service that returns a list of books using the stored procedure:

1.Open Visual Studio .NET and select File New Project.

2.Select ASP.NET Web Service as the project type in the New Project dialog box.

3.Name the project BookSeller (see Figure 27-2).

Figure 27-2: A Web service is a separate project type.

4.Rename the Web service from Service1.asmx to Books.asmx.

5.Switch to Code view, by clicking the Books.asmx.cs tab, and change all occurrences of Service1 to Books (see Figure 27-3).

Figure 27-3: You can change the default service name to something more descriptive.

6.Change the using section to contain the following:

7.using System;

8.using System.Web.Services;

9.using System.Data;

10.using System.Data.OleDb;

11.Add the following methods and property to the Books class:

12.private static string oleDbConnectionString

13.{

14.get

15.{

16.// NOTE: Using the sa account in production

17.applications

18.// is, of course, a BAD, BAD practice. In addition,

19.leaving the

20.// password blank for the sa account is equally

21.inadmissible.

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