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

Professional ASP.NET 3.5 in C# and Visual Basic Part 138 docx

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 (572.06 KB, 10 trang )

Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1333
Chapter 29: Building and Consuming Services

Description
: Applies a text description to the
WebMethod
that appears on the
.aspx
test page of
the XML Web service.

EnableSession
: Setting
EnableSession
to
True
enables session state for a particular
WebMethod
.
The default setting is
False
.

MessageName
: Applies a unique name to the
WebMethod
. This is a required step if you are work-
ing with overloaded
WebMethod
s (discussed later in the chapter).


TransactionOption
: Specifies the transactional support for the
WebMethod
. The default setting
is
Disabled
.Ifthe
WebMethod
is the root object that initiated the transaction, the Web service can
participate in a transaction with another
WebMethod
that requires a transaction. Other possible
values include
NotSupported
,
Supported
,
Required
,and
RequiresNew
.
The XML Web Service Interface
The Customers Web service from Listing 29-5 has only a single
WebMethod
that returns a DataSet contain-
ing the complete Customers table from the SQL Server Northwind database.
Running
Customers.asmx
in the browser pulls up the ASP.NET Web service test page. This visual inter-
face to your Web service is really meant either for testing purposes or as a reference page for developers

interested in consuming the Web services you expose. The page generated for the Customers Web service
is shown in Figure 29-3.
Figure 29-3
The interface shows the name of the Web service in the blue bar (the dark bar in this black and white
image) at the top of the page. By default, the name of the class is used unless you changed the value
through the
Description
property of the
WebService
attribute, as defined earlier. A bulleted list of
links to the entire Web service’s
WebMethod
s is displayed. In this example, there is only one
WebMethod
:
GetCustomers
.
1333
Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1334
Chapter 29: Building and Consuming Services
A link to the Web service’s Web Services Description Language (WSDL) document is also available (the
link is titled Service Description in the figure). The WSDL file is the actual interface with the Customers
Web service. The XML document (shown in Figure 29-4) is not really meant for human consumption; it is
designed to work with tools such as Visual Studio, informing the tool what the Web service requires to be
consumed. Each Web service requires a request that must have parameters of a specific type. When the
request is made, the Web service response comes back with a specific set of data defined using specific
data types. Everything you need for the request and a listing of exactly what you are getting back in a
response (if you are the consumer) is described in the WSDL document.
Figure 29-4
Clicking the

GetCustomers
link gives you a new page, shown in Figure 29-5, that not only describes the
WebMethod
in more detail, but it also allows you to test the
WebMethod
directly in the browser.
At the top of the page is the name of the XML Web service (
Customers
); below that is the name of this
particular
WebMethod
(
GetCustomers
). The page shows you the structure of the SOAP messages that are
required to consume the
WebMethod
, as well as the structure the SOAP message take s for the response.
1334
Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1335
Chapter 29: Building and Consuming Services
Below t he SOAP examples is an example of consuming the XML Web service using HTTP Post (with
name/value pairs). It is possible t o use this method of consumption instead of using SOAP. (This is
discussed later in the ‘‘Transport Protocols for Web Services’’ section of this chapter.)
Figure 29-5
You can test the
WebMethod
directly from the page. In the Test section, you find a form. If the
WebMethod
you are calling requires an input of some parameters to get a response, you see some text
boxes included so you can provide the parameters before clicking the Invoke button. If the

WebMethod
you are calling does not require any parameters, you see only the Invoke button and nothing more.
Clicking Invoke is ac tually sending a SOAP request to the Web service, causing a new browser instance
with the result to appear, as illustrated in Figure 29-6.
Now that everything is in place to expose the XML Web service, you can consume it in an ASP.NET
application.
1335
Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1336
Chapter 29: Building and Consuming Services
Figure 29-6
Consuming a Simple XML Web Ser vice
So far, you have seen only half of the XML Web service story. Exposing data and logic as SOAP to dis-
parate systems across the enterprise or across the world is a simple task using .NET and particularly
ASP.NET. The other half of the story is the actual consumption of an XML Web service into an ASP.NET
application.
You are not limited t o consuming XML Web services only into ASP.NET applications; but because this
is an ASP.NET book, it focuses on that aspect of the consumption process. Consuming XML Web ser-
vices into other types of applications is not that difficult and, in fact, is rather similar to how you would
consume them using
ASP.NET.
Remember that the Web services you come across can be consumed in
Windows Forms, mobile applications, databases, and more. You can even consume XML Web services
with other Web services so you can have a single Web service made up of what is basically an aggregate
of other Web services.
Adding a Web Reference
To consume the Customers Web service that you created earlier in this chapter, create a new ASP.NET
Web site called
CustomerConsumer
. The first step in consuming an X ML Web service in an ASP.NET
application is to make a reference to the remote object — the Web service. This is done by right-clicking

