Tải bản đầy đủ (.pdf) (10 trang)

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

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (167.83 KB, 10 trang )

Evjen c28.tex V2 - 01/28/2008 3:52pm Page 1323
Chapter 28: Using Business Objects
interoperability for the unmanaged code to reference the managed code. Figure 28-15 illustrates using
private assemblies.
MyDotNet.dllMyApp.exe
C:\Program Files\First Application Location\
MyDotNet.dllMyApp.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) (Managed Code)
(Unmanaged Code)
Figure 28-16
As with private assemblies, the .NET component and the consuming unmanaged code are the only
requirements for deployment — besides the need to register the interop assembly using
regasm.exe
.
1323
Evjen c28.tex V2 - 01/28/2008 3:52pm Page 1324
Chapter 28: Using Business Objects
Summary


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
Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1325
Building and Consuming
Services
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
systems. There probably will not be a day when everything resides on a single platform where all
the data moves seamlessly from one server to another. For that reason, these various systems must
be able to talk to one another. If disparate systems can communicate easily, moving unique datasets
around the enterprise becomes a simple process — alleviating the need for replication systems and
data stores.
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 Ob ject 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 Com ponent 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 e asy
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: " /><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi=" />xmlns:xsd=" />xmlns:soap=" />1326
Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1327
Chapter 29: Building and Consuming Services
<soap:Body>
<HelloWorld xmlns=" />
</soap:Body>
</soap:Envelope>
The request is sent to the Web service to invoke the
HelloWorld
WebMethod (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=" />xmlns:xsd=" />xmlns:soap=" /><soap:Body>
<HelloWorldResponse xmlns=" /><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 fe w files you can use to get started. In the Solution Explorer of Visual Studio
(see Figure 29-2) is a single XML Web service named
Service.asmx
; its code-behind file,
Service.vb
or
Service.cs
, is located in the
App_Code
folder.
1327
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 the
Service.asmx
file. All ASP.NET Web service files use the
.asmx
file extension instead of
the
.aspx

extension used by t ypical ASP.NET pages.
The WebService Page Directive
Open the
Service.asmx
file in Visual Studio, and you see that the file contains only the
WebService
page
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
Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1329
Chapter 29: Building and Consuming Services
You use the
@WebService
directive instead of the
@Page
directive.
The simple
WebService
directive 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. The
CodeBehind
attribute 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 the
App_Code
folder,
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 either
True
or
False
.Ifthe
Debug
attribute is set to
True
,the
XML Web service is compiled with debug symbols in place; setting the v alue to
False
ensures
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 the

WebService.vb
or
WebService.cs
file — the code-behind file for the XML Web. By
default, a structure of code is already in place in the
WebService.vb
or
WebService.cs
file, 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:=" _
<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#
using System;

using System.Linq;
Continued
1329
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 = " />[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
the
System.Linq
and
System.Xml.Linq
namespaces are now included in the C# solution. In addi-

tion, the other change in this version is the inclusion of the commented
System.Web.Script.Services
.ScriptService
object 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, the
System.Web.Services
.Protocols
namespace is included by default. T herefore, 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 the
Service.asmx
file 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
Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1331
Chapter 29: Building and Consuming Services
Imports System.Data
Imports System.Data.SqlClient
<WebService(Namespace := " _
<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 = " />[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");
return myDataSet;
}
}
1331
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 the
WebService
attribute placed before the class declaration. Here is an example:
<WebService(Namespace := " />>
_
The
WebService
attribute can take a few properties. By default, the
WebService

attribute is used in your
Web service along with the
Namespace
property, which has an initial value of
/>.
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, the
Namespace
value
was changed to
www.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 the
WebService
attribute differently. Visual
Basic 2008 uses a colon and an equal sign to set the property:
Namespace:=" />C# uses just an equal sign to assign the properties within the
WebService
attribute values:
Namespace=" />Other possible
WebService
properties include
Name
and
Description
.
Name
enables 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).
Description
allows 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-
vice
attribute contains more than a single property, separate the properties using a comma. Here’s an
example:
<
WebService(Namespace:=" Name:="GetCustomers")> _
The WebMethod Attribute
In Listing 29-5, the class called
Customers
has only a single
WebMethod
.A
WebService
class can contain
any number of
WebMethod
s, or a mixture of standard methods along with methods that are enabled to
be
WebMethod
s 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 the
WebMethod
attribute.
As with the
WebService

attribute,
WebMethod
can also contain some properties, which are described in
the following list:

BufferResponse
:When
BufferResponse
is set to
True
, the response from the XML Web service
is held in memory and sent as a complete package. If it is set to
False
, 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 is
0
, which means that caching is disabled. Putting an XML Web ser-
vice’s response in the cache increases the Web service’s performance.
1332

×