1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional ASP.NET 3.5 in C# and Visual Basic Part 137 ppt

10 278 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 167,83 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

This chapter looks at building XML Web services and how you can consume XML Web service interfaces and integrate them into your ASP.NET applications.. An example SOAP request from the cl

Trang 1

Chapter 28: Using Business Objects

interoperability for the unmanaged code to reference the managed code Figure 28-15 illustrates using

private assemblies

MyDotNet.dll MyApp.exe

C:\Program Files\First Application Location\

MyDotNet.dll MyApp.exe

C:\Program Files\Second Application Location\

(Unmanaged Code) (Managed Code)

(Unmanaged Code) (Managed Code)

Figure 28-15

Public Assemblies

The use of a public assembly is illustrated in Figure 28-16 This scenario involves installing the NET

component into the Global Assembly Cache (GAC)

MyApp.exe C:\Program Files\First Application Location\

YourApp.exe C:\Program Files\Second Application Location\

MyDotNet.dll Global Assembly Cache (GAC)

(Unmanaged Code)

Figure 28-16

As with private assemblies, the NET component and the consuming unmanaged code are the only

Trang 2

Evjen c28.tex V2 - 01/28/2008 3:52pm Page 1324

Chapter 28: Using Business Objects

Summar y

When NET was introduced, there was some initial concern about existing ActiveX controls and their

place in Microsoft’s vision for the future of component development Immediately, Microsoft stepped up

to the bat and offered the robust and solid NET Interop functionality to provide a means to communicate

not only from NET managed code to COM unmanaged code, but also from COM unmanaged code

to NET managed code The latter was an unexpected, but welcome, feature for many Visual Basic 6

developers and future NET component builders

This layer of interoperability has given Microsoft the position to push NET component development as a

solution for not only newly created applications, but also applications that are currently in development

and ones that have already been rolled out and are now in the maintenance phase

Interoperability has given NET developers a means to gradually update applications without rewriting

them entirely, and it has given them a way to start new NET projects without having to wait for all the

supporting components to be developed in NET

1324

Trang 3

Building and Consuming

Ser vices

When the NET Framework 1.0 was first introduced, much of the hype around its release was

focused on XML Web services In fact, Microsoft advertised that the main purpose of the newly

released NET Framework 1.0 was to enable developers to build and consume XML Web services

with ease Unfortunately, the new Web services model was slow to be accepted by the development

community because it was so radically different from those that came before Decision makers in

the development community regarded this new Web services model with a cautious eye

Since then, Microsoft has stopped trumpeting that NET is all about Web services and instead has

really expanded the power of NET and its relation to applications built within the enterprise Still,

the members of the IT community continued to look long and hard at the Web services model

(Microsoft is no longer alone in hyping this new technology), examining how it could help them

with their current issues and problems

This chapter looks at building XML Web services and how you can consume XML Web service

interfaces and integrate them into your ASP.NET applications It begins with the foundations of

XML Web services in the NET world by examining some of the underlying technologies such as

SOAP, WSDL, and more

Communication Between Disparate Systems

It is a diverse world In a major enterprise, very rarely do you find that the entire organization

and its data repositories reside on a single vendor’s platform In most instances, organizations are

made up of a patchwork of systems — some based on Unix, some on Microsoft, and some on other

Trang 4

Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1326

Chapter 29: Building and Consuming Services

When XML (eXtensible Markup Language) was introduced, it became clear that the markup language

would be the structure to bring the necessary integration into the enterprise XML’s power comes from

the fact that it can be used regardless of the platform, language, or data store of the system using it to

expose DataSets

XML has its roots in the Standard Generalized Markup Language (SGML), which was created in 1986

Because SGML was so complex, something a bit simpler was needed — thus the birth of XML

XML is considered ideal for data representation purposes because it enables developers to structure XML

documents as they see fit For this reason, it is also a bit chaotic Sending self-structured XML documents

between dissimilar systems does not make a lot of sense — you would have to custom build the exposure

and consumption models for each communication pair

Vendors and the industry as a whole soon realized that XML needed a specific structure that put some

rules in place to clarify communication The rules defining XML structure make the communication

between the disparate systems just that much easier Tool vendors can now automate the

communi-cation process, as well as provide for the automation of the possible creation of all the components of

applications using the communication protocol

The industry settled on using SOAP (Simple Object Access Protocol) to make the standard XML structure

work Previous attempts to solve the communication problem that arose included component

tech-nologies such as Distributed Component Object Model (DCOM), Remote Method Invocation (RMI),

Common Object Request Broker Architecture (CORBA), and Internet Inter-ORB Protocol (IIOP) These

first efforts failed because each of these technologies was either driven by a single vendor or (worse yet)

very vendor-specific It was, therefore, impossible to implement them across the entire industry

SOAP enables you to expose and consume complex data structures, which can include items such as

DataSets, or just tables of data that have all their relations in place SOAP is relatively simple and easy

to understand Like ASP.NET, XML Web services are also primarily engineered to work over HTTP The

DataSets you send or consume can flow over the same Internet wires (HTTP), thereby bypassing many

firewalls (as they move through port 80)