1336
Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1337
Chapter 29: Building and Consuming Services
on the root node of your project from within the Solution Explorer of Visual Studio and selecting Add
Web Reference. This pulls up the Add Web Reference dialog box, shown in Figure 29-7.
Figure 29-7
The Add Web Reference dialog box enables you to point to a particular
.asmx
file to make a reference to
it. Understand that the Add Web Reference dialog box is really looking for WSDL files. Microsoft’s XML
Web services automatically generate WSDL files based on the
.asmx
files themselves. To pull up the
WSDL file in the browser, simply type in the URL of your Web service’s
.asmx
file and add a
?WSDL
at
the end of the string. For example, you might have the following construction (this is not an actual web
service, but simply an example):
/>Because the Add Web Reference dialog box automatically finds where the WSDL file is for any Microsoft-
based XML Web service, you should simply type in the URL of the actual WSDL file for any non–
Microsoft-based XML Web service.
If you are using Microsoft’s Visual Studio and its built-in Web server instead of IIS, you will be required
to also interject the port number the Web server is using into the URL. In this case, your URL would be
structured similar to
http://localhost:5444/MyWebService/Customers.asmx?WSDL
.
In the Add Web Reference dialog box, change the reference from the default name to something a little
more meaningful. If you are working on a single machine, the Web reference might have the name of

localhost
; if you are actually working with a remote Web service, the name is the inverse of the URL,
1337
Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1338
Chapter 29: Building and Consuming Services
such as
com.wrox.www
. In either case, it is best to rename it so that the name makes a little more sense and
is easy to use within your application. In the example here, the Web reference is renamed
WroxCustomers
.
Clicking the Add Reference button causes Visual Studio to make an actual reference to the Web service
from the
web.config
file of your application (shown in Figure 29-8). You may find some additional files
under the
App_WebReferences
folder — such as a copy of the Web service’s WSDL file.
Figure 29-8
Your consuming application’s
web.config
file contains the reference to the Web service in its
<
appSettings
> section. The addition is shown in Listing 29-6.
Listing 29-6: Changes to the web.config file after making a reference to the Web
service
<configuration xmlns=" /><appSettings>
<add key="WroxCustomers.Customers"
value=" /></appSettings>

</configuration>
You can see that t he
WroxCustomers
reference has been made along with the name of the Web service,
providing a key value of
WroxCustomers.Customers
.The
value
attribute takes a value of the location of
the Customers Web service, which is found within the
Customers.asmx
page.
Invoking the Web Service from the Client Application
Now that a reference has been made to the XML Web service, you can use it in your ASP.NET application.
Create a new Web Form in your project. With this page, you can consume the Customers table from the
remote Northwind database directly into your application. The data is placed in a GridView control.
On the design part of the page, place a Button and a GridView control so that your page looks something
like the one shown in Figure 29-9.
1338
Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1339
Chapter 29: Building and Consuming Services
Figure 29-9
The idea is that, when the end user clicks the button contained on the form, the application sends a SOAP
request to the Customers Web service and gets back a SOAP response containing the Customers table,
which is then bound to the GridView control on the page. Listing 29-7 shows the code for this simple
application.
Listing 29-7: Consuming the Customers Web service in an ASP.NET page
VB
<%@ Page Language="VB" %>
<script runat="server">

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim ws As New WroxCustomers.Customers()
GridView1.DataSource = ws.GetCustomers()
GridView1.DataBind()
End Sub
</script>
<html xmlns=" >
<head runat="server">
<title>Web Service Consumer Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" Runat="server" Text="Get Customers"
OnClick="Button1_Click" />
<br />
<br />
<asp:GridView ID="GridView1" Runat="server" BorderWidth="1px"
BackColor="#DEBA84" CellPadding="3" CellSpacing="2" BorderStyle="None"
BorderColor="#DEBA84">
<FooterStyle ForeColor="#8C4510" BackColor="#F7DFB5"></FooterStyle>
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center"></PagerStyle>
<HeaderStyle ForeColor="White" Font-Bold="True"
BackColor="#A55129"></HeaderStyle>
<SelectedRowStyle ForeColor="White" Font-Bold="True"
BackColor="#738A9C"></SelectedRowStyle>
Continued
1339
Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1340
Chapter 29: Building and Consuming Services

