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

Tài liệu Module 5: Implementing a Simple Web Service pdf

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 (916.77 KB, 78 trang )









Contents
Overview 1
Creating a Web Service Project 2
Implementing Web Service Methods 13
Managing State in an ASP.NET Web
Service 33
Debugging Web Services 41
Lab 5: Implementing a Simple Web
Service 59
Review 73

Module 5: Implementing
a Simple Web Service



Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or


transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

 2001 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, Active Directory, Authenticode, Biztalk,
Intellisense, Jscript, MSDN, PowerPoint, Visual Basic, Visual C++, Visual C#, Visual Studio,
Win32, and Windows Media are either registered trademarks or trademarks of Microsoft
Corporation in the U.S.A. and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.


Module 5: Implementing a Simple Web Service iii


Instructor Notes
This module provides students with the skills that are required to implement a
Web Service using Microsoft
®
Visual Studio
®
.NET and debug it. They will
also modify the solution to Lab 4, “Implementing a Web Service Consumer

Using Visual Studio .NET,” in Course 2524A, Developing XML Web Services
Using Microsoft Visual C# .NET Beta 2, to communicate with the Web Service
they will create in the lab exercises for this module.
After completing this module, students will be able to:
!
Create a Web Service project.
!
Implement Web Service methods, expose them, and control their behavior.
!
Manage state in a Microsoft ASP.NET-based Web Service.
!
Debug Web Services.

Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.
Required Materials
To teach this module, you need the Microsoft PowerPoint
®
file 2524A_05.ppt.
Preparation Tasks
To prepare for this module:
!
Read all of the materials for this module.
!
Try the walkthroughs and demonstrations in this module.
!
Complete the lab.

Presentation:

150 Minutes

Lab:
75 Minutes
iv Module 5: Implementing a Simple Web Service


Module Strategy
Use the following strategy to present this module:
!
Creating a Web Service Project
This section provides an overview of the mechanics of implementing a
simple Web Service using the ASP.NET Web Service project template. It
also explains the purpose of each of the files generated for the default Web
Service project.
!
Implementing Web Service Methods
This section is intended to help students understand:
• How the various properties of the WebMethod attribute affect a Web
Service method.
• How to implement Web Service methods with parameter lists of varying
complexity.
Do not get drawn into a discussion of the tradeoffs between the various
options for representing parameter lists. This discussion should be deferred
until Module 8, “Designing Web Services,” in Course 2524A, Developing
XML Web Services Using Microsoft Visual C# .NET Beta 2. Be sure to
practice the Component Designer and XML Designer demonstrations.
!
Managing State in an ASP.NET Web Service
This section discusses application and session state management in Web

Services. It covers the mechanics of using application and session state, and
not the advantages and disadvantages of using these state services. For
students who are familiar with ASP programming, emphasize the similarity
in the mechanics of using the application and session state services. Once
again, defer any in-depth discussion of issues relating to performance or
scaling to Module 8, “Designing Web Services,” in Course 2524A,
Developing XML Web Services Using Microsoft Visual C# .NET Beta 2.
!
Debugging Web Services
This topic is intended to familiarize students with various tools and
techniques available for debugging Web Services. The simplest debugging
tools covered are the Trace and Debug classes. The use of Simple Object
Access Protocol (SOAP) extensions to provide more sophisticated tracing is
also covered. Do not explain all the details of the TraceExtension
implementation. Just cover the concepts of hooking the serialization process
and the mechanics of associating a SOAP extension with a method through
a custom attribute.
The last topic of this section provides a brief overview of application- and
page-level tracing using trace.axd, using an event log, and performance
counters. Focus on the mechanics and not about the issues related to
performance, scaling, and deployment.

Module 5: Implementing a Simple Web Service 1


Overview
!
Creating a Web Service Project
!
Implementing Web Service Methods

!
Managing State in an ASP.NET Web Service
!
Debugging Web Services

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Web Services can be implemented in several ways using any programming
language. For example, you can implement a Web Service using Microsoft
®
Visual C#