So what is actually going across the wire? ASP.NET Web services generally use SOAP over HTTP using

the HTTP Post protocol An example SOAP request (from the client to the Web service residing on a Web

server) takes the structure shown in Listing 29-1

Listing 29-1: A SOAP request

POST /MyWebService/Service.asmx HTTP/1.1

Host: www.wrox.com

Content-Type: text/xml; charset=utf-8

Content-Length: 19

SOAPAction: "http://tempuri.org/HelloWorld"

<?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/">

1326

Trang 5

Chapter 29: Building and Consuming Services

<soap:Body>

<HelloWorld xmlns="http://tempuri.org/" />

</soap:Body>

</soap:Envelope>

The request is sent to the Web service to invoke theHelloWorldWebMethod (WebMethods are discussed later in this chapter) The SOAP response from the Web service is shown in Listing 29-2

Listing 29-2: A SOAP response

HTTP/1.1 200 OK

Content-Type: text/xml; charset=utf-8

Content-Length: 14

<?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>

<HelloWorldResponse xmlns="http://tempuri.org/">

<HelloWorldResult>Hello World</HelloWorldResult>

</HelloWorldResponse>

</soap:Body>

</soap:Envelope>

In the examples from Listings 29-1 and 29-2, you can see that what is contained in this message is an XML file In addition to the normal XML declaration of the<xml>node, you see a structure of XML that is the SOAP message A SOAP message uses a root node of<soap:Envelope>that contains the<soap:Body>

or the body of the SOAP message Other elements that can be contained in the SOAP message include a SOAP header,<soap:Header>, and a SOAP fault —<soap:Fault>

For more information about the structure of a SOAP message, be sure to check out the SOAP

specifica-tions You can find them at the W3 C Web site,www.w3.org/tr/soap.

Building a Simple XML Web Ser vice

Building an XML Web service means that you are interested in exposing some information or logic to

another entity either within your organization, to a partner, or to your customers In a more granular

sense, building a Web service means that you, as a developer, simply make one or more methods from a class you create that is enabled for SOAP communication

You can use Visual Studio 2008 to build an XML Web service The first step is to actually create a new

Web site by selecting File➪New➪Web Site from the IDE menu The New Web Site dialog opens Select ASP.NET Web Service, as shown in Figure 29-1

Visual Studio creates a few files you can use to get started In the Solution Explorer of Visual Studio

(see Figure 29-2) is a single XML Web service namedService.asmx; its code-behind file,Service.vbor

Service.cs, is located in theApp_Codefolder

Trang 6

Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1328

Chapter 29: Building and Consuming Services

Figure 29-1

Figure 29-2

Check out theService.asmxfile All ASP.NET Web service files use the.asmxfile extension instead of

the.aspxextension used by typical ASP.NET pages

The WebService Page Directive

Open theService.asmxfile in Visual Studio, and you see that the file contains only theWebServicepage

directive, as illustrated in Listing 29-3

Listing 29-3: Contents of the Service.asmx file

<%@ WebService Language="VB" CodeBehind="~/App_Code/Service.vb"

Class="Service" %>

1328

Trang 7

Chapter 29: Building and Consuming Services

You use the@WebServicedirective instead of the@Pagedirective

The simpleWebServicedirective has only four possible attributes The following list explains these

attributes:

❑ Class: Required It specifies the class used to define the methods and data types visible to the

XML Web service clients

❑ CodeBehind: Required only when you are working with an XML Web service file using the

code-behind model It enables you to work with Web services in two separate and more manage-able pieces instead of a single file TheCodeBehindattribute takes a string value that represents the physical location of the second piece of the Web service — the class file containing all the

Web service logic In ASP.NET, it is best to place the code-behind files in theApp_Codefolder,

starting with the default Web service created by Visual Studio when you initially opened the

Web service project

❑ Debug: Optional It takes a setting of eitherTrueorFalse If theDebugattribute is set toTrue, the XML Web service is compiled with debug symbols in place; setting the value toFalseensures

that the Web service is compiled without the debug symbols in place

❑ Language: Required It specifies the language that is used for the Web service

Looking at the Base Web Service Class File

Now look at theWebService.vborWebService.csfile — the code-behind file for the XML Web By

default, a structure of code is already in place in theWebService.vborWebService.csfile, as shown in Listing 29-4

Listing 29-4: Default code structure provided by Visual Studio for your Web service

VB

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols

’ To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment

’ the following line

’ <System.Web.Script.Services.ScriptService()> _

<WebService(Namespace:="http://tempuri.org/")> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _

Public Class Service

Inherits System.Web.Services.WebService

<WebMethod()> _

Public Function HelloWorld() As String

Return "Hello World"

End Function

End Class

C#

Trang 8

Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1330

Chapter 29: Building and Consuming Services

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Xml.Linq;

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

// To allow this Web Service to be called from script, using ASP.NET AJAX,

// uncomment the following line

// [System.Web.Script.Services.ScriptService]

public class Service : System.Web.Services.WebService

{

public Service () {

//Uncomment the following line if using designed components //InitializeComponent();

}

[WebMethod]

public string HelloWorld() {

return "Hello World";

}

}

Some minor changes to the structure have been made since the NET 3.5 release You will notice that

theSystem.LinqandSystem.Xml.Linqnamespaces are now included in the C# solution In

addi-tion, the other change in this version is the inclusion of the commentedSystem.Web.Script.Services

.ScriptServiceobject to work with ASP.NET AJAX scripts To make use of this attribute, you simply

uncomment the item

Since the NET 1.0/1.1 days, there also have been some big changes First, theSystem.Web.Services

.Protocolsnamespace is included by default Therefore, in working with SOAP headers and other

capabilities provided via this namespace, you do not need to worry about including it

The other addition is the new<WebServiceBinding>attribute It builds the XML Web service responses

that conform to the WS-I Basic Profile 1.0 release (found at

www.ws-i.org/Profiles/BasicProfile-1.0-2004-04-16.html)

Besides these minor changes, very little has changed in this basic Hello World structure.

Exposing Custom Datasets as SOAP

To build your own Web service example, delete theService.asmxfile and create a new file called

Cus-tomers.asmx This Web service will expose the Customers table from SQL Server Then jump into the

code shown in Listing 29-5

Listing 29-5: An XML Web service that exposes the Customers table from Northwind

VB

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols

1330

Trang 9

Chapter 29: Building and Consuming Services

Imports System.Data

Imports System.Data.SqlClient

<WebService(Namespace := "http://www.wrox.com/customers")> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

Public Class Customers

Inherits System.Web.Services.WebService

<WebMethod()> _

Public Function GetCustomers() As DataSet

Dim conn As SqlConnection

Dim myDataAdapter As SqlDataAdapter

Dim myDataSet As DataSet

Dim cmdString As String = "Select * From Customers"

conn = New SqlConnection("Server=localhost;uid=sa;pwd=;database=Northwind")

myDataAdapter = New SqlDataAdapter(cmdString, conn)

myDataSet = New DataSet()

myDataAdapter.Fill(myDataSet, "Customers")

Return myDataSet

End Function

End Class

C#

using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Data;

using System.Data.SqlClient;

[WebService(Namespace = "http://www.wrox.com/customers")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Customers : System.Web.Services.WebService

{

[WebMethod]

public DataSet GetCustomers() {

SqlConnection conn;

SqlDataAdapter myDataAdapter;

DataSet myDataSet;

string cmdString = "Select * From Customers";

conn = new SqlConnection("Server=localhost;uid=sa;pwd=;database=Northwind");

myDataAdapter = new SqlDataAdapter(cmdString, conn);

myDataSet = new DataSet();

myDataAdapter.Fill(myDataSet, "Customers");

Trang 10

Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1332

Chapter 29: Building and Consuming Services

The WebService Attribute

All Web services are encapsulated within a class The class is defined as a Web service by theWebService

attribute placed before the class declaration Here is an example:

<WebService(Namespace := "http://www.wrox.com/customers")> _

TheWebServiceattribute can take a few properties By default, theWebServiceattribute is used in your

Web service along with theNamespaceproperty, which has an initial value ofhttp://tempuri.org/

This is meant to be a temporary namespace and should be replaced with a more meaningful and original

name, such as the URL where you are hosting the XML Web service In the example, theNamespacevalue

was changed towww.wrox.com/customers Remember that it does not have to be an actual URL; it can

be any string value you want The idea is that it should be unique It is common practice is to use a URL

because a URL is always unique

Notice that the two languages define their properties within theWebServiceattribute differently Visual

Basic 2008 uses a colon and an equal sign to set the property:

Namespace:="http://www.wrox.com/customers"

C# uses just an equal sign to assign the properties within theWebServiceattribute values:

Namespace="http://www.wrox.com/customers"

Other possibleWebServiceproperties includeNameandDescription.Nameenables you to change how

the name of the Web service is presented to the developer via the ASP.NET test page (the test page is

discussed a little later in the chapter).Descriptionallows you to provide a textual description of the

Web service The description is also presented on the ASP.NET Web service test page If your

WebSer-viceattribute contains more than a single property, separate the properties using a comma Here’s an

example:

<WebService(Namespace:="http://www.wrox.com/customers", Name:="GetCustomers")> _

The WebMethod Attribute

In Listing 29-5, the class calledCustomershas only a singleWebMethod AWebServiceclass can contain

any number ofWebMethods, or a mixture of standard methods along with methods that are enabled to

beWebMethods via the use of the attribute preceding the method declaration The only methods that are

accessible across the HTTP wire are the ones to which you have applied theWebMethodattribute

As with theWebServiceattribute,WebMethodcan also contain some properties, which are described in

the following list:

❑ BufferResponse: WhenBufferResponseis set toTrue, the response from the XML Web service

is held in memory and sent as a complete package If it is set toFalse, the default setting, the

response is sent to the client as it is constructed on the server

❑ CacheDuration: Specifies the number of seconds that the response should be held in the system’s

cache The default setting is0, which means that caching is disabled Putting an XML Web

ser-vice’s response in the cache increases the Web serser-vice’s performance

1332

Ngày đăng: 05/07/2014, 19:20

TỪ KHÓA LIÊN QUAN