<RowStyle ForeColor="#8C4510" BackColor="#FFF7E7"></RowStyle>
</asp:GridView>
</div>
</form>
</body>
</html>
C#
<%@ Page Language="C#" %>
<script runat="server">
protected void Button1_Click(Object sender, EventArgs e) {
WroxCustomers.Customers ws = new WroxCustomers.Customers();
GridView1.DataSource = ws.GetCustomers();
GridView1.DataBind();
}
</script>
The e nd user is presented with a simple button. Clicking it causes the ASP.NET application t o send a
SOAP request to the remote XML Web service. The returned DataSet is bound to the GridView control,
and the page is redrawn, as shown in Figure 29-10.
Figure 29-10
1340
Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1341
Chapter 29: Building and Consuming Services
The Customers Web service is invoked by the instantiation of the
WroxCustomers.Customers
proxy
object:
Dim ws As New WroxCustomers.Customers()
Then you can use the
ws
object like any other object within your project. In the code example from

Listing 29-7, the results of the
ws.GetCustomers()
method call is assigned to the
DataSource
property of
the GridView control:
GridView1.DataSource = ws.GetCustomers()
As you develop or consume more Web services within your applications, you will see more of their
power and utility.
Transpor t Protocols for Web Ser vices
XML Web services use standard wire formats such as HTTP for transmitting SOAP messages back and
forth, and this is one of the reasons for the tremendous popularity of Web services. Using HTTP makes
using Web services one of the more accessible and consumable messaging protocols when working
between disparate systems.
The transport capabilities o f Web services are a fresh new addition to the evolutionary idea of a mes-
saging format to use between platforms. DCOM, an older messaging technology that was developed to
address the same issues, uses a binary protocol that consists of a method-request layer riding on top of
a proprietary communication protocol. One of the problems with using DCOM and similar methods for
calling remote objects is that the server’s firewall usually gets in the way because DCOM flows through
some odd port numbers.
Web services, on the other hand, commonly use a port that is typically open on almost every server — port
80. The port is used for HTTP or Internet traffic. Moving messages from one system to another through
port 80 over HTTP is sensible and makes consumption of Web services easy.
An interesting note about XML Web services is that, although many people still think of Web services as
SOAP going over HTTP, you can actually consume the Web service in a couple of different ways. Three
wire formats are available to Web services: HTTP-GET, HTTP-POST, and SOAP.
Listing 29-8 shows how to work with these different wire formats by consuming a simple Addition Web
service.
Listing 29-8: The Addition Web service
VB

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
<WebService(Namespace := " _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
Public Class WroxMath
Continued
1341
Evjen c29.tex V2 - 01/28/2008 3:53pm Page 1342
Chapter 29: Building and Consuming Services
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function Addition(ByVal a As Integer, ByVal b As Integer) As Integer
Return (a + b)
End Function
End Class
C#
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace = " />[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WroxMath : System.Web.Services.WebService
{
[WebMethod]
public int Addition(int a, int b) {
return a + b;
}
}
The Addition Web service takes two parameters:

a
and
b
. The Web service then adds these numbers
and returns the result in a SOAP message. You might typically consume this Web service by sending a
request SOAP message to the service. Now look at some of the other means of consumption.
HTTP-GET
The use of HTTP-GET has been rather popular for quite awhile. It enables you to send your entire request,
along with any required parameters, all contained within the URL submission. Here is an example of a
URL request that is passing a parameter to the server that will respond:
?newscategory=world
In this example, a request from the
Reuters.com
Web site is made, but in addition to a typical Web
request, it is also passing along a parameter. Any parameters that are sent along using HTTP-GET
can only be in a name/value pair construction — also known as querystrings. This means that you can
have only a single value assigned to a single parameter. You cannot provide hierarchal structures through
querystrings. As you can tell from the previous URL construction, the name/value pair is attached to the
URL by ending the URL string with a question mark, followed by the variable name.
Using querystrings, you can also pass more than a single name/value pair with the URL request as the
following example shows:
?newscategory=world&language=en
In this example, the URL construction includes two name/value pairs. The name/value pairs are sepa-
ratedwithanampersand(
&
).
1342

×