, Microsoft Visual Basic
®
, or Managed Extensions to Microsoft
Visual C++
®
. You can also implement a Web Service using the Microsoft
Active Template Library (ATL) Server, and deploy it as dynamic-link libraries
(DLLs).
In general, Course 2524A, Developing XML Web Services Using Microsoft
Visual C# .NET Beta 2, explains how to implement Web Services using
ASP.NET and Visual C#, and in particular, this module teaches you how to
implement a simple Web Service using these technologies.
To implement Web Services you must understand the components of a
Microsoft ASP.NET Web Service project and how to expose C# class methods
as Web Service operations. You must also understand how state can be

managed in ASP.NET Web Services and some of the issues related to state
management and Web Services.
Debugging distributed applications is not easy, and Web Services are not any
different in that respect. Therefore, you need to be familiar with some of the
techniques that you can use to debug Web Services.
After completing this module, you will be able to:
!
Create a Web Service project.
!
Implement Web Service methods, expose them, and control their behavior.
!
Manage state in an ASP.NET-based Web Service.
!
Debug Web Services.

Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
Web Services can be
implemented in several
ways using any language.
2 Module 5: Implementing a Simple Web Service


"
""
"


Creating a Web Service Project
!
Demonstration: Creating a Web Service Project
!
Examining the Parts of a Web Service Project

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In this section, you will look at the first step in implementing a Web Service,
which is creating the base project. You will also examine the results of
generating a project using the Web Service project template.
Topic Objective
To introduce the topics in
this section.
Lead-in
In this section, you will look
at the first step in
implementing a Web
Service, which is creating
the base project.
Module 5: Implementing a Simple Web Service 3


Demonstration: Creating a Web Service Project

*****************************
ILLEGAL FOR NON

-
TRAINER USE
******************************
In this demonstration, you will see how to create a Visual C#-based ASP.NET
Web Service project in Visual Studio .NET.
Topic Objective
To demonstrate how to
create a Web Service
project in Visual Studio
.NET.
Lead-in
In this demonstration, you
will see how to create a
Visual C#-based ASP.NET
Web Service project in
Visual Studio .NET.
Delivery Tip
1. In Visual Studio .NET,
create a Visual C#-based
ASP.NET Web Service
project.
2. Point out the project
location.
The next slide could be
presented as the rest of this
demonstration.
Tell the students not to try
out the steps while you are
performing the
demonstration, because

they will get a chance to do
this activity in the lab for this
module.
4 Module 5: Implementing a Simple Web Service


Examining the Parts of a Web Service Project
!
References
#
System namespace
#
System.Data namespace
#
System.Web namespace
#
System.Web.Services namespace
#
System.XML namespace
!
The .asmx File
#
Service Help page
#
Service Method Help page
#
Service Description Page

*****************************
ILLEGAL FOR NON

-
TRAINER USE
******************************
ASP.NET Web Services are ASP.NET applications and therefore there are
many elements that are common between them. Let us look at the various parts
of the base project.
References
By default, references to a list of Microsoft .NET Framework namespaces are
included in the base project. Let us look at this list.
System namespace
The System namespace contains classes that define commonly-used values and
reference data types, events and event handlers, interfaces, attributes, and
processing exceptions.
System.Data namespace
The System.Data namespace consists primarily of the classes that constitute
the Microsoft ADO.NET architecture. The DataSet class plays a central role in
the ADO.NET architecture. A DataSet is an in-memory cache of data obtained
from many possible data sources such as databases or Extensible Markup
Language (XML) documents. A DataSet reads and writes data and schema as
XML documents. Both the data and schema can be sent over the Hypertext
Transfer Protocol (HTTP) and can be used by any application, on any platform
that supports XML.
You will learn about DataSets in detail in the next section.
Topic Objective
To explain the references
and .asmx file of a Web
Service project.
Lead-in
ASP.NET Web Services are
ASP.NET applications and

therefore there are many
elements that are common
between them.
Module 5: Implementing a Simple Web Service 5


System.Web namespace
The System.Web namespace supplies classes and interfaces that facilitate
communication between a browser and a server. This namespace includes the
HTTPRequest and HTTPResponse classes that are discussed in Module 3,
“The Underlying Technologies of Web Services,” in Course 2524A,
Developing XML Web Services Using Microsoft Visual C# .NET Beta 2.
System.Web also includes classes for cookie manipulation, file transfer,
exception information, and output cache control. You will revisit this
namespace later in this module when you look at improving Web Service
performance using caching, and cookie-based and cookieless authentication.
System.Web.Services namespace
The System.Web.Services namespace consists of classes that help you to build
and use Web Services. One of the most important classes in this namespace is
the WebService class. If a Web Service needs access to the ASP.NET intrinsic
(built-in) objects, then the class which implements the Web Service operations
must be derived from the WebService class.
System.XML namespace
The System.XML namespace exposes the XML classes that provide standards-
based support for processing XML. The supported standards are:
!
XML 1.0
The XmlTextReader class provides a parser for documents in XML 1.0.
!
XML namespaces

The .NET Framework supports the use of namespaces in both XML streams
and the Document Object Model (DOM).
!
XML schemas
The .NET Framework supports schema mapping and XML serialization.
However, it does not support validation using XML Schema Definition
language (XSD).
!
XML Path Language (XPath) expressions
The XPathNavigator class provides read-only, random access to XML
documents using XPath expressions.
!
Extensible Stylesheet Language Transformations (XSLT)
XSLT allows you to transform XML data using XSLT stylesheets.
!
DOM
The XmlDocument class implements the World Wide Web Consortium
(W3C) DOM Level 1 Core and DOM Level 2 Core specifications.
!
Simple Object Access Protocol (SOAP) 1.1
The classes that encapsulate SOAP support in the .NET Framework can be
found in the System.Web.Services.Protocols namespace.

6 Module 5: Implementing a Simple Web Service


The .asmx File
The .asmx file is the front end for a Web Service implemented using ASP.NET.
The way you access this file through HTTP determines the type of response you
receive.

By default, the .asmx file contains a class that is similar to the following
example class:
public class Service1 : System.Web.Services.WebService
{

The class contains a sample WebMethod implementation that is similar to the
following:
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}

The Service Help page
When you request an .asmx file from a Web browser without supplying a
recognized query string, the file returns an automatically generated service help
page for the Web Service. If you performed an HTTP-GET request for the
.asmx page without supplying a query string, the results would be the same. A
Service Help page provides a list of the methods of the Web Service that can be
accessed programmatically. The page contains links for each method, and each
of these links will take you to a Service Method Help page for the
corresponding method.
Delivery Tip
From your browser,
navigate to the following
URL: http://localhost/
contoso/Micropayment
.asmx. Explain the
conscepts in the student
notes using this page.

Module 5: Implementing a Simple Web Service 7


A Service Help page also contains a link to the corresponding Web Service
description document as shown in the following illustration.

8 Module 5: Implementing a Simple Web Service


!
To access the Service Help page of a Web Service
• From your browser, navigate to the base URL for the corresponding Web
Service, using the following format:
http://servername/projectname/webservicename.asmx


The following table describes the parts of the preceding URL:
Part Value

servername The server on which the Web Service
resides.
projectname The name of the Web Service project and
any additional path information needed to
access the .asmx file for the Web Service.
webservicename.asmx The name of the .asmx file for the Web
Service.

The Service Method Help page
The Service Method Help page of a Web Service provides additional
information that relates to a method of the Web Service.

The page also allows you to invoke the method if it can be invoked using the
HTTP-POST protocol.
Sample request and response messages for the protocols supported by the Web
Service method are provided at the bottom of the Service Method Help page.
The following is an illustration of a Service Method Help page.

Module 5: Implementing a Simple Web Service 9


The Service Description
The service description for a Web Service is a Web Services Description
Language (WSDL) document. The Service Help page provides a link to the
service description. You can also access the service description of a Web
Service from a browser by typing in the base URL for the Web Service, similar
to the way you access a Service Help page. However, you also need to supply
the query string WSDL as shown in the following example:
http://servername/projectname/webservicename.asmx?WSDL

10 Module 5: Implementing a Simple Web Service


Examining the Parts of a Web Service Project (continued)
!
Global.asax
!
Web.config
!
The .vsdisco file
!
AssemblyInfo.cs

!
The /bin folder

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Apart from the list of references and the .asmx file for a Web Service, the Web
Service project consists of several other entries.
Global.asax
The Global.asax file is an optional file that contains the code for responding to
application-level events raised by ASP.NET or by the HttpModule class. The
Global.asax file resides in the root directory of an ASP.NET application. At
run time, Global.asax is parsed and compiled into a dynamically-generated
.NET Framework class derived from the HttpApplication base class. The
Global.asax file itself is configured so that any direct URL request for the file is
automatically rejected. Therefore, external users cannot download or view the
code written within the Global.asax.
When you save changes to Global.asax file that is in use, the ASP.NET
framework detects that the file has been changed. It completes all of the current
requests for the application, sends the Application_OnEnd event to listeners
(if any), and restarts the application domain. In effect, the previous set of
actions restarts the application, closes all browser sessions, and flushes all state
information from the memory. When a new request arrives from a browser, the
ASP.NET framework re-parses and recompiles the Global.asax file and raise
the Application_OnStart event.
Topic Objective
To explain the remaining
parts of a Web Service

project.
Lead-in
Apart from the list of
references and the .asmx
file for a Web Service, the
Web Service project
consists of several other
entries.
Module 5: Implementing a Simple Web Service 11


Web.config
It is essential for Web Service developers to be able to implement configuration
settings without embedding values into the code, and Web site administrators to
be able to easily adjust configuration settings of a deployed Web Service.
ASP.NET Web Services provide this capability through a file named
Web.config.
The following are the features of Web.config:
!
Web.config is an XML-based text file. Any standard text editor or XML
parser can be used to create and edit the file.
!
Web.config applies configuration settings to the folder in which it resides
and all of its child folders.
Configuration files in child folders can supply configuration settings, in
addition to the settings inherited from parent folders. The child folder
configuration settings can override or modify the settings defined in parent
directories. A root configuration file named Machine.config, located at
C:\WINNT\Microsoft.NET\Framework\version\CONFIG, provides
ASP.NET configuration settings for the entire Web server.

!
At run time, ASP.NET uses the configuration settings provided by
Web.config to generate a collection of configuration settings for an
ASP.NET application. The resulting configuration settings are then cached
for all subsequent requests for a resource.
!
ASP.NET detects changes to Web.config and automatically applies the new
settings to the affected resources. The server does not need to be rebooted
for the changes to take effect.
!
Web.config is extensible. You can define new configuration parameters and
write configuration handlers to process them.
!
ASP.NET protects Web.config from external access by configuring the
Microsoft Internet Information Services (IIS) to prevent access to
configuration files directly from the browser. HTTP access error 403
(forbidden) is returned to any browser that attempts to directly request a
configuration file.

Throughout Course 2524A, Developing XML Web Services Using Microsoft
Visual C# .NET Beta 2, you will make periodic modifications to Web.config to
control debug and tracing behavior, security, etc.
The .vsdisco file
Module 4, “Consuming Web Services,” in Course 2524A, Developing XML
Web Services Using Microsoft Visual C# .NET Beta 2, explained the discovery
process and discovery documents. The .vsdisco file is just a discovery
document.
12 Module 5: Implementing a Simple Web Service



AssemblyInfo.cs
AssemblyInfo.cs is a project information file that contains metadata, such as
name, version, and culture information, about the assemblies in a project. This
file is compiled into the Web Service assembly. For more information about the
metadata for assemblies, see Course 2350A, Securing and Deploying
Assemblies.
The /bin folder
Below your project root folder is a folder named bin. The bin folder contains
the assembly that contains the compiled output of the project. The assembly is
first compiled to Microsoft intermediate language (MSIL) code when a Web
Service project is compiled, and then the assembly is just-in-time (JIT)-
compiled to native code on demand.
Module 5: Implementing a Simple Web Service 13


"
""
"

Implementing Web Service Methods
!
Exposing Web Service Methods
!
Examining Data Types and Parameter Lists
!
Demonstration: Creating a Typed DataSet Using the
Component Designer
!
Demonstration: Creating a Typed DataSet Using the
XML Designer


*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
After creating a Web Service project, the next step in implementing a Web
Service is to define its operations. In this section, you see how to expose
methods that you implement as Web Service operations, how to control the
serialization behavior of a method, and finally examine how to implement
methods with parameter lists and return types of varying complexity.
Topic Objective
To introduce the topics in
this section.
Lead-in
After creating a Web
Service project, the next
step in implementing a Web
Service is to define its
operations.
14 Module 5: Implementing a Simple Web Service


Exposing Web Service Methods
!
Applying the WebMethod Attribute
!
Configuring the WebMethod Attribute Properties
#
BufferResponse

#
CacheDuration
#
Description
#
EnableSession
#
MessageName
#
TransactionOption

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
A Web Service method is exposed by applying the WebMethod attribute to the
method. You can also control the behavior of the method by configuring the
properties of the WebMethod attribute.
Applying the WebMethod Attribute
To expose a method of a Web Service, you must do the following:
!
Specify that the method is public.
!
Apply the WebMethod attribute to the method.


Even if a Web Service method is specified as public, you still need to
attach the WebMethod attribute to expose it as part of a Web Service.


You can control the behavior of a Web Service method by configuring the
properties of the WebMethod attribute.
Configuring the WebMethod Attribute Properties
The WebMethod attribute has the following properties:
!
BufferResponse
!
CacheDuration
!
Description
!
EnableSession
!
MessageName
!
TransactionOption

Topic Objective
To explain the WebMethod
attribute and its properties.
Lead-in
A Web Service method is
exposed by applying the
WebMethod attribute to the
method.
Note
Delivery Tip
Explain how to set the
WebMethod attribute
properties by using the code

examples provided in this
topic.
Module 5: Implementing a Simple Web Service 15


BufferResponse
The BufferResponse property of the WebMethod attribute enables buffering
of responses for a Web Service method. When BufferResponse is set to true,
which is the default setting, ASP.NET buffers the entire response before
sending it to the client. The buffering is very efficient and helps improve
performance by minimizing communication between the worker process and
the IIS process. When BufferResponse is set to false, ASP.NET buffers the
response in chunks of 16KB. Typically, you would set this property to false
only if you did not want the entire contents of the response in memory all at
once. For example, if you are returning a collection whose items are streamed
out of a database to a client, you might not want to wait to send the first byte to
the client until the last byte has been retrieved.
You can set the BufferResponse property as shown in the following example:
public class Service1 : System.Web.Services.WebService
{
[WebMethod(BufferResponse=false)]
public Transactions GetTransactionHistory()
{
//implementation code
}
}

CacheDuration
The CacheDuration property enables caching of the results for a Web Service
method. This is known as output caching. ASP.NET caches the results for each

unique parameter set. A parameter set is a set of values that are supplied as
arguments to an operation. Each unique parameter set is associated with a
cached response. The value of the CacheDuration property specifies the time
duration (in seconds) for which ASP.NET must cache the response. The default
value of zero disables the caching of results. For more information about output
caching, see Module 8, “Designing Web Services,” in Course 2524A,
Developing XML Web Services Using Microsoft Visual C# .NET Beta 2.
You can set the CacheDuration property as shown in the following example:
public class Service1 : System.Web.Services.WebService
{
[WebMethod(CacheDuration=60)]
public double ConvertTemperature(double dFahrenheit)
{
return ((dFahrenheit - 32) * 5) / 9;
}
}

Example
Example
16 Module 5: Implementing a Simple Web Service


Description
The Description property supplies a description for a Web Service method that
will appear on the Service Help page. Unless set otherwise, the default value for
this property is an empty string.
You can set the Description property as shown in the following example:
public class Service1 : System.Web.Services.WebService
{
[WebMethod(Description="This method converts a !

temperature in degrees Fahrenheit to a !
temperature in degrees Celsius.")]
public double ConvertTemperature(double dFahrenheit)
{
return ((dFahrenheit - 32) * 5) / 9;
}
}

EnableSession
The EnableSession property enables session state for a Web Service method. If
a Web Service method supports session state, the Web Service can access the
session state collection directly from HttpContext.Current.Session or with the
WebService.Session property if the method inherits from the WebService base
class. The default value of the EnableSession property is false. You will learn
more about session state management later in this module. For more
information about session state and state management from the perspective of
performance and scalability, see Module 8, “Designing Web Services,” in
Course 2524A, Developing XML Web Services Using Microsoft Visual C# .NET
Beta 2.
You can set the EnableSession property as shown in the following example:
public class Service1 : System.Web.Services.WebService
{
[WebMethod(EnableSession=true)]
public double ConvertTemperature(double dFahrenheit)
{
Session("NumberOfConversions") =
Session("NumberOfConversions") + 1;
return ((dFahrenheit - 32) * 5) / 9;
}
[WebMethod(EnableSession=true)]

public int GetNumberOfConversions()
{
return Session("NumberOfConversions");
}
}

Example
Example
Module 5: Implementing a Simple Web Service 17


MessageName
The MessageName property enables the Web Service to uniquely identify
overloaded methods using an alias. The default value for this property is the
method name. If you set the MessageName property to a different value, the
resulting SOAP messages will reflect this name instead of the actual method
name.
You can set the MessageName property as shown in the following example:
public class Service1 : System.Web.Services.WebService
{
[WebMethod(MessageName="AddDoubles")]
public double Add(double dValueOne, double dValueTwo)
{
return dValueOne + dValueTwo;
}
[WebMethod(MessageName="AddIntegers")]
public int Add(int iValueOne, int iValueTwo)
{
return iValueOne + iValueTwo;
}

}

The AddDoubles SOAP request message for the method that adds doubles will
resemble the following:
POST /myWebService/Service1.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi=" />instance" xmlns:xsd="
xmlns:soap="
<soap:Body>
<AddDoubles xmlns="
<dValueOne>double</dValueOne>
<dValueTwo>double</dValueTwo>
</AddDoubles>
</soap:Body>
</soap:Envelope>
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

In the preceding code, notice that the name of the operation is not Add, but it is
the name specified in the MessageProperty, which is AddDoubles.

is a namespace available for Web Services that
are under development. It is recommended that you change this default
namespace before making a Web Service public.


Example
Note
18 Module 5: Implementing a Simple Web Service


The AddDoubles SOAP response message for the method that adds doubles
would resemble the following:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope namespaces omitted for brevity>
<soap:Body>
<AddDoublesResponse xmlns="
<AddDoublesResult>double</AddDoublesResult>
</AddDoublesResponse>
</soap:Body>
</soap:Envelope>

TransactionOption
The TransactionOption property enables a Web Service method to participate
as the root object of a Microsoft Distributed Transaction Coordinator (MS
DTC) transaction. Even though you can assign the TransactionOption
property with any of the values of the
System.EnterpriseServices.TransactionOption enumeration, a Web Service
method has only two possible behaviors:
!
The method does not participate in a transaction (Disabled, NotSupported,
Supported)
!
The method initiates a new transaction (Required, RequiresNew)


The default value for the TransactionOption property is
TransactionOption.Disabled. Before you can use the TransactionOption
property, you must add a reference to System.EnterpriseServices.dll to your
project. This assembly contains the System.EnterpriseServices namespace
which has methods and properties that expose the distributed transaction model
found in Microsoft Component Object Model (COM+) services. The
System.EnterpriseServices.ContextUtil class lets you vote on the outcome of
a transaction using the SetAbort or SetComplete methods.
Module 5: Implementing a Simple Web Service 19


Let us look at how to configure a Web Service method to initiate a new MS
DTC transaction.
!
To initiate a new MS DTC transaction
1. Add a reference to System.EnterpriseServices.dll.
2. Add the System.EnterpriseServices namespace to the Web Service, as
shown in the following code:
using System.EnterpriseServices;

3. Use the TransactionOption property as shown in the following code:
public class Service1 : System.Web.Services.WebService
{

[WebMethod(TransactionOption=TransactionOption.RequiresNew)
]
public string DoSomethingTransactional()
{
// The transaction was successful...
ContextUtil.SetComplete();

return ContextUtil.TransactionId;
}
}


Delivery Tip
Explain the steps on
initiating a new DTC
transaction to the students.
20 Module 5: Implementing a Simple Web Service


Examining Data Types and Parameter Lists
!
Simple Datatypes
!
In, Out, and Ref Parameters
!
Variable Length Parameter Lists
!
Complex Datatypes
#
Classes and structures
#
Arrays
#
Collections
#
DataSets


*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
When you implement Web Service methods using C#, there are some subtle
issues that you need to be aware of. Let us examine parameter lists of varying
complexity in Web Service methods.
Simple Datatypes
Simple datatypes such as int, double, and string can be used as in, out, or ref
parameters, or can be used as return values of Web Service methods. The
parameters are marshaled as XSD intrinsic datatypes.
In, Out, and Ref Parameters
All the in and ref parameters are defined in a WSDL document as part of the
inbound message for an operation. Similarly, any out and ref parameters and
the function return value are defined as part of the outbound message for an
operation. The only complexity that must be addressed is when you pass object
references. We will discuss this issue in detail later in this module.
Variable Length Parameter Lists
Web Service methods can handle variable length parameter lists. The parameter
lists can be homogeneous (all of the references in a list are of the same
datatype) or heterogeneous (not all of the references in a list are of the same
datatype).
Implementing a Web Service method that has a variable length parameter list is
no different from implementing a method on any class that takes a variable
length parameter list.
Topic Objective
To examine the Web
Service method data types
and parameter lists of

varying complexities.
Lead-in
When you implement Web
Service methods using C#,
there are some subtle
issues that you need to be
aware of.
Module 5: Implementing a Simple Web Service 21


The following examples show a method that takes a variable length list of
strings as its argument, and a method that takes a variable length list of objects
as its argument:
[WebMethod]
public int ListOfString(params string [] list)
{ return list.Length; }
[WebMethod]
public int ListOfThings(params object [] list)
{ return list.Length; }

By default, the Web Service proxy methods generated for these Web Service
methods will take arrays of string and list respectively. For example, the proxy
method for
ListOfThings
will resemble the following:
public int ListOfThings ( !
[XmlArrayItem("Object", IsNullable=true)] object[] list)

To call a method with a variable length argument list, you must manually add
the params keyword before the XmlArrayItem attribute as shown in the

following code:
public int ListOfThings ( !
params [XmlArrayItem("Object", IsNullable=true)] !
object[] list)

Remember that all of the preceding code is generated code. Therefore, if you
regenerate the proxy, then you must edit the proxy code again. Otherwise, you
can copy the modified code into another file so that it will not be overwritten.
The following is an example of calling a Web Service method with varying
arguments lists:
Fancy f = new Fancy();
Console.WriteLine("I sent {0}",f.ListOfThings ("one","two"));
Console.WriteLine("I sent {0}",f.ListOfThings (2,"one",3.5));

Complex Datatypes
For Web Services to be widely adopted, it is necessary that Web Service
methods can support complex datatypes as arguments and return values in
addition to supporting simple datatypes. Let us look at some examples of Web
Service methods that use complex datatypes.
Classes and structures
It is important to remember that Web Services do not perform object remoting.
In other words, when a proxy class is generated for a Web Service, state
information is never transmitted to the client. Nor is the object that implements
the Web Service methods persistent on the server side. This is because HTTP is
stateless. For these reasons, if you specify a class as a parameter or a return
type, you must think of the class as a structure.
Examples

×