Microsoft Official Course 2524C, Developing XML Web Services Using Microsoft ASP - NET-Microsoft (2003)
Microsoft Official Course 2524C, Developing XML Web Services Using Microsoft ASP - NET-Microsoft (2003)
Delivery Guide
Course Number: 2524C
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.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Contents
Introduction
Course Materials...................................................................................................2
Prerequisites .........................................................................................................3
Course Outline......................................................................................................4
Setup.....................................................................................................................8
Microsoft Official Curriculum..............................................................................9
Microsoft Certified Professional Program..........................................................11
Facilities .............................................................................................................13
Module 1: The Need for XML Web Services
How to Teach This Module .................................................................................iv
Overview ..............................................................................................................1
Evolution of Distributed Applications..................................................................2
Lesson: Problems with Traditional Distributed Applications...............................4
Introducing Web Services ..................................................................................14
The Web Technology Stack and .NET ...............................................................16
The .NET Alternatives to Web Services.............................................................18
Common Web Service Scenarios .......................................................................20
Review................................................................................................................22
Module 2: XML Web Service Architectures
Overview ..............................................................................................................1
Service-Oriented Architecture ..............................................................................2
Lesson: Web Services Architectures and Service-Oriented Architecture ............4
Lesson: Roles in a Web Services Architecture.....................................................8
The Web Services Programming Model.............................................................16
Review................................................................................................................18
Module 3: The Underlying Technologies of XML Web Services
Overview ..............................................................................................................1
Lesson: HTTP Fundamentals ...............................................................................2
Lesson: Using HTTP with the .NET Framework .................................................8
Lesson: XML Essentials.....................................................................................17
Lesson: SOAP Fundamentals .............................................................................30
Lesson: Using SOAP with the .NET Framework ...............................................37
Review................................................................................................................46
Lab 3: Issuing HTTP and SOAP Requests Using the .NET Framework............48
Module 4: Consuming XML Web Services
Overview ..............................................................................................................1
WSDL Documents................................................................................................2
Lesson: Web Service Discovery...........................................................................9
Lesson: Web Service Proxies .............................................................................20
Lesson: Implementing a Web Service Consumer Using Visual Studio .NET....28
Review................................................................................................................35
Lab 4: Implementing an XML Web Service Consumer Using Visual Studio
.NET ...................................................................................................................37
iv Developing XML Web Services Using Microsoft® ASP.NET
Familiarity with C# !
Programming in C++, !
Java, or Microsoft®
Visual Basic®
Familiarity with !
Extensible Markup
Language (XML)
Course Objectives After completing this course, the student will be able to:
" Explain how Web services emerged as a solution to the problems with
traditional approaches to designing distributed applications.
" Describe the architecture of a Web services-based solution.
" Explain how to use the Microsoft .NET Framework to implement Web
services.
" Implement a Web service consumer by using Microsoft Visual Studio®
.NET.
" Implement a simple Web service by using Microsoft Visual Studio .NET.
" Publish and deploy a Web service.
" Secure a Web service.
" Evaluate the trade-offs and issues that are involved in designing a real-world
Web service.
" Implement nonstandard Web services such as Hypertext Markup Language
(HTML) screen scraping and aggregating Web services.
" Describe the Global XML Architecture and explain how to design Web
services to anticipate the new services.
vi Developing XML Web Services Using Microsoft® ASP.NET
Course Timing
The following schedule is an estimate of the course timing. Your timing
may vary.
Day 1
Start End Module
9:00 9:20 Introduction
9:20 10:20 Module 1: The Need for XML Web Services
10:20 10:30 Break
10:30 11:30 Module 2: XML Web Service Architecture
11:30 12:15 Lunch
12:15 2:15 Module 3: The Underlying Technologies of XML Web Services
2:15 2:25 Break
2:25 3:10 Lab 3: Issuing HTTP and SOAP Requests Using the .NET
Framework
3:10 5:10 Module 4: Consuming XML Web Services
Day 2
Start End Module
9:00 10:15 Lab 4: Implementing an XML Web Service Consumer Using
Visual Studio .NET
10:15 10:25 Break
10:25 12:00 Module 5: Implementing a Simple XML Web Service
12:00 12:45 Lunch
12:45 1:40 Module 5: Implementing a Simple XML Web Service
(continued)
1:40 2:55 Lab 5: Implementing a Simple XML Web Service
2:55 3:05 Break
3:05 4:35 Module 6: Deploying and Publishing XML Web Services
Developing XML Web Services Using Microsoft® ASP.NET vii
Day 3
Start End Module
9:00 11:00 Module 7: Securing XML Web Services
11:00 11:10 Break
11:10 12:10 Lab 7: Securing XML Web Services
12:10 1:00 Lunch
1:00 2:00 Module 8: Designing XML Web Services
2:00 2:40 Lab 8.1: Implementing Caching in an XML Web Service
2:40 2:50 Break
2:50 3:20 Module 8: Designing XML Web Services (continued)
3:20 4:20 Lab 8.2: Implementing an Aggregated XML Web Service
4:20 4:50 Module 9: Global XML Web Services Architecture
viii Developing XML Web Services Using Microsoft® ASP.NET
Document Conventions
The following conventions are used in course materials to distinguish elements
of the text.
Convention Use
Contents
Introduction 1
Course Materials 2
Prerequisites 3
Course Outline 4
Setup 8
Microsoft Official Curriculum 9
Microsoft Certified Professional Program 11
Facilities 13
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.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Introduction iii
Instructor Notes
Presentation: The Introduction module provides students with an overview of the course
20 Minutes content, materials, and logistics for Course 2524, Developing XML Web
Services Using Microsoft® ASP.NET.
Required Materials To teach this course, you need the following materials:
! Delivery Guide
! Trainer Materials compact disc
Introduction
Course Materials
Note To open the Web page, insert the Student Materials compact disc into
the CD-ROM drive, and then in the root directory of the compact disc,
double-click Autorun.exe or Default.htm.
Prerequisites
Course Outline
Module 4, “Consuming XML Web Services,” is the first of the modules that
discusses the implementation details of a Web service-based solution. This
module specifically focuses on how to implement a Web service consumer to
consume (use) Web services. Web Service consumers are implemented based
on the service description documents of Web services. In this context, this
module discusses the structure of a Web Service Description Language
(WSDL) document and how to find Web services and their service descriptions
at known endpoints by using Disco.exe. After completing this module, you will
be able to implement a Web service consumer by using Microsoft
Visual Studio® .NET.
6 Introduction
Setup
Labs There are starter and solution files associated with the labs in this course. The
starter files are located in the install_ folder\Labfiles\language\Lab0x\Starter
folder and the solution files are in the install_ folder\Labfiles\language\
Lab0x\Solution folder, where Lab0x reflects the current lab.
Note The labs in this course are based on a banking services scenario. A
complete working solution of this scenario is located in the
install_folder\Labfiles\language\WebServicesSolution folder.
Demonstrations and There are code files associated with the demonstrations and code walkthroughs
code walkthroughs in this course. These files are located in the install_folder\Democode\language\
Mod0x folder, where Mod0x reflects the current module.
Introduction 9
Other related courses may become available in the future, so for up-to-date
information about recommended courses, visit the Training and Certification
Web site.
Microsoft Training and For more information, visit the Microsoft Training and Certification Web site at
Certification information http://www.microsoft.com/traincert/.
Introduction 11
Certification The certification requirements differ for each certification category and are
requirements specific to the products and job functions addressed by the certification. To
become a Microsoft Certified Professional, you must pass rigorous certification
exams that provide a valid and reliable measure of technical proficiency and
expertise.
For More Information See the Microsoft Training and Certification Web site at
http://www.microsoft.com/traincert/.
You can also send e-mail to [email protected] if you have specific
certification questions.
Acquiring the skills Microsoft Official Curriculum (MOC) and MSDN Training Curriculum can
tested by an MCP exam help you develop the skills that you need to do your job. They also complement
the experience that you gain while working with Microsoft products and
technologies. However, no one-to-one correlation exists between MOC and
MSDN Training courses and MCP exams. Microsoft does not expect or intend
for the courses to be the sole preparation method for passing MCP exams.
Practical product knowledge and experience is also necessary to pass the MCP
exams.
To help prepare for the MCP exams, use the preparation guides that are
available for each exam. Each Exam Preparation Guide contains exam-specific
information, such as a list of the topics on which you will be tested. These
guides are available on the Microsoft Training and Certification Web site at
http://www.microsoft.com/traincert/.
Introduction 13
Facilities
Contents
Overview 1
Evolution of Distributed Applications 2
Lesson: Problems with Traditional
Distributed Applications 4
Introducing Web Services 14
The Web Technology Stack and .NET 16
The .NET Alternatives to Web Services 18
Common Web Service Scenarios 20
Review 22
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.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 1: The Need for XML Web Services iii
Instructor Notes
Presentation: This module provides students with an understanding of the problem space that
60 minutes XML (Extensible Markup Language) Web services address. The module
compares various approaches to implementing distributed applications. Web
Lab: services are shown to be the natural evolution of distributed application
00 minutes architectures on the Internet. Because the Web services in this course are
implemented by using Microsoft® ASP.NET and the Microsoft .NET
Framework, alternate options for implementing distributed applications by
using the .NET Framework are discussed to better define what kinds of
solutions Web services are appropriate for.
After completing this module, students will be able to:
! Describe the evolution of distributed applications.
! Identify the problems with traditional distributed application architectures
and technologies.
! Describe Web services and briefly explain how they address the design
problems in traditional distributed applications.
! List the alternate options for distributed application development.
! Identify the kinds of scenarios where Web services are an appropriate
solution.
Required materials To teach this module, you need the Microsoft PowerPoint® file 2524C_01.ppt.
Preparation tasks To prepare for this module:
! Read all of the materials for this module.
! Read the topic “Designing Distributed Applications” in the Microsoft
Visual Studio® .NET documentation in Microsoft MSDN®. Also, read all of
the linked topics.
iv Module 1: The Need for XML Web Services
Overview
Why do we need The driving forces behind the move to decentralize processing and data storage
distributed include:
applications?
! Cost of mainframes
One of the primary driving forces was the cost of mainframes. Not only was
the initial investment cost beyond the reach of most companies, but having a
single point of failure was a risk that most companies could not afford.
! Data ownership
An important factor behind decentralization was the politics of data
ownership. Departments, divisions, geographic locations, or sites that
owned the data did not like to delegate the responsibility of managing their
data to some other central location.
! Security
Another important factor was security. For an organization, typically most
of its data must be easily accessible. However, sensitive corporate data still
must be secured. Catering to these two competing security requirements was
much easier if the data could be physically segmented.
The preceding factors led to the emergence of a new application design pattern,
which is known as distributed applications.
Distributed applications With the emergence of the design pattern for the distributed application came
as service providers the realization that the computer industry had not yet achieved its goal of reuse.
Instead of viewing distributed applications as logically monolithic, it became
useful to view the distributed components of an application as providers of
services to a logical application. The concept of distributing functionality held
the promise of reuse. Developers could use each of the distributed sets of
functionality as a building block for much larger applications. There are
significant problems in achieving this type of reuse. Some of these problems are
covered later in this module, when the various architectures and technologies
that are used to implement distributed applications are explained.
Distributed applications Although the Internet had existed for more than twenty years, it was only in the
and the Web mid-1990s that the possibility of the Internet providing significant infrastructure
for building distributed applications was realized. Simple text-based protocols
were developed as a primary means for communicating service requests and
sending data on the Internet. The widespread adoption of such protocols made
the Internet a viable platform for distributed applications. Instead of relying on
competing and often proprietary technologies, Web standards would form the
foundation for distributed applications for the Web.
4 Module 1: The Need for XML Web Services
The problems with the preceding architectures will also be discussed. Finally,
you will look at the effect of the Web standards on distributed application
development.
Module 1: The Need for XML Web Services 5
Security In distributed applications, there are more opportunities for security threats. Not
only must you consider authentication and authorization, but you also must
consider how to secure the communication between a client and a server, and
how to guard against man-in-the-middle attacks, denial-of-service attacks,
replay attacks, and other attacks.
Synchronizing clocks Many operations rely on time stamping. For example, it is not acceptable for a
server to acknowledge that it received a purchase order before the purchase
order was placed. This kind of a problem can arise if the clocks on the client
and server computers are not synchronized. Therefore, you must decide how
you will ensure the synchronization of the clocks on the various computers that
communicate in a distributed application.
Module 1: The Need for XML Web Services 7
RPC-Based Architectures
Building redundancy The first problem that is inherent in RPC-based architectures is discovery. How
can the application discover the information that is needed to connect to an
endpoint that could supply the required services? The simple solution that is
used in most applications is to hard-code the endpoint information. This is not
an optimal solution because it makes building redundancy and failover
capabilities into an application very difficult.
Aggregate availability As an application begins to rely on multiple distributed services, it becomes
more susceptible to the possibility of some critical service being unavailable.
Therefore, the aggregate availability of a distributed application would be
negatively affected by the brittleness of typical implementations. Typical
implementations are brittle because they do not tolerate changes to their
deployment environment very well without failure.
Load balancing and Hard-coding the endpoints in an application results in another problem.
failover Specifically, there is no simple way for an RPC-based application to do any
form of dynamic load balancing. Neither can the application respond to server
unavailability by dynamically failing over to an alternate server.
Prioritization Prioritization of requests is almost impossible because all requests by default
are handled on a first-come, first-serve basis. If a particular server is heavily
loaded, the higher priority clients might be subjected to unacceptable delays.
Consider an investment brokerage house. Most brokerage clients are small
accounts. However, the brokerage would also have a number of large accounts
that require special service because of their transaction volumes. In a volatile
market, large clients must be given precedence over smaller customers. The
brokerage house cannot afford to have the transactions of large clients queued
behind transactions of smaller clients, at the risk of losing business from large
clients.
Load spikes
Another significant problem with RPC-based applications is the inability to
handle load spikes. Load spikes can have the following consequences:
! Temporary server outages due to server failure.
! Failure of an action because a required resource (for example, database
connections) had been exhausted.
! The need for more hardware than is required for typical loads, to handle the
infrequent load spikes.
Module 1: The Need for XML Web Services 9
Message-Based Architectures
Even if the preceding requirements are met, the resulting solution tends to be
difficult to implement and expensive. Therefore, message-based solutions are
not viable as a standard way to implement distributed applications.
Workflows and message Many distributed application scenarios involve workflows that are defined as a
sequencing sequence of messages being exchanged between multiple computers. Because
messages are sent asynchronously, it is possible that messages may arrive out of
order. In some scenarios, it would be fatal if messages were processed in an
incorrect sequence. For example, if a stock broker received orders to buy and
sell, out of sequence, this could significantly affect the prices paid in each
transaction. This means that the application developer has the additional burden
of creating a high-level protocol layer on top of the messaging protocol to track
the sequence of messages.
Module 1: The Need for XML Web Services 11
Web Standards
! Data formats
Another problem with binary protocols is the encoding of data that is
transmitted by using these protocols. Every protocol encodes data
differently, which places a huge overhead on organizations when they have
to consume data that was encoded in multiple, incompatible ways.
Also, the difficulty in translating data from one format to another leads to
the segregation of organizations based on the data formats that they can
handle.
Because of the problems in using binary protocols, there was a need for a
ubiquitous protocol, and an easily parsable and transformable data encoding. It
turned out that the emergence of the World Wide Web (WWW) provided the
universal solution that everyone could easily use.
The Internet and the Transmission Control Protocol (TCP) and Internet Protocol (IP) were originally
Web developed to connect different networks that different designers designed into a
network of networks. Ultimately, this network of networks came to be known
as the Internet.
Then, in late 1990, Tim Berners-Lee, a computer scientist at CERN invented
the World Wide Web, which is also known as the Web. The Web is a globally
interconnected network of hypertext documents. Emerging from this effort were
two revolutionary technologies: Hypertext Markup Language (HTML) and
Hypertext Transfer Protocol (HTTP).
HTML is a language that defines how to add markup (in the form of tags) to
text documents to provide information to a Web browser on how to lay out the
text in the document. The documents with HTML tags are known as hypertext
documents.
Advantages of HTTP HTTP is the protocol that is used for requesting and receiving hypertext
documents on the Web. A very important point to be noted about HTTP is that
it is not restricted to work with just HTML documents. An example of this fact
is that Web services and their clients can exchange XML documents by using
HTTP.
As the popularity of the Web increased, HTTP as a protocol has been almost
universally adopted. Using HTTP overcomes one of the major obstacles for the
interoperation of distributed object models, specifically the lack of a ubiquitous,
trusted protocol.
XML - A universal data Developers soon realized that although HTML allowed a document author to
format define presentation structure, it did not provide any way to define the structure
of the data or the relationship between the data in a document. In 1996, this
limitation led to the birth of a language for marking up text to describe the
structure of the data in a document. This language is known as Extensible
Markup Language (XML). Some of the goals of XML documents are that they
must be:
! Easily usable over the Internet.
! Unambiguous.
! Easy to create.
! Easy to parse and process.
! Extensible, platform independent, and able to support localization.
Module 1: The Need for XML Web Services 13
Web servers can forward requests for any kind of service that an HTTP request
describes and whose results can be packaged in an HTTP response. And all of
this can be done without requiring any reconfiguration or loosening of firewall
policy.
Problems with the Web In spite of the benefits that the Web has provided, there are some concerns in
the areas of security and performance.
Security
Because the Internet is a public infrastructure, it also means that any
communication is potentially vulnerable to interception, modification, spoofing
(a technique that is used to gain unauthorized access to a computer), and other
access-related issues.
Performance The majority of Internet users still only have dial-up access to the Internet. This
introduces significant performance problems and severely constrains the type
and complexity of application that can be delivered over the Web. For example,
some interactive applications require significant interaction with the server. The
bandwidth limitations of dial-up connections severely limit the kinds of
interactivity an application could support.
Performance issues combined with security concerns and reliability problems
(even the largest Web sites are not immune to server outages and service
unavailability) make designing applications for a private network a better
solution, in some scenarios.
14 Module 1: The Need for XML Web Services
Note In this course, any mention of Web services specifically refers to XML-
based Web services. Although other kinds of Web services are possible (for
example, custom HTTP listeners), it is unlikely that they will be as popular and
highly used as XML-based Web services.
Foundations for Web The foundations for Web services are HTTP, XML, and Simple Object Access
services Protocol (SOAP, a lightweight HTTP- and XML-based protocol that is used for
information exchange). The development of these technologies is governed by
the World Wide Web Consortium (W3C). You will learn about these
technologies in greater detail later in Module 3, “The Underlying Technologies
of XML Web Services,” in Course 2524C, Developing XML Web Services
Using Microsoft ASP.NET.
Building blocks Like components, Web services are black boxes. They encapsulate the
implementation and provide an interface for communicating with the Web
service. Therefore, you can use Web services as building blocks for
applications.
No granularity There is no restriction on the granularity of a Web service. It can range from
restriction simple components such as an order-tracking component published by a
shipping company to large applications such as hosted financial applications.
You can apply Web services at many different levels of a solution.
Module 1: The Need for XML Web Services 15
Static resources or Web services can provide convenient access to a static set of information. For
interactive applications example, a Web service can allow a customer to request demographic
information for a specified city.
Alternatively, developers might use Web services to implement highly
interactive applications. For example, a travel Web site might make it possible
to build an entire vacation itinerary online by using multiple Web services. The
user can use Web services for making hotel and rental car reservations,
planning flight itineraries, booking flights, and other travel-related processes.
Aggregating Web A Web service can aggregate other Web services to provide a sophisticated set
services of services. For example, a Web service for a real-estate agency might make use
of a Web service for a credit verification to facilitate approval of online loan
applications. In the future, more and more distributed applications will be built
from Web services. In such applications, Web services will often be selected at
run time based on different metrics, such as availability, cost, performance, and
quality. This level of choice will be invaluable in designing redundant systems
with failover capabilities.
Note Aggregating Web services are also known as federated Web services.
The future of distributed Why should Web services succeed where all other technologies have failed? Let
applications us look at the key characteristics of Web services that can enable its success.
Interoperability Web services are intended to be invoked by using SOAP. Because SOAP is
platform neutral, developers must no longer figure out how to build bridges
between DCOM, CORBA, and other disparate protocols. Any Web service can
interoperate with any other Web service.
Also, because Web services communicate by using HTTP and XML, any
network node, which supports these technologies, can both host and access
Web services.
Multilanguage support Developers can write Web services in any language. Consequently, developers
need not learn new languages or standardize on a single language to create or
consume Web services.
Reusing existing It is very easy to expose existing components and libraries as Web services.
applications Vendors, like Microsoft, provide tools to make the task of exposing
components and libraries even easier. Most companies have a large number of
existing components, libraries, and applications. It may be more cost effective
to reuse the functionality in these software resources than to reimplement them.
Use of industry- All of the major vendors are supporting technologies that are related to Web
supported standards services, specifically, HTTP, XML, and SOAP. The universal support for these
standards is unprecedented. This kind of support will make it very easy for
heterogeneous systems to communicate. For example, a component that is
written in C# and exported as a Web service can easily be used by a Common
Gateway Interface (CGI) application that is written in C++, if that application
were to make a SOAP request and process the result appropriately.
16 Module 1: The Need for XML Web Services
SOAP If you want to implement distributed services that have a very loose coupling
with the service consumers and are based completely on Web standards, then
you can implement a Web service. The protocol of choice for this kind of
application is the Simple Object Access Protocol (SOAP). A discussion on
SOAP is provided in Module 3, “The Underlying Technologies of XML Web
Services,” in Course 2524C, Developing XML Web Services Using Microsoft
ASP.NET.
The .NET Framework supports implementing Web services through the
System.Web.Services namespace.
18 Module 1: The Need for XML Web Services
Stand-alone listeners The first alternative to a Web service is a stand-alone listener. A stand-alone
listener is an application that monitors a well-known port and responds to the
messages it receives at that port. As a developer, you can implement stand-
alone listeners in different ways:
! You can use a prewritten Internet Server Application Programming
Interface (ISAPI) filter to handle all of the low-level socket communication
and protocol implementation on behalf of your listener. Some examples are
SOAP, Microsoft Active Server Pages (ASP), and Microsoft Active
Template Library (ATL) Server filters. You could then implement the
listener functionality in a C++ class or an ASP page.
! You can implement an ISAPI filter that handles requests for documents with
a specific extension and then decodes the contents of an HTTP request.
! You can write a server application that monitors a well-known port. You
will then not be restricted to using HTTP or SOAP protocols. To write such
an application, you can use the classes in the System.Net namespace of the
.NET Framework.
The preceding list is not exhaustive. However, it introduces you to the options
that are available for implementing stand-alone listeners.
Custom protocol If HTTP does not fit your requirements, then you can implement a custom
handlers protocol handler by deriving it from the WebRequest and WebResponse
classes, which are found in the .NET Framework. You can still make use of the
.NET serialization support when using your custom protocol, but the general
object-remoting capabilities are not available.
.NET Remoting If you need a remote component infrastructure, but do not need the level of
interoperability that Web services provide, then you can use .NET Remoting.
The System.Runtime.Remoting namespace provides classes to activate remote
objects, marshal arguments by value and by reference, make asynchronous
calls, and other operations.
.NET Remoting vs. Web On the surface, .NET Remoting and Web services appear very similar to each
services other. In fact, Web services are built on the .NET Remoting infrastructure.
However, it is recommended that you consider the following when choosing
which technology is more appropriate for the problem you are trying to solve:
! .NET Remoting tends to be more appropriate for applications where the
implementation of the applications at both endpoints is under the control of
the same organization.
! Web services are more appropriate for applications where the client side of
the service is likely to be outside the control of a particular organization (for
example, a trading partner).
From an ASP’s perspective, all hosted applications must meet at least the
following criteria:
! Application instances must be separately configurable for each subscriber,
even on shared hardware. This includes security settings.
! Applications must have mechanisms for measuring the duration of use of an
application for billing purposes.
Application integration Another potential use of Web services is in the area of application integration.
Scenarios for application integration are generally characterized by a loose
coupling with a published communication contract among the various
applications that need to be integrated.
Web services provide useful capabilities in both of these aspects. By design,
Web services are URL addressable, which provides for very loose coupling.
Also, by using Web Services Description Language (WSDL), individual Web
services can provide a contract that describes the Web service interface.
Note You will learn more about WSDL in Module 4, “Consuming XML Web
Services,” in Course 2524C, Developing XML Web Services Using Microsoft
ASP.NET.
22 Module 1: The Need for XML Web Services
Review
2. What are some of the problems that are associated with traditional
distributed application architectures?
• Use of binary protocols
• Use of proprietary data formats
• Tightly-coupled solutions
• Complexity of development
Module 1: The Need for XML Web Services 23
4. What is the main difference between .NET remoting and Web services?
.NET Remoting provides the infrastructure to support object remoting
solutions, including functionality. Web services support only the
transport of data, and not functionality.
THIS PAGE INTENTIONALLY LEFT BLANK
Module 2: XML Web
Service Architectures
Contents
Overview 1
Service-Oriented Architecture 2
Lesson: Web Services Architectures and
Service-Oriented Architecture 4
Lesson: Roles in a Web Services
Architecture 8
The Web Services Programming Model 16
Review 18
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.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 2: XML Web Service Architectures iii
Instructor Notes
Presentation: This module broadly describes the service-oriented architecture, which is a
60 Minutes conceptual architecture. Then, the module explains how XML (Extensible
Markup Language) Web service architectures are a type of service-oriented
Lab: architecture. It also describes the various roles within the Web service
00 Minutes architecture.
After completing this module, students will be able to:
! Identify how Web service architectures are a type of service-oriented
architecture.
! Describe the elements of a Web service architecture and explain their roles.
! Describe the Web service programming model.
Required Materials To teach this module, you need the Microsoft® PowerPoint® file 2524C_02.ppt.
Preparation Tasks To prepare for this module:
! Read all of the materials for this module.
! Try out the demonstration.
iv Module 2: XML Web Service Architectures
Demonstration
This section provides demonstration procedures that are not appropriate for the
student notes.
An Electronic Funds
Transfer Web Service
! To demonstrate the NorthwindClient application
1. Start the application NorthwindClient.exe, which can be found in the folder
install_folder\Labfiles\CS\Lab08_2\Solution\NorthwindClient\bin\Debug or
install_folder\Labfiles\VB\Lab08_2\Solution\NorthwindClient\bin.
2. In the From list, click Woodgrove Online Bank.
3. In the To list, click Contoso Micropayments.
4. Click Transfer.
5. Explain that $100 has been transferred from an account at the Woodgrove
Bank to an account at the micropayment service, named Contoso.
6. Explain that the Northwind Traders Web service took care of all the details
of managing the transfer, including retrieving routing numbers, and so on.
Module Strategy
Use the following strategy to present this module:
! Service-Oriented Architecture
Explain what a service-oriented architecture is. This topic is intended to
provide the students with a conceptual framework to be able to understand
the architecture of Web service-based solutions.
! Web Service Architectures and Service-Oriented Architecture
Explain the relationship between the conceptual service-oriented
architecture and Web services architectures. Use the demonstration of the
solution of the final lab in the course to show each of the Web service
architectural elements as concrete implementations.
! Roles in a Web Service Architecture
This topic examines the specific roles in Web service architecture and
explains that the Microsoft .NET Framework can provide assistance in
implementing the functionality for each of the entities that plays a role.
! The Web Services Programming Model
Describe the features of the Web services programming model. Emphasize
how this model is different than the traditional stateful, monolithic
programming model. However, defer any in-depth discussion on how the
Web services programming model affects the design of XML Web services
until Module 8, “Designing XML Web Services,” in Course 2524,
Developing XML Web Services Using Microsoft ASP.NET.
Module 2: XML Web Service Architectures 1
Overview
Service-Oriented Architecture
Building applications that meet the preceding requirements can result in the
following advantages:
! You can construct applications by integrating core business processes with
outsourced software services and resources.
! You can create more granular software resources.
! Reusable third-party software resources can provide cost and productivity
benefits.
! The sale of software as services can become widespread. For example, a
company could sell a shared calendar service as a Web accessible service
instead of selling a stand-alone calendar application.
Module 2: XML Web Service Architectures 3
All of these network nodes should be able to communicate with each other
typically through a Transmission Control Protocol/Internet Protocol (TCP/IP)
based network.
The diagram on the slide shows the relationship among the various elements of
a Web service architecture. The rest of this module focuses on how the
elements of a Web services architecture correspond to service-oriented
architecture and then focuses on the various elements of the architecture.
6 Module 2: XML Web Service Architectures
Note The entry points to Web services that are implemented by using
ASP.NET are Web pages with the extension .asmx.
The service consumer in The role of a service consumer is fulfilled by any node that can communicate
Web services by using Simple Object Access Protocol (SOAP) or HTTP, understands the
service interface that is being used, and can supply the necessary authentication
credentials.
Module 2: XML Web Service Architectures 7
IIS and Web services A Web server such as IIS can invoke a service on behalf of a client, by using
many different options. A Web server can start a Common Gateway Interface
(CGI) application; run a script interpreter as done in Microsoft Active Server
Pages (ASP), or invoke an ISAPI application.
When IIS works in conjunction with the common language runtime, it uses an
ISAPI filter to intercept requests for pages with the extension .asmx, and then
start a run-time host. The run-time host then executes the code for a Web
service that is implemented by using the .NET Framework.
IIS is not restricted to hosting .NET-based Web services. It can also host
Microsoft Active Template Library (ATL) Server-based Web services. ATL
Server-based Web services are beyond the scope of this course. However,
.NET-based Web service provides some significant advantages. One of the
most important advantages is the flexible security infrastructure that .NET
technology provides. For more information, see Module 7, “Securing XML
Web Services,” in Course 2524, Developing XML Web Services Using
Microsoft ASP.NET.
Examples of Web If an organization wants to provide Web services, it must be capable of
service providers providing some kind of electronic service. Because almost any piece of
functionality can be classified as a service, it is impossible to enumerate all the
possible kinds of Web services. However, two common examples of Web
service providers are independent software vendors and general-purpose
business processes.
Independent software vendors own products that perform a variety of tasks.
These products can be exposed as individual Web services or aggregations of
Web services. For example, a company that sells a calculation application for
personal taxes might want to make that application accessible as a Web service.
General-purpose business processes, which are sufficiently generalized for
adoption by a wide variety of clients, can also be exposed as Web services. For
example, a payroll processing service can offer its payroll management services
as a Web service.
Module 2: XML Web Service Architectures 11
Proxies When implementing a Web service consumer, developers can spend their time
more productively on other issues, and should not have to concern themselves
with the following tasks:
! Working with the underlying protocols.
! Parsing byte streams to extract data.
! Validating the inbound data streams.
! Constructing the outbound data packets.
However, the developer is often forced to handle the preceding tasks because
there is no prebuilt code available to perform these tasks. A typical approach to
handling these tasks is to encapsulate or hide the implementation details in a
wrapper class that acts as a proxy for the Web service. Not only can the proxy
classes hide implementation details, but they also provide the developer with a
familiar programming model of calling methods on objects.
The only problem with this technique is that a proxy class must be implemented
for every Web service interface that a Web service consumer wants to interact
with.
Microsoft provides a tool called Wsdl.exe to implement Web service proxy
classes. However, there are some pitfalls inherent in making the programming
interface to a Web service appear like a local procedure call. For more
information, see Module 4, “Consuming XML Web Services,” and Module 8,
“Designing XML Web Services,” in Course 2524, Developing XML Web
Services Using Microsoft ASP.NET.
Because a Web service interface is defined by using XML, it is also fairly
straightforward to write tools that can automatically generate the proxy wrapper
classes.
Asynchronous calls Because Web services are usually accessed over networks that are not as
reliable or fast as local area networks (LANs), it is often better to implement
Web service consumers that make asynchronous calls to Web services. The
proxies that are generated by using Wsdl.exe allow the caller to make
asynchronous calls to a Web server. The proxy class in conjunction with the
runtime handles details of thread pool management, the completion of a
callback notification method, and so on. For more information about how to
make asynchronous calls to a Web service, see Module 4, “Consuming XML
Web Services,” in Course 2524, Developing XML Web Services Using
Microsoft ASP.NET.
Examples of Web Line-of-business applications will probably be the primary users of Web
service consumers services, but there a number of types of businesses that could be Web service
consumers. Two examples of these types of businesses are online newspapers
and an Application Service Provider (ASP).
An online newspaper might use multiple Web service news feeds. The
incoming news feeds could be formatted, filtered, catalogued, and made
searchable according to customer preferences.
An Application Service Provider (ASP) might host Web services, re-brand Web
services, or do both. Also, an ASP might aggregate multiple Web services and
offer the composite Web service to its customers.
Module 2: XML Web Service Architectures 13
Interactions between Brokers specify to providers what kinds of information needs to be made
brokers and providers public, and then publishes this information. The kinds of information published
by a broker include:
! Classification information to allow Web services to be categorized.
! Contact information for the Web service.
! A textual description of the offered services.
! Links to documents providing information about the Web services that the
provider hosts.
! The location of endpoints for Web services.
These locations are usually stored as Uniform Resource Locators (URLs)
that denote the location of the advertised Web services. Because it is not
feasible to specify all of the information in the broker’s repository, there
may be pointers to URLs or file-based resources that will facilitate further
discovery. For example, service-level guarantees or information regarding
authentication requirements may be discoverable only at a Web service
provider’s location.
Interactions between The primary interaction between Web service consumers and the Web service
brokers and consumers broker is related to searching. Brokers must facilitate the search of their
repository to enable Web service consumers to locate the appropriate Web
service and then discover the information that is required to bind to that Web
service.
UDDI registries There are many approaches to providing the Web service brokering services.
One simple approach is to have all of the potential trading partners
communicate binding information to each other by using a specific method
created for that purpose. In this approach, you specifically do not require a
broker. For example, some organizations using electronic data interchange
(EDI) simply publish the list of required EDI document specifications that the
trading partners must use on a Web site. The problem with this approach is that
there is no easy way to discover which of the external businesses is compatible
with your business.
Another approach is to have all of the businesses publish a Web services
description file on their Web site. Then, Web crawlers can automatically access
a registered URL and can index the description files for the Web services that
are found at each Web site. A Web service broker could then provide a portal
that gives access to the indexes that the Web crawlers build. Relying on Web
crawlers to provide indexes for Web services has similar problems to the
problems encountered with standard Web search engines and catalogs that we
have today. The problem is that there is no mechanism to ensure consistency in
service description formats and for the easy tracking of changes whenever they
occur. Just as Web search engines return many invalid links, such a mechanism
for Web services would also result in out-of-date service descriptions and
binding information.
The brokering approach that has been chosen for Web services relies on a
distributed registry of businesses and their service descriptions that are
implemented in a common XML format. The solution that implements this
approach to solving the discovery problem is known as Universal Description,
Discovery, and Integration (UDDI).
Module 2: XML Web Service Architectures 15
For more information about how to publish an XML Web service in a UDDI-
compliant registry and how to search a UDDI-compliant registry to locate Web
services, see Module 6, “Deploying and Publishing XML Web Services,” in
Course 2524, Developing XML Web Services Using Microsoft ASP.NET.
16 Module 2: XML Web Service Architectures
For more information about how to design stateless Web services and how to
manage state in stateless Web services, see Module 8, “Designing XML Web
Services,” in Course 2524, Developing XML Web Services Using Microsoft
ASP.NET.
Loosely coupled In a nondistributed application, if any of the required software resources, such
as a function library in a dynamic-link library (DLL), are available when an
application is launched, they will continue to be available for the lifetime of the
application. Usually, they will also be available on each successive use of the
application. For distributed applications, especially distributed applications that
make use of software resources over the Internet, there is an increased
likelihood that the required software resources will not always be available.
Therefore, distributed applications that are implemented by using Web services
must be more resilient to software resources becoming unavailable, even at run
time.
As a consequence, Web service-based solutions must be loosely coupled so that
they can dynamically reconfigure themselves if a resource becomes
unavailable. Loosely coupled applications also have the advantage of allowing
failover because the consumers will not have affinity with any particular
instance of a Web service.
For more information about how to design Web services to facilitate loose-
coupling, and also learn how to implement loosely coupled Web services, see
Module 8, “Designing XML Web Services,” in Course 2524, Developing XML
Web Services Using Microsoft ASP.NET.
Universal data format The universal data format that is used in Web services is XML. A complete
coverage of XML is beyond the scope of this course, but a working knowledge
of XML is imperative to implement and consume Web services.
The following are a few of the areas where XML is used in Web services:
! The SOAP protocol is XML-based.
! Web service descriptions are XML documents.
! Data returned from a Web service is in an XML document.
! Web services are registered with a UDDI registry by using XML documents
that are business service descriptions.
! ASP.NET applications are configured by using XML configuration files.
18 Module 2: XML Web Service Architectures
Review
2. What service-oriented architecture role does a network node with IIS and
the runtime have in a Web service architecture?
Web service provider
Module 2: XML Web Service Architectures 19
3. Which wire format is used by a Web service and a Web service consumer to
communicate with each other?
SOAP
Overview 1
Lesson: HTTP Fundamentals 2
Lesson: Using HTTP with the
.NET Framework 8
Lesson: XML Essentials 17
Lesson: SOAP Fundamentals 30
Lesson: Using SOAP with the
.NET Framework 37
Review 46
Lab 3: Issuing HTTP and SOAP Requests
Using the .NET Framework 48
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.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 3: The Underlying Technologies of XML Web Services iii
Instructor Notes
Presentation: This module provides students with an overview of the technologies that form
120 Minutes the foundation of Extensible Markup Language (XML)-based Web services.
Lab: After completing this module, students will be able to:
45 Minutes
! Describe the structures of a Hypertext Transfer Protocol (HTTP) request
and response.
! Issue HTTP POST and GET requests and process the responses by using
the Microsoft® .NET Framework.
! Describe data types by using the XML Schema Definition language (XSD).
! Explain how to control the way a .NET Framework object is serialized to
XML.
! Describe the structures of a Simple Object Access Protocol (SOAP) request
and response.
! Issue a SOAP request and process the response by using the .NET
Framework.
Required Materials To teach this module, you need the Microsoft PowerPoint® file 2524C_03.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.
iv Module 3: The Underlying Technologies of XML Web Services
Module Strategy
This module is intended to explain the technologies underlying XML Web
services. Throughout this module, you should emphasize to the students the
simplicity of the technologies that are covered.
Use the following strategy to present this module:
! HTTP Fundamentals
This section is intended to provide students with a basic understanding of
the HTTP protocol and explain how to issue HTTP requests by using the
.NET Framework. Explain that HTTP is a simple protocol that is designed
for interoperability and not performance. Emphasize how simple HTTP is to
understand.
! Using HTTP with the .NET Framework
Use the code walkthroughs in this section to show the use of the base
classes that the .NET Framework provides to access data from the Internet.
Emphasize that these classes encapsulate the HTTP-specific operations
when communicating with a Web server, and show how synchronous and
asynchronous operations are supported.
! XML Essentials
Explain that XML is fundamental to Web services. Do not spend much time
on the basics of XML. Briefly review the important XML concepts. Cover
the topics on XSD as a progressive tutorial, rather than a list of concepts.
! XML Serialization in the .NET Framework
Explain how you can modify the default serialization behavior for .NET
Framework data types. Explain the importance of the ability to modify the
default serialization behavior of data types.
! SOAP Fundamentals
This topic is intended to provide students with a basic understanding of the
SOAP protocol and explain how to issue SOAP requests by using the .NET
Framework. Emphasize that SOAP is the preferred wire format for Web
services.
! Using SOAP with the .NET Framework
Explain to the students that the .NET Framework handles most of the details
of communication between a Web service and a Web service consumer
when using SOAP in Web services that are implemented by using the .NET
Framework.
Module 3: The Underlying Technologies of XML Web Services 1
Overview
Overview of HTTP
Symbol=MSFT
The first line in an HTTP request is known as the request line, and the methods
that a request supports are as follows:
! OPTIONS
! GET
! HEAD
! POST
! DELETE
! TRACE
! CONNECT
! extension-method
Module 3: The Underlying Technologies of XML Web Services 5
The most important feature of the request line is the query string. The query
string is the portion of the URI that follows the question mark, and consists of a
set of URL-encoded name/value pairs.
In an HTTP-GET request, there is typically no message body. The response for
an HTTP-GET request is just a standard HTTP response, which is described in
the preceding topic.
HTTP-POST request Consider the following HTTP-POST request:
POST /Trading/GetStockPrice.asp HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: 11
Symbol=MSFT
Module 3: The Underlying Technologies of XML Web Services 7
In the preceding code, notice that there is no query string as part of the URI.
This is because the information about the request is contained in the message
body. This feature of an HTTP-POST request makes it a very convenient way
of passing larger sets of data to the server in contrast to an HTTP-GET where
the size of the query string is restricted to 1024 bytes. Also, transmitting the
data as part of the message body imposes fewer restrictions on the kind of data
that is sent to the server.
In Module 5, “Implementing a Simple XML Web Service,” in Course 2524,
Developing XML Web Services Using Microsoft ASP.NET, you will see how the
choice of an HTTP request method affects the kinds of interfaces that the Web
services can expose.
8 Module 3: The Underlying Technologies of XML Web Services
HttpWebRequest and WebRequest and WebResponse are abstract base classes in the .NET
HttpWebResponse Framework for accessing data from the Internet in a protocol-neutral way. The
HttpWebRequest and HttpWebResponse classes, which are derived from
WebRequest and WebResponse respectively, encapsulate the HTTP-specific
aspects of the communications with a Web server. Most importantly, they
provide easy access to the HTTP headers, and the underlying request and
response streams.
StreamReader and The StreamReader and StreamWriter classes are two utility classes that are
StreamWriter used to read and write streams by using a specific encoding (UTF-8/UTF-16,
etc.).
Support for The HttpWebRequest class supports both synchronous and asynchronous
synchronous and requests. In the next two topics, you will look at code samples of synchronous
asynchronous and asynchronous operations.
operations
10 Module 3: The Underlying Technologies of XML Web Services
C# code example
1. HttpWebRequest req = (HttpWebRequest )
WebRequest.Create(url);
2. req.ContentType=contentType;
3. req.Method = method;
4. req.ContentLength=content.Length;
5. Stream s;
6. s = req.GetRequestStream();
7. StreamWriter sw = new StreamWriter(s,Encoding.ASCII);
8. sw.Write(content);
9. sw.Close();
10.
11. HttpWebResponse res = (HttpWebResponse)
req.GetResponse();
12. s = res.GetResponseStream();
13.
14. StreamReader sr = new StreamReader(s,Encoding.ASCII);
15. StringBuilder sb = new StringBuilder();
16. char [] data = new char[1024];
17. int nBytes;
18. do {
19. nBytes = sr.Read(data,0,(int)1024);
20. sb.Append(data);
21. } while (nBytes == 1024);
Code explanation The functionality that the preceding code implements is described in the
following list. Please note that each line reference to the code applies to both
the C# and Microsoft Visual Basic® .NET examples.
! In line 1, the return value of the WebRequest.Create call is converted to
HttpWebRequest.
In most cases, the WebRequest and WebResponse classes provide all of
the functionality that you need to perform an HTTP request. However, if
you need to access HTTP-specific features such as HTTP headers, you need
a protocol-specific derived class of WebRequest.
! In lines 2 through 4, HTTP-specific properties are set.
! In lines 6 through 9, the content for the request is written to a stream.
Note in line 7 that the type of encoding is specified for the stream.
! In line 11, the response from the server is retrieved.
! In lines 12 through 21, the content of the response message is read.
Because the response stream is not seekable, the total amount of data to be
read cannot be determined at the start of the content retrieval. As a result,
the content is retrieved in blocks.
Module 3: The Underlying Technologies of XML Web Services 13
C# code example
1. Stream s;
2. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
3. req.ContentType=contentType;
4. req.Method = method;
5. req.ContentLength=content.Length;
6. s = req.GetRequestStream();
7. StreamWriter sw = new StreamWriter(s);
8. sw.Write(content);
9. sw.Close();
10.
11. Handler h = new Handler();
12. AsyncCallback callback = new AsyncCallback(h.Callback);
13. // Pass the request object as the state object
14. req.BeginGetResponse(callback, req);
15.
16. ...
17.
18. public class Handler
19. {
20. public void Callback(IAsyncResult ar) {
21. // Get the WebRequest from RequestState.
22. HttpWebRequest req = (HttpWebRequest)ar.AsyncState;
23. // Get the response object associated
24. // with the request.
25. HttpWebResponse res =
(HttpWebResponse)req.EndGetResponse(ar);
26. // Start reading data from the response stream
27. Stream s = res.GetResponseStream();
28.
29. StreamReader sr = new StreamReader(s,Encoding.ASCII);
30. StringBuilder sb = new StringBuilder();
31. char [] data = new char[1024];
32. int nBytes;
33. do {
34. nBytes = sr.Read(data,0,(int)1024);
35. sb.Append(data);
36. } while (nBytes == 1024);
37. ...
38. // continue processing
39. }
40. }
Module 3: The Underlying Technologies of XML Web Services 15
1. Dim s As Stream
2. Dim req As HttpWebRequest = CType(WebRequest.Create(url), _
HttpWebRequest)
3. req.ContentType = contentType
4. req.Method = method
5. req.ContentLength = content.Length
6. s = req.GetRequestStream()
7. Dim sw As New StreamWriter(s)
8. sw.Write(content)
9. sw.Close()
10.
11. Dim h As New Handler()
12. Dim callback As New AsyncCallback(AddressOf h.Callback)
13. ' Pass the request object as the state object
14. req.BeginGetResponse(callback, req)
15.
16. ...
17.
18. Public Class Handler
19.
20. Public Sub Callback(ar As IAsyncResult)
21. ' Get the WebRequest from RequestState.
22. Dim req As HttpWebRequest = CType(ar.AsyncState, _
HttpWebRequest)
23. ' Get the response object associated
24. ' with the request
25. Dim res As HttpWebResponse = _
CType(req.EndGetResponse(ar), HttpWebResponse)
26. 'Start reading data from the response stream
27. Dim s As Stream = res.GetResponseStream()
28.
29. Dim sr As New StreamReader(s, Encoding.ASCII)
30. Dim sb As New StringBuilder()
31. Dim data(1024) As Char
32. Dim nBytes As Integer
33. Do
34. nBytes = sr.Read(data, 0, CInt(1024))
35. sb.Append(data)
36. Loop While nBytes = 1024
37. ...
38. ' continue processing
39. End Sub 'Callback
40. End Class 'Handler
16 Module 3: The Underlying Technologies of XML Web Services
Overview of XML
When describing the data that your Web service consumes or returns, it is
important to know the differences between elements and attributes so that you
can use them appropriately in your XML documents.
Module 3: The Underlying Technologies of XML Web Services 19
Well-formed documents All XML documents must be well-formed. For a document to be well-formed,
it must adhere to the following rules:
! There must be a single root element.
XML documents are trees, and not forests.
! All elements must be closed, unlike HTML, where many elements
(example: <BR>) are not required to be closed.
! Capitalization of opening and closing tags of elements must be consistent.
Many browsers allow inconsistent casing when using HTML elements
(example: <table>...</TABLE>), but inconsistent casing is not allowed in
XML.
! Elements must be nested correctly.
! Attribute values must be enclosed in quotes. Many browsers allow attribute
values to be unquoted, but unquoted attribute values are not allowed in
XML.
! An attribute cannot be repeated in an element.
Now that you have reviewed some of the important concepts of XML, the
remainder of this topic will focus on how XML is used in Web services.
Schemas To successfully use a Web service, you must know the operations that the Web
service supports and the structure of the documents (or messages) that each
operation consumes and produces. This information is defined in a document,
known as a service description, which describes a Web service. The service
description is created by using the Web Service Description Language (WSDL),
which is an XML-based language.
Within the WSDL documents, you define XSD schemas that describe the data
types and document structures that are allowed in XML documents. XSD
schemas validate XML documents in a mechanical way. This frees the
programmer from the error-prone task of correctly parsing and validating a
complex document structure.
You will learn the basics of XSD later in this module. For more information
about WSDL, see Module 4, “Consuming XML Web Services,” in
Course 2524, Developing XML Web Services Using Microsoft ASP.NET.
20 Module 3: The Underlying Technologies of XML Web Services
XSD Fundamentals
Note This topic is intended only to provide a brief introduction of some of the
major features of XSD. The complete specifications can be found at
http://www.w3c.org/XML/Schema.
Simple and complex An XML schema can consist of elements that are simple types or complex
types types. A complex type can contain child elements in addition to attributes in its
content. A simple type can contain neither child elements nor attributes in its
content.
Consider the following XML code:
<account status="active">
<number>1234-5X</number>
<type>CK</type>
<balance>5000.00</balance>
</account>
Module 3: The Underlying Technologies of XML Web Services 21
In the preceding example, you can further constrain the element named type to
restrict it to a 2-character code that is made up of only upper-case letters. You
can do this by defining a simple type and redefining the type element as
follows:
1. <xsd:element name="type" type="acctTypeCode"/>
2.
3. <xsd:simpleType name="acctTypeCode">
4. <xsd:restriction base="xsd:string">
5. <xsd:pattern value="[A-Z]{2}"/>
6. </xsd:restriction>
7. </xsd:simpleType>
Groups When designing the structure of a document, it can be useful to define groups
of elements or attributes that can be used in the definition of many different
complex types. For example, you might want to define different types of
accounts such as checking, savings, credit card, etc. It would be inconvenient to
repeatedly list the common elements in each account type in the type definition.
In such situations, XSD groups are useful.
In continuation with the preceding example, you can define a group of common
elements for all types of accounts as follows:
1. <xsd:group name="acct">
2. <xsd:sequence>
3. <xsd:element name="description" type="xsd:string"/>
4. <xsd:element name="number" type="xsd:string"/>
5. <xsd:element name="type" type="acctTypeCode"/>
6. <xsd:element name="balance" type="xsd:decimal"/>
7. </xsd:sequence>
8. </xsd:group>
22 Module 3: The Underlying Technologies of XML Web Services
You can use the preceding XSD group to define different account types as
shown in the following code:
1. <xsd:complexType name="checkingAcct">
2. <xsd:sequence>
3. <xsd:group ref="acct" />
4. </xsd:sequence>
5. <xsd:attribute name="status" type="xsd:string"/>
6. </xsd:complexType>
7.
8. <xsd:complexType name="savingsAcct">
9. <xsd:sequence>
10. <xsd:group ref="acct" />
11. <xsd:element name="minimumBalance" type="xsd:decimal" />
12. </xsd:sequence>
13. <xsd:attribute name="status" type="xsd:string"/>
14. </xsd:complexType>
Module 3: The Underlying Technologies of XML Web Services 23
! xsd:all
The xsd:all compositor defines an unordered list of elements, groups, or
compositors. For example, the xsd:all compositor in the following schema
code specifies that the XML document that the schema validates can contain
the checking, savings, and credit card elements in any order:
1. <xsd:complexType name="listOfAccts">
2. <xsd:all minOccurs="0" maxOccurs="unbounded">
3. <xsd:element ref="checking" minOccurs="0" />
4. <xsd:element ref="savings" minOccurs="0" />
5. <xsd:element ref="creditcard" minOccurs="0" />
6. </xsd:all>
7. </xsd:complexType>
Module 3: The Underlying Technologies of XML Web Services 25
Derivation Another powerful feature of XSD is the ability to define new types by
derivation. There are two ways of using derivation to define new types:
! restriction
Defining new types by using restriction involves further constraining
elements and attributes of the base type. For example, numeric values might
be restricted to a smaller range than in the base type.
! extension
Defining new types by using extension involves adding new elements to the
derived type. The derived type now has all of the elements that are added in
the derived type definition in addition to the elements that are defined in the
base type.
In the earlier example on simple types, you saw a new simple type named
accTypeCode that was derived by using restriction. In the following
example, a new type named savingsAcct is derived by extending the acct
type:
1. <xsd:complexType name="acct">
2. <xsd:sequence>
3. <xsd:element name="description" type="xsd:string"/>
4. <xsd:element name="number" type="xsd:string"/>
5. <xsd:element name="type" type="acctTypeCode"/>
6. <xsd:element name="balance" type="xsd:decimal"/>
7. </xsd:sequence>
8. <xsd:attribute name="status" type="xsd:string" />
9. </xsd:complexType>
10.
11. <xsd:complexType name="savingsAcct">
12. <xsd:complexContent>
13. <xsd:extension base="acct" >
14. <xsd:sequence>
15. <xsd:element name="minimumBalance"
16. type="xsd:decimal" />
17. </xsd:sequence>
18. </xsd:extension>
19. </xsd:complexContent>
20. </xsd:complexType>
26 Module 3: The Underlying Technologies of XML Web Services
The attribute classes that are used in the preceding code are explained in the
following paragraphs.
Note In the .NET Framework, attribute class names have the format
XXXXAttribute. However, using the .NET compilers makes it unnecessary for
developers to use the Attribute suffix in their code. Therefore, the .NET
developer can refer to “the XXXX attribute” instead of the XXXXAttribute class
without ambiguity.
The XmlRootAttribute Every XML document must have a single root element. The XmlRoot attribute
class allows you to control how the root element is generated by setting certain
properties. For example, you can specify the name of the generated XML
element by setting the ElementName property. You can apply the XmlRoot
attribute to classes only.
28 Module 3: The Underlying Technologies of XML Web Services
The You can apply the XmlElement attribute to public fields or public properties to
XmlElementAttribute control the characteristics of XML elements, such as the element name and
class namespace.
If you apply the XmlElement attribute to a field or property that returns an
array, the items in the array are generated as a sequence of XML elements.
However, if you do not apply the XmlElement attribute to such a field or
property, the items in the array are generated as a sequence of child elements,
nested under an element, which is named after the field or property.
The By default, the XML serializer serializes public fields and properties as XML
XmlAttributeAttribute elements. When you apply the XmlAttribute attribute to a public field or
class property, the XML serializer serializes the member as an XML attribute.
XML attributes can only be simple types. Therefore, you can apply the
XmlAttribute attribute only to public fields or properties that return a primitive
type.
The XmlArrayAttribute When you apply the XmlArray attribute class to a class member, the XML
class serializer generates a nested sequence of XML elements from that member. For
example, if a class that is to be serialized represents a bank’s customer, then
you can generate an array of accounts that the customer owns by applying the
XmlArray attribute to a public field that returns an array of objects that
represent the accounts. If you apply the XmlArray attribute to a field or
property that returns an array, then by default, the name of the generated XML
element is derived from the member identifier. However, by setting the
ElementName property of the XmlArray attribute, you can change the name
of the generated XML element.
The To more precisely control the XML element generation for the members of an
XmlArrayItemAttribute array, you can use the XmlArrayItem class. Using XmlArrayItem also allows
class you to ensure that polymorphic arrays (arrays containing derived objects of the
base array type) are correctly serialized. For example, suppose that a class
named acct exists and two other classes named checkingAcct and savingAcct
respectively that are derived from acct also exist. Further, suppose that a class
named bankCustomer has a field that returns an array of account objects. To
allow the XmlSerializer class to serialize both the checkingAcct and
savingsAcct classes, apply the XmlArrayItem to the field twice, once for each
of the two acceptable types.
There are many other attributes that you can use to control the format of a
serialized object. For more information, see the documentation for the
XmlXXXXAttribute classes in the System.XML namespace.
Module 3: The Underlying Technologies of XML Web Services 29
Caveats In the context of XML, the .NET Framework, and Web services, there are a few
caveats to keep in mind.
! Use of POST/GET versus SOAP
Currently, when you use [return:XmlArrayItem], the name of the array
item is modified when you use SOAP, but not when you use GET or POST.
Therefore, the generated XML document will be different depending on
whether the Web service consumer uses POST/GET or SOAP. The
following code shows how to control the names of the XML elements that
are emitted when an array is serialized:
C# example code [return:XmlArrayItem(ElementName="savingsAcct",
Type=typeof(SavingsAcct))]
[return:XmlArrayItem(ElementName="creditCardAcct",
Type=typeof(CreditCardAcct))]
[WebMethod]
public Acct[] GetAllAccounts()
{
...
! Property serialization
When an object is serialized, only public read/write properties are serialized.
In other words, there is no way to serialize a read-only property (a property
with only a get accessor).
30 Module 3: The Underlying Technologies of XML Web Services
You can potentially use SOAP in combination with a variety of other protocols.
However, the only protocol bindings currently defined are for HTTP and HTTP
Extension Framework (HTTP-EF).
Module 3: The Underlying Technologies of XML Web Services 31
Overview of SOAP
The SOAP Fault element defines the following four child elements:
! faultcode
The faultcode element is intended for use by the Web service consumer to
identify the fault. This element must be present within the SOAP Fault
element. SOAP defines a small set of SOAP fault codes that cover the basic
SOAP faults.
! faultstring
The purpose of the faultstring element is to provide a human-readable
explanation of the fault. It must be present within the SOAP Fault element
and must provide information explaining the nature of the fault.
! faultactor
The purpose of the faultactor element is to provide information about who
caused the fault to happen within the message path. It indicates the source of
the fault. The value of the faultactor element is a URI that identifies the
source. Applications that are not the ultimate destination of the SOAP
message must include the faultactor element in the SOAP Fault element.
! detail
The detail element is for holding application-specific error information
related to the Body element. It is included if the contents of the Body
element could not be successfully processed. The absence of the detail
element within the Fault element indicates that the fault is not related to
processing of the Body element.
The following example code shows a SOAP fault message that might be
generated when you attempt to withdraw money from a bank account:
1. HTTP/1.0 500 Internal Server Error
2. Content-Length: 460
3. Content-Type: text/xml; charset="utf-8"
4.
5. <soap:Envelope !
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
6. <soap:Body>
7. <soap:Fault>
8. <faultcode>123XYZ</faultcode>
9. <faultstring>Server Error</faultstring>
10. <detail>
11. <bank:faultdetails xmlns:bank="urn:OnlineBank">
12. <message>Your account is overdrawn</message>
13. <errorcode>1234</errorcode>
14. </bank:faultdetails>
15. </detail>
16. </soap:Fault>
17. </soap:Body>
18. </soap:Envelope>
Module 3: The Underlying Technologies of XML Web Services 35
Code example: HTTP The response to the preceding method invocation is returned in an HTTP
response response. The response is in the form of an XML document in the soap:Body
element.
1. HTTP/1.1 200 OK
2. Content-Type: text/xml; charset=utf-8
3. Content-Length: 247
4.
5. <?xml version="1.0" encoding="utf-8"?>
6. <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/">
7. <soap:Body>
8. <GetAccountResponse xmlns="http://woodgrovebank.com">
9. <savingsAcct>
10. <balance>5250.00</balance>
11. </savingsAcct>
12. </GetAccountResponse>
13. </soap:Body>
14. </soap:Envelope>
Module 3: The Underlying Technologies of XML Web Services 37
Both of the preceding encoding rules are optional. Therefore, ASP.NET Web
Services supports SOAP requests and responses that use both of these encoding
rules, along with other variants.
Module 3: The Underlying Technologies of XML Web Services 39
Formatting the SOAP You can format a Web service method within the Body element of a SOAP
body request or a SOAP response by using either RPC encoding or document
encoding. ASP.NET Web Services support both the RPC and document
encoding styles, with document encoding being the default style.
! RPC encoding
The RPC-encoding style formats the Body element according to Section 7
of the SOAP specification. This section explains how to use SOAP for RPC.
In the RPC-encoding style, all parameters are wrapped within a single
element that is named after the Web service method and each element
within that element represents a parameter named after its respective
parameter name.
! Document encoding
The document-encoding style formats the Body element as described in an
XSD schema. If you use the document-encoding style, the service
description for the Web service defines the XSD schemas for both SOAP
requests and SOAP responses to the Web service method. These schemas
are part of WSDL documents, which are explained in detail in Module 4,
“Consuming XML Web Services,” in Course 2524, Developing XML Web
Services Using Microsoft ASP.NET.
In the document-encoding style, clients must send an XML document to a
Web service exactly in the format specified in the associated XSD schemas.
Formatting parameters Because the parameters to a Web service method can make up the bulk of the
data passed in a SOAP request or response, how the parameters are encoded
determines how the XML document will look. There are two encoding styles
for parameters:
! Encoded
This style encodes the parameters by using the SOAP-encoding rules
outlined in Section 5 of the SOAP specification.
! Literal
This style encodes each parameter according to a predefined XSD schema.
You will see how to control encoding of the SOAP document for Web services
and the format of parameters in Module 5, “Implementing a Simple XML Web
Service,” in Course 2524, Developing XML Web Services Using Microsoft
ASP.NET.
40 Module 3: The Underlying Technologies of XML Web Services
C# code example The following code shows how the preceding message can be constructed.
1. public static string BuildSOAPMessage()
2. {
3. MemoryStream st;
4. st = new MemoryStream(1024);
5.
6. XmlTextWriter tr = new XmlTextWriter(st,Encoding.UTF8);
7. tr.WriteStartDocument();
8. tr.WriteStartElement("soap","Envelope",
"http://schemas.xmlsoap.org/soap/envelope/");
9. tr.WriteAttributeString("xmlns","xsi",null,
"http://www.w3.org/2001/XMLSchema-instance");
10. tr.WriteAttributeString("xmlns","xsd",null,
"http://www.w3.org/2001/XMLSchema");
11. tr.WriteAttributeString("xmlns","soap",null,
"http://schemas.xmlsoap.org/soap/envelope/");
12.
13. tr.WriteStartElement("Body",
"http://schemas.xmlsoap.org/soap/envelope/");
14. tr.WriteStartElement(null,"GetAccount",
"http://woodgrovebank.com");
15. tr.WriteElementString("acctNumber","1234");
16. tr.WriteEndElement();
17. tr.WriteEndElement();
18. tr.WriteEndDocument();
19. tr.Flush();
20. ...
21. }
42 Module 3: The Underlying Technologies of XML Web Services
C# code example The following code shows how you can issue the preceding SOAP request by
using the .NET Framework:
1. public static string GetSOAPData(string url,
string action,string content)
{
2. Stream s;
3. HttpWebRequest req = (HttpWebRequest)
WebRequest.Create(url);
4. string hdr = "SOAPAction: \"http://sftsrc.com/"
+ action + "\"";
5. req.Headers.Add(hdr);
6. req.ContentType="text/xml; charset=utf-8";
7. req.Method = "POST";
8. if (content.Length > 0) {
9. req.ContentLength=content.Length;
10. s = req.GetRequestStream();
11. StreamWriter sw = new StreamWriter(s);
12. sw.Write(content);
13. sw.Close();
14. }
15.
16. ...
17. HttpWebResponse res = (HttpWebResponse)
req.GetResponse();
18. return GetResponseAsString(res);
19. ...
20. }
44 Module 3: The Underlying Technologies of XML Web Services
C# code example The following code shows how you can convert the preceding response
message into a string:
1. public static string GetResponseAsString(WebResponse res)
2. {
3. Stream s = res.GetResponseStream();
4. StreamReader sr = new StreamReader(s,Encoding.ASCII);
5. StringBuilder sb = new StringBuilder();
6. char [] data = new char[1024];
7. int nBytes;
8. do {
9. nBytes = sr.Read(data,0,(int)1024);
10. sb.Append(data);
11. } while (nBytes == 1024);
12. return sb.ToString();
13. }
Review
2. If you need an XML entity that can have a default value, should you use an
element or an attribute?
Attribute
4. How are errors reported to a client when using the SOAP protocol?
By using SOAP Fault elements
5. Which SOAP parameter encoding style entails the use of an XSD schema to
encode the parameters?
Literal
48 Module 3: The Underlying Technologies of XML Web Services
Note This lab focuses on the concepts in this module and as a result may not
comply with Microsoft security recommendations. For example, the
Woodgrove and Contoso Web services store their Microsoft SQL Server™
connection strings in the Web.config file, with the sa password in clear text.
The Web.config file for the Woodgrove Web service was also modified to
accept HTTP-GET and HTTP-POST requests.
Lab Setup For each lab exercise in this course, you have the option of coding in either C#
or Visual Basic .NET. In order to avoid unnecessary instructions, the following
placeholders will be used throughout the lab exercises:
install_folder The install folder for the course content. Usually this will be
the folder C:\Program Files\Msdntrain\2524.
lab_root The folder install_folder\Labfiles\CS or
install_folder\Labfiles\VB, depending on the language you
are using for the lab exercises.
It is recommended that you select only one language for the lab exercises.
Module 3: The Underlying Technologies of XML Web Services 49
There are starter and solution files that are associated with this lab. The starter
files are in the folder lab_root\Lab03\Starter. The solution files for this lab are
in the folder lab_root\Lab03\Solution.
Scenario In this lab, you will issue HTTP and SOAP requests to a Web service named
Woodgrove Online Bank. Specifically, you will be constructing requests to
invoke the GetAccount operation of the Web service.
Estimated time to
complete this lab:
45 minutes
50 Module 3: The Underlying Technologies of XML Web Services
Exercise 0
Setting up the Woodgrove Web Service
In this exercise, you will create the virtual directory for the Woodgrove Web
service. You will use either the Visual Basic .NET or C# Woodgrove Web
service depending on your programming language preference.
Exercise 1
Creating the Base Project
In this exercise, you will create a console application named Technology. You
will also add the required namespace declarations so that you can issue HTTP
and SOAP requests. Finally, you will incorporate a helper function (which has
been provided for you) that will assist in displaying the responses to your
requests.
7. For students completing the lab using Microsoft Visual Basic .NET,
perform the following steps:
a. In Solution Explorer, right click the project name.
b. Click Properties.
c. In the Startup object combobox, select Sub Main and click OK.
Note The remainder of the code that you add to the Main method in this
lab must be added immediately after the code just inserted.
Exercise 2
Implementing a Method to Issue HTTP Requests
In this exercise, you will implement a method named GetData that will be used
to issue HTTP requests. This method will be used for HTTP-GET, HTTP-
POST, and SOAP requests.
Exercise 3
Issuing HTTP-GET and HTTP-POST Requests
In this exercise, you will add code to invoke the GetAccount method of the
Web service for the Woodgrove Online Bank by using HTTP-GET and HTTP-
POST requests.
Exercise 4
Completing the BuildSOAPMessage Method
In this exercise, you will complete the code for a method named
BuildSOAPMessage.
Exercise 5
Issuing a SOAP Request
In this exercise, you will add code to invoke the GetAccount operation of the
Web service for the Woodgrove Online Bank by using a SOAP request.
2. Compare the inbound and outbound messages for each of the three request
types.
3. Ensure that each of the different method calls returns the same results:
accountID=1; description=Savings; type=SV; balance=14300;
lastTransaction=2001-09-07T15:46:2200000-07:00; interestRate=2.
4. Press ENTER to close the console application.
THIS PAGE INTENTIONALLY LEFT BLANK
Module 4: Consuming
XML Web Services
Contents
Overview 1
WSDL Documents 2
Lesson: Web Service Discovery 9
Lesson: Web Service Proxies 20
Lesson: Implementing a Web Service
Consumer Using Visual Studio .NET 28
Review 35
Lab 4: Implementing an XML Web Service
Consumer Using Visual Studio .NET 37
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.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 4: Consuming XML Web Services iii
Instructor Notes
Presentation: This module teaches students how to implement XML (Extensible Markup
120 Minutes Language) Web service consumers by using Microsoft® Visual Studio® .NET.
Lab: After completing this module, students will be able to:
75 Minutes
! Explain the structure of a Web Service Description Language (WSDL)
document.
! Explain the Web services discovery process.
! Locate service contracts by using Disco.exe.
! Generate Web service proxies by using Wsdl.exe.
! Implement a Web service consumer by using Visual Studio .NET.
! Invoke a Web service synchronously and asynchronously by using a Web
service proxy.
Required materials To teach this module, you need the Microsoft PowerPoint® file 2524C_04.ppt.
Preparation tasks To prepare for this module:
! Read all of the materials for this module.
! Try the demonstrations and study the code examples in this module.
! Complete the lab.
Dual-language The PowerPoint file for this module contains macros that allow you to switch
PowerPoint macros the displayed code between C# and Microsoft Visual Basic® .NET. To run the
macros, you must install the full version of PowerPoint.
To switch a single slide to C#, perform the following steps:
1. Open the PowerPoint deck in PowerPoint.
2. On the Slide Show menu, click View Show.
3. Locate the slide that you want to switch to C#.
4. Click C# on the slide.
To switch a single slide to Visual Basic .NET, perform the following steps:
1. Open the PowerPoint deck in PowerPoint.
2. On the Slide Show menu, click View Show.
3. Locate the slide that you want to switch to Visual Basic .NET.
4. Click Visual Basic .NET on the slide.
Note You can switch a slide to C# or Visual Basic .NET at any time while
displaying the slides. Just click C# or Visual Basic .NET to switch between the
languages.
iv Module 4: Consuming XML Web Services
Demonstration
This section provides demonstration procedures that will not fit in the margin
notes or are not appropriate for the student notes.
Module Strategy
Use the following strategy to present this module:
! WSDL Documents
You should approach the topics in this section as a progressive development
of an example of a WSDL document. Explain the concepts in the first topic
with a simple Web service that has only one operation that returns a class,
(the code is defined in the student notes). Progressively build upon this
example WSDL document when you explain each of the WSDL topics. The
intent of teaching WSDL syntax is not for students to write a WSDL
document without assistance. The intent is for students to be able to describe
the structure of a WSDL document and explain how the definitions in a
WSDL document correspond to the code that they will implement in a Web
service.
! Web Service Discovery
Explain that this section focuses on how to find WSDL documents and the
endpoints for Web services that implement the interfaces that are defined in
the WSDL documents. For completeness, it is important that you briefly
describe Universal Description, Discovery, and Integration (UDDI) as part
of the solution, but defer any in-depth discussion of UDDI until Module 6,
“Deploying and Publishing XML Web Services,” in Course 2524,
Developing XML Web Services Using Microsoft ASP.NET. Explain how
students can use Disco.exe to generate local copies of WSDL documents
and other discovery documents.
vi Module 4: Consuming XML Web Services
Overview
WSDL Documents
Structure of a WSDL A WSDL document is just a list of definitions. In a WSDL file, the root element
document is named definitions. This element contains five primary child elements that are
used to define the Web service. The following five elements appear within the
definitions element in a WSDL file in the order specified:
! The types element defines the various data types that are used to exchange
messages.
! The message element describes the messages to be communicated.
! The portType element identifies a set of operations and the messages that
are involved with each of those operations.
! The binding element specifies the protocol details for various service
operations and describes how to translate the abstract content of these
messages into a concrete format.
! The service element groups a set of related ports together.
The following describes a Web service for which we want to create a WSDL
file.
C# code example [XmlRoot("account")]
public class Acct
{
[XmlElement("description")]
public string Description;
[XmlElement("number")]
public string Number;
[XmlElement("type")]
public string Type;
[XmlElement("balance")]
public decimal Balance;
[XmlAttribute("status")]
public string Status;
}
The types element In this section, you will learn how to define a WSDL document that describes
the preceding Web service.
First, you define the types that are used in the message exchange. This is mostly
just a matter of defining the types by using XML Schema Definition Language
(XSD). The acctNumber parameter is defined as follows:
...
<types>
...
<s:complexType>
<s:sequence>
<s:element minOccurs="1" maxOccurs="1"
name="acctNumber" nillable="true"
type="s:string" />
</s:sequence>
</s:complexType>
...
</types>
Module 4: Consuming XML Web Services 5
The type definition for the Acct class, which the GetAccount method returns,
is slightly more complex than the previous definition. The type definition for
this class can be as follows:
<s:complexType name="Acct">
<s:sequence>
<s:element minOccurs="1" maxOccurs="1"
name="description" type="s:string" />
<s:element minOccurs="1" maxOccurs="1"
name="number" type="s:string" />
<s:element minOccurs="1" maxOccurs="1"
name="type" type="s:string" />
<s:element minOccurs="1" maxOccurs="1"
name="balance" type="s:decimal" />
</s:sequence>
<s:attribute name="status" type="s:string" />
</s:complexType>
The preceding type definition represents an XML document with the following
structure:
<?xml version="1.0" encoding="utf-8"?>
<account status="active">
<description>Adam's savings acct</description>
<number>1234-XX</number>
<type>SV</type>
<balance>10000</balance>
</account>
Next, we define the structure of the messages that are to be exchanged. In this
example, the method name is GetAccount and we use the following naming
convention:
! The inbound message has the same name as the method.
! The outbound message has the name of the method with the word Response
appended.
6 Module 4: Consuming XML Web Services
The portType element A Web service provider (a network node, which is a Web server) may expose
multiple Web services. A single Web service can support invocation of its
operations by using a variety of protocols. The format of the data that is
exchanged between a Web service consumer and a Web service may depend on
the protocol that is used to invoke an operation or a method. Therefore, there
must be a way to match the operations to the endpoints from which they can be
accessed. You can do this kind of matching by using the portType element.
The following XML code shows the GetAccount operation and a portType
with which it is associated:
<portType name="BankService">
<operation name="GetAccount">
<input message="s0:GetAccountIn" />
<output message="s0:GetAccountOut" />
</operation>
</portType>
In the preceding code, notice that the input and output elements specify the
names of the request and response messages that are to be transmitted.
The binding element After defining the logical port, next you define how a Web service consumer
can bind to the port on which the GetAccount operation is available. This
involves associating an operation with a protocol and providing any protocol-
specific binding information. To do this, you use the binding element. The
following XML code shows the SOAP binding definition for the GetAccount
operation:
<binding name="BankService" type="s0:BankService">
<soap:binding transport =!
"http://schemas.xmlsoap.org/soap/http"
style="document" />
<operation name="GetAccount">b
<soap:operation soapAction = !
"http://woodgrovebank.com/GetAccount"
style="document" />
<input>
<soap:body use="literal" />
</input>
<output>
<soap:body use="literal" />
</output>
</operation>
</binding>
The service element All that remains in creating a WSDL file is defining the endpoints for each of
the protocols that you can use to access a Web service. To define the endpoints,
you use the service element.
The following XML code defines a bank service and specifies the ports that can
be used to access the operations of the service:
<service name="BankService">
<port name="BankService" binding="s0:BankService">
<soap:address location =!
"http://localhost/woodgrove/Bank.asmx" />
</port>
</service>
In the preceding code, the binding attribute of the port element specifies the
name of the binding element that is to be used, in this example,
s0:BankService. Also, notice that the endpoint location is specified as a child
element of the port element.
Note The complete code for the preceding WSDL file is available in
<install folder>\Democode\<language>\Mod04\WoodgroveBank.wsdl.
If you can access a Web service by using multiple protocols, then a WSDL
document for the Web service will contain multiple port elements, each
referring to a protocol-specific binding element by name. Also, each of the
protocol-specific binding elements will in turn refer to protocol-specific
portType elements. The protocol-specific portType elements will in turn refer
to protocol-specific sets of input and output message elements, which in turn
refer to types that the types element defines.
Module 4: Consuming XML Web Services 9
Introducing Disco
Note A Web server that provides access to a Web service is not required to
support discovery. Either another server can be responsible for providing the
service contracts, or a Web service has been created for only private use with no
public mechanism for discovery.
Static discovery Static discovery is possible when the location of a discovery document (usually
with the extension .disco) is already known. Static discovery involves retrieving
the discovery document and interpreting its contents. The following code is an
example of a discovery document:
<?xml version="1.0"?>
<discovery xmlns:xsi="http://www.w3.org/2000/10/!
XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2000/10/XMLSchema/"
xmlns="http://schemas.xmlsoap.org/disco/">
<discoveryRef ref="http://www.contoso.com/MicroPayment!
/MicroPayment.vsdisco"/>
<discoveryRef ref="http://www.contoso.com/Services/!
AccountMgmt.disco"/>
<contractRef ref="http://www.contoso.com/Services/!
AcctMgmt.asmx?wsdl"
docRef="http://www.contoso.com/Services/!
AcctMgmt.asmx"!
xmlns="http://schemas.xmlsoap.org/disco/scl/"/>
</discovery>
In a discovery document, the URLs that specify the various document locations
can be absolute or relative. If the URLs are relative, then the locations are
assumed to be relative to the location of the discovery document.
The root discovery document along with all the referenced discovery
documents make up the catalog of Web services that are available at the
interrogated endpoint. This catalog is effectively static.
Dynamic discovery Dynamic discovery takes place when all that is known to the consumer is the
endpoint of the Web service provider. In this situation, there is no static list of
.disco files at the endpoint. Instead, the list of available Web services and the
associated service contracts must be dynamically generated.
The dynamic discovery of Web services is disabled by default. You can enable
it by removing the comment for .vsdisco httpHandler in either machine.config
or web.config.
<httpHandlers>
<!--<add verb="*" path="*.vsdisco"
type=
!"System.Web.Services.Discovery.DiscoveryRequestHandler,
!System.Web.Services,
!Version=1.0.3300.0,Culture=neutral,
!PublicKeyToken=b03f5f7f11d50a3a" validate="false"
/>-->
12 Module 4: Consuming XML Web Services
You also must place a file named Default.vsdisco at the root of the Web site
that hosts a Web service. If you install Visual Studio .NET on a computer,
Default.vsdisco will be placed in the folder containing the root of the
computer’s default Web site. The following code is an example of a .vsdisco
file:
<?xml version="1.0" ?>
<dynamicDiscovery xmlns="urn:schemas-
dynamicdiscovery:disco.2000-03-17">
<exclude path="_vti_cnf" />
<exclude path="_vti_pvt" />
<exclude path="_vti_log" />
<exclude path="_vti_script" />
<exclude path="_vti_txt" />
</dynamicDiscovery>
It is not difficult to see the similarity between .disco files and WS-Inspection
documents.
The WS-Inspection specification may be found at:
http://msdn.microsoft.com/library/default.asp?url=/library/
en-us/dnsrvspec/html/ws-inspection.asp
Implementations, tools, and samples are available as part of Visual Studio .NET
and may be found at:
http://msdn.microsoft.com/code/default.asp?url=/code/sample.asp?url=/
msdn-files/026/002/541/msdncompositedoc.xml
14 Module 4: Consuming XML Web Services
The options for the URL argument that the disco command supports are
described in the following table.
Options Description
Uses for Disco.exe The primary use of Disco.exe is to generate local copies of service contract
documents (.wsdl documents) and static discovery documents (.disco
documents). The tool also produces a file named Results.discomap. This file
can be used as the input to the Wsdl.exe, which you will examine later in this
module.
The Disco tool displays an error message if it cannot find discoverable
resources at the supplied URL.
The following example shows how to use Disco.exe to search a URL for
discovery documents and save them to a local folder:
disco /out:d:\disco /u:administrator /p:biffle!
http://localhost/woodgrove/catalog.disco
In the preceding example, the username and password are supplied to allow the
tool to connect to a server that requires authentication.
16 Module 4: Consuming XML Web Services
Programmatic Discovery
DiscoveryClientResultCollection results;
results =
client.WriteAll(outputDirectory,"results.discomap");
foreach (DiscoveryClientResult res in results)
{
Console.WriteLine(res.Filename + " <- " + res.Url);
}
}
}
Module 4: Consuming XML Web Services 19
Using WSDL to generate Because WSDL documents are XML documents, it is easy to generate
proxies language-specific proxies to Web services. It is also easy to match the types
defined in the WSDL document to types that are native to the language of the
consumer that uses the proxy.
Earlier in this module, in the topic on WSDL, you learned how to create the
XSD representation of the following class definition.
C# code example public class Acct
{
public string Description;
public string Number;
public string Type;
public decimal Balance;
public string Status;
}
The arguments and options for the path that the wsdl command supports are
described in the following table.
Options Description
C# and Visual Basic The following example generates a proxy by using the default language (C#)
.NET examples and default protocol (SOAP).
wsdl http://localhost/woodgrove/bank.asmx?wsdl
Proxy class details A proxy class that Wsdl.exe generates exposes both synchronous and
asynchronous methods for each of the operations in a Web service. For
example, if a Web service supports an operation named GetAccount, then a
proxy class for this Web service will contain the methods GetAccount,
BeginGetAccount, and EndGetAccount. The GetAccount method is used to
invoke the XML Web service synchronously and the
BeginGetAccount/EndGetAccount pair is used to invoke the Web service
asynchronously. You will see how to make both synchronous and asynchronous
calls to a Web service later in this module.
Each of the methods in a proxy class correctly formats the messages and parses
the responses. These tasks include translating data between XML and the .NET
runtime supported types.
The methods in the proxy class also contain details on the network
communication to be used. By default, the proxy classes use SOAP to invoke a
Web service method. The proxy classes use SOAP because SOAP supports the
richest set of data types in comparison with the other two supported protocols.
However, if a Web service can only be called by using HTTP-GET or HTTP-
POST protocols, then Wsdl.exe can also generate proxy classes that support
these protocols.
If errors occur during a call to a Web service, then the proxy class throws
standard .NET exceptions.
The proxy class is derived from a protocol-specific class, which is derived from
the HttpWebClientProtocol class. For more information about proxy classes,
refer to the .NET Framework SDK documentation.
26 Module 4: Consuming XML Web Services
Configuring Proxies
The following example code shows how to supply credential details by using
the Credentials property.
C# code example ICredentials credentials = new NetworkCredential("Adam",
"ABarr-user", "woodgrovebank.com");
theBank.Credentials = credentials;
Timeout property You use the Timeout property to modify the default timeout for synchronous
invocations of the Web service method. When you modify the Timeout
property, it applies to all subsequent requests made with the same instance of
the proxy class, until it is modified again.
Note Even though a Web service consumer can set the Timeout property to
infinity, a Web server can still force the request to time out on the server side.
The following example sets the timeout on the client side to 20 seconds.
C# code example theBank.Timeout = 20000;
Visual Basic .NET code 'Set the proxy server to proxyserver, port to 80, and specify
example 'that proxy server must be bypassed for local addresses
IWebProxy proxyObject = new WebProxy _
("http://proxyserver:80", true)
theBank.Proxy = proxyObject
Visual Basic .NET code 'Allow the server to automatically redirect the request
example theBank.AllowAutoRedirect = true
28 Module 4: Consuming XML Web Services
The type of application that you implement has very little effect on the
mechanics of consuming a Web service.
For all Web service consumers, the basic steps involved in consuming a Web
service are as follows:
1. Create a proxy class for the Web service.
2. Reference the proxy class in the application code.
3. Create an instance of the proxy class in the application code.
4. Invoke a Web service method by using the instance of the proxy class.
In the next two topics, you will see demonstrations on how to implement a
console application client and a Web Forms client.
Note The Web service consumers that you will implement in this course are
.NET applications.
Module 4: Consuming XML Web Services 29
2. In the Main function, add the following code to invoke the GetAccount
method of the Woodgrove Web service.
C# WoodgroveOnlineBank bank = new WoodgroveOnlineBank();
Acct acct;
acct = bank.GetAccount(1);
Console.WriteLine(
"The account '{0}' has a balance of {1:C}",
acct.description, acct.balance);
Console.ReadLine();
2. In the Page_Load event, add the following code to invoke the GetAccount
method of the Woodgrove Web service and display the account balance.
C# WoodgroveOnlineBank bank = new WoodgroveOnlineBank();
Acct acct;
acct = bank.GetAccount(1);
Response.Write(string.Format
("The account '{0}' has a balance of {1:C}",
acct.description, acct.balance));
3. Build the ASP.NET Web application and then browse the WebForm1.aspx
page.
Module 4: Consuming XML Web Services 33
3. When the callback delegate is invoked, access the proxy reference that is
passed to the Beginxxxx method through the IAsyncResult.AsyncState
property.
4. Use the proxy reference to call the Endxxxx method to complete the
asynchronous call.
C# and Visual Basic The following code shows how to make an asynchronous call to a Web service
.NET examples by using a proxy.
C# code example class TheConsumer
{
static void Callback(IAsyncResult ar)
{
OnlineBank bank = (OnlineBank) ar.AsyncState;
Acct acct = bank.EndGetAccount(ar);
Console.WriteLine(
"The account '{0}' has a balance of {1:C}",
acct.description, acct.balance);
}
static void Main(string[] args)
{
OnlineBank bank = new OnlineBank();
AsyncCallback callback;
callback = new AsyncCallback(TheConsumer.Callback);
bank.BeginGetAccount("1234",callback,bank);
Console.ReadLine();
}
}
Review
3. Which tool can you use to generate client proxies for Web services?
Wsdl.exe or Visual Studio .NET
36 Module 4: Consuming XML Web Services
4. Which tool can use a WSDL document to generate a class implementing the
operations of the Web service that are described in the WSDL document?
Wsdl.exe
5. When you add a Web reference to a client application, how are the types
that are exposed by the Web service exposed in the client application?
They are exposed in a nested namespace that is a child of the default
namespace of the client application.
Module 4: Consuming XML Web Services 37
Note This lab focuses on the concepts in this module and as a result may not
comply with Microsoft security recommendations. For example, the
Woodgrove Web Service uses the Microsoft SQL Server™ sa account to
connect to SQL Server and stores the password in the Web.config file.
Lab Setup For each lab exercise in this course, you have the option of coding in either C#
or Visual Basic .NET. To avoid unnecessary instructions, the following
placeholders will be used throughout the lab exercises:
install_folder The install folder for the course content. Usually this will
be the folder C:\Program Files\Msdntrain\2524.
lab_root The folder install_folder\Labfiles\CS or
install_folder\Labfiles\VB, depending on the language you
are using for the lab exercises.
It is recommended that you select only one language for the lab exercises
There are starter and solution files that are associated with this lab. The starter
files are in the folder lab_root\Lab04\Starter. The solution files for this lab are
in the folder lab_root\Lab04\Solution.
38 Module 4: Consuming XML Web Services
Scenario In this lab, you are provided with a Microsoft Visual Studio .NET Windows
application as a starting point. The application is named Woodgrove and
Contoso Account Manager, as shown in the following illustration.
This application is a client to two Web services: the Woodgrove Online Bank
Web service and the Contoso Micropayment Web service. These Web services
are described as follows:
! Woodgrove Online Bank
A bank that provides traditional online services such as account balances.
The bank’s services are made available through a Web service.
! Contoso Micropayment Service
A micropayment service (similar to Microsoft Wallet) that manages
accounts for users who do not want to provide their personal financial
information to all of the e-commerce sites at which they shop. The account
management features of this service are also exposed as a Web service.
You will locate the WSDL service contract for the Woodgrove Online Bank
Web service by using Visual Studio .NET, and then create a Web service proxy
class. You will then modify the client application to use the following
Woodgrove Online Bank Web service methods:
! GetAllAccounts
! GetAccount
! GetTransactionHistory
Estimated time to
complete this lab:
75 minutes
40 Module 4: Consuming XML Web Services
Exercise 0
Setting up the Woodgrove Web Service
If you did not previously create a virtual directory for the Woodgrove Web
service, do so now.
Exercise 1
Locating a WSDL Service Contract and Generating a Web
Service Proxy
In this exercise, you will examine the Woodgrove Online Bank Web service
functionality. Then, you will locate the WSDL service contract for the
Woodgrove Online Bank Web service and then generate a Web service proxy to
use it.
accountID 1
startDate 1/1/2001
endDate 1/1/2010
In the following two procedures of this exercise, you will enable the client
application to use the GetAllAccounts, GetAccount, and
GetTransactionHistory methods.
3. Close the browser windows.
Exercise 2
Invoking a Web Service Method
In this exercise, you will add code to invoke the GetAllAccounts method of the
WoodgroveOnlineBank proxy class to populate the Account Information list.
3. Build and run the Woodgrove and Contoso Account Manager application.
The Accounts for Customer list box in the WoodGrove Online Bank
group box will display a list of account IDs.
4. Close the Woodgrove and Contoso Account Manager application.
44 Module 4: Consuming XML Web Services
Exercise 3
Using a Web Service Method That Returns Derived Types
In this exercise, you will add code to invoke the GetAccount method of the
WoodgroveOnlineBank proxy class to fill the Account Information text box.
The GetAccount method returns an object derived from the type Acct.
4. If the type data member has the value SV, then the object is a SavingsAcct
object. Therefore, do the following:
a. Cast the Acct object to a SavingsAcct object.
C# SavingsAcct acctSV = acct as SavingsAcct;
7. In the Accounts for Customer list, select one of the listed account
numbers.
You should see account information similar to the following in the Account
Information text box that is contained in the WoodGrove Online Bank
group box:
Exercise 4
Using a Web Service Method That Returns an ADO.NET Typed
Dataset
In this exercise, you will add code to invoke the GetTransactionHistory
method for the WoodgroveOnlineBank proxy class. This method returns an
ADO.NET typed DataSet, the class TransactionDataSet.
3. Click OK, and then close the Woodgrove and Contoso Account Manager
application.
Module 5: Implementing a
Simple XML Web Service
Contents
Overview 1
Lesson: Creating a Web Service Project 2
Lesson: Implementing Web Service
Methods 10
Lesson: Managing State in an ASP.NET
Web Service 33
Lesson: Debugging Web Services 42
Review 62
Lab 5: Implementing a Simple XML
Web Service 64
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.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 5: Implementing a Simple XML Web Service iii
Instructor Notes
Presentation: This module provides students with the skills that are required to implement an
150 Minutes XML (Extensible Markup Language) Web service by using Microsoft® Visual
Studio® .NET and debug it. Students will also modify the solution to Lab 4,
Lab: “Implementing an XML Web Service Consumer Using Visual Studio .NET,” in
75 Minutes Course 2524, Developing XML Web Services Using Microsoft ASP.NET, to
communicate with the Web service that 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.
Required Materials To teach this module, you need the Microsoft PowerPoint® file 2524C_05.ppt.
Preparation Tasks To prepare for this module:
! Read all of the materials for this module.
! Try the demonstrations and study the code examples in this module.
! Complete the lab.
iv Module 5: Implementing a Simple XML Web Service
Demonstration
This section provides demonstration procedures that are not appropriate for the
student notes.
Creating a Web Service 1. Open Visual Studio .NET.
Project
2. On the File menu, point to New, and click Project.
3. Select the language of your choice, then select the ASP.NET Web Service
project template. Set the project location to
http://localhost/FirstWebService. Click OK to begin.
4. Open the Service1.asmx code-behind file:
a. In Solution Explorer, right-click Service1.asmx.
b. On the shortcut menu, click View Code.
5. Locate the HelloWorld method.
6. Uncomment the method.
7. Compile and run the Web service.
8. Click the HelloWorld link.
9. Click Invoke.
10. Close all Microsoft Internet Explorer windows and Visual Studio .NET.
Module Strategy
Use the following strategy to present this module:
! Creating a Web Service Project
This lesson provides an overview of the mechanics of implementing a
simple Web service by using the ASP.NET Web Service project template. It
also explains the purpose of each of the files that are generated for the
default Web service project.
! Implementing Web Service Methods
This lesson 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 discuss the tradeoffs between the various options for representing
parameter lists. Defer this discussion until Module 8, “Designing XML Web
Services,” in Course 2524, Developing XML Web Services Using Microsoft
ASP.NET.
Be sure to practice the Component Designer and XML Designer
demonstrations in this section.
! Managing State in an ASP.NET Web Service
This lesson 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 Active Server Pages (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 XML Web
Services,” in Course 2524, Developing XML Web Services Using Microsoft
ASP.NET.
! Debugging Web Services
This lesson is intended to familiarize students with various tools and
techniques available for debugging Web services. The simplest debugging
tools that this section covers 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 lesson provides a brief overview of application- and
page-level tracing using Trace.axd, an event log, and performance counters.
Focus on the mechanics and not on the issues that are related to
performance, scaling, and deployment.
Module 5: Implementing a Simple XML Web Service 1
Overview
System.Web.Services The System.Web.Services namespace consists of classes that help you to build
namespace 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 by using XSD.
! XML Path Language (XPath) expressions
The XPathNavigator class provides read-only, random access to XML
documents by using XPath expressions.
! Extensible Stylesheet Language Transformations (XSLT)
XSLT allows you to transform XML data by using XSLT style sheets.
! 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
You can find the classes that encapsulate SOAP support in the .NET
Framework in the System.Web.Services.Protocols namespace.
The .asmx file The .asmx file is the front-end for a Web service that is implemented by using
ASP.NET. The way that you access this file through HTTP determines the type
of response that you receive.
By default, the .asmx file contains a class that is similar to the following
example class.
C# code example public class Service1 : System.Web.Services.WebService
{
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 Web service methods 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.
A Service Help page also contains a link to the corresponding Web service
description document as shown in the following illustration:
The Service Method The Service Method Help page of a Web service provides additional
Help page information about a specific method of the Web service.
The page also allows you to invoke the method if it can be invoked by using the
HTTP-POST protocol.
Sample request and response messages for the protocols that the Web service
method supports are provided at the bottom of the Service Method Help page.
The following illustration shows the Service Method Help page.
The Service Description The service description for a Web service is a Web Services Description
page 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 that you access a Service Help page. However, you also must supply
the query string WSDL as shown in the following example:
http://servername/projectname/webservicename.asmx?WSDL
8 Module 5: Implementing a Simple XML Web Service
The .vsdisco file The .vsdisco file is a dynamic discovery document. When you deploy a Web
service into a production environment you should only deploy the .vsdisco file
if you want the Web service to be dynamically discoverable. This is generally
not recommended.
AssemblyInfo (.cs or AssemblyInfo (.cs or .vb) is a project information file that contains metadata,
.vb) 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 AssemblyInfo, see Course 2350A, Securing and Deploying
Microsoft .NET 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.
10 Module 5: Implementing a Simple XML Web Service
Note Even if a Web service method is specified as public, you still must attach
the WebMethod attribute to expose it as part of a Web service.
Configuring the You can control the behavior of a Web service method by configuring the
WebMethod attribute properties of the WebMethod attribute.
properties
The WebMethod attribute has the following properties:
! BufferResponse
! CacheDuration
! Description
! EnableSession
! MessageName
! TransactionOption
12 Module 5: Implementing a Simple XML Web Service
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 an XML Web Service,” in Course 2524,
Developing XML Web Services Using Microsoft ASP.NET.
You can set the CacheDuration property as shown in the following example.
C# code example [WebMethod(CacheDuration=60)]
public double ConvertTemperature(double dFahrenheit){
return ((dFahrenheit - 32) * 5) / 9;
}
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.
Module 5: Implementing a Simple XML Web Service 13
You can set the Description property as shown in the following example.
C# code example [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 the HttpContext.Current.Session
property 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 in general from
the perspective of performance and scalability, see Module 8, “Designing XML
Web Services,” in Course 2524, Developing XML Web Services Using
Microsoft ASP.NET.
You can set the EnableSession property as shown in the following example.
C# code example [WebMethod(EnableSession=true)]
public double ConvertTemperature(double dFahrenheit) {
Session["NumberOfConversions"] =
(int)Session["NumberOfConversions"] + 1;
return ((dFahrenheit - 32) * 5) / 9;
}
[WebMethod(EnableSession=true)]
public int GetNumberOfConversions() {
return (int)Session["NumberOfConversions"];
}
<WebMethod(EnableSession := True)> _
Public Function GetNumberOfConversions() As Integer
Return Session("NumberOfConversions")
End Function 'GetNumberOfConversions
14 Module 5: Implementing a Simple XML Web Service
MessageName The MessageName property enables the Web service to uniquely identify
overloaded methods by 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.
C# code example [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;
}
<WebMethod(MessageName := "AddIntegers")> _
Public Function Add(iValueOne As Integer, iValueTwo As _
Integer) As Integer
Return iValueOne + iValueTwo
End Function 'Add
The AddDoubles SOAP request message for the method that adds two values
that are of type System.Double will resemble the following:
POST /myWebService/Service1.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/AddDoubles"
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.
The AddDoubles SOAP response message for the method would resemble the
following code:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope namespaces omitted for brevity>
<soap:Body>
<AddDoublesResponse xmlns="http://tempuri.org/">
<AddDoublesResult>double</AddDoublesResult>
</AddDoublesResponse>
</soap:Body>
</soap:Envelope>
In the following procedure, you will learn how to configure a Web service
method to initiate a new MS DTC transaction.
To initiate a new DTC transaction:
1. Add a reference to System.EnterpriseServices.dll.
2. Add the System.EnterpriseServices namespace to the Web service.
3. Use the TransactionOption property as shown in the following code:
C# code example public class Service1 : System.Web.Services.WebService
{
[WebMethod(TransactionOption=
TransactionOption.RequiresNew)]
public string DoSomethingTransactional()
{
// The transaction was successful
ContextUtil.SetComplete();
return ContextUtil.TransactionId.ToString();
}
}
<WebMethod(TransactionOption := _
TransactionOption.RequiresNew)> _
Public Function DoSomethingTransactional() As String
' The transaction was successful
ContextUtil.SetComplete()
Return ContextUtil.TransactionId.ToString()
End Function 'DoSomethingTransactional
End Class 'Service1
Module 5: Implementing a Simple XML Web Service 17
Examples 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:
C# code example [WebMethod]
public int ListOfString(params string [] list)
{
return list.Length;
}
[WebMethod]
public int ListOfThings(params object [] list)
{
return list.Length;
}
<WebMethod()> _
Public Function ListOfThings(ParamArray list() As Object) _
As Integer
Return list.Length
End Function 'ListOfThings
By default, the Web service proxy methods that are 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 code.
C# code example public int ListOfThings(object[] list) {
object[] results = this.Invoke("ListOfThings",
new object[]{list});
return ((int)(results[0]));
}
To call a method with a variable length argument list, you must manually add
the params keyword for C# and the ParamArray keyword for Visual Basic
.NET as shown in the following code.
C# code example public int ListOfThings(params object[] list) {
object[] results = this.Invoke("ListOfThings",
new object[] {list});
return ((int)(results[0]));
}
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
argument lists.
C# code example 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 data types For Web services to be widely adopted, it is necessary that Web service
methods support complex data types as arguments and return values in addition
to supporting simple data types. This section examines some examples of Web
service methods that use complex data types.
20 Module 5: Implementing a Simple XML Web Service
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.
When an instance of a class is passed between a Web service consumer and a
Web service, the state of the object is serialized. The state that is serialized
includes all read/write public properties and all read/write public fields.
Any class that is used as an argument to a Web service method must also have a
default constructor. This is because, internally, the Web services infrastructure
must be able to rebuild the object when it is passed into a Web service. Unlike
classes, structures always have a default constructor, and therefore you do not
have to define a default constructor to use a structure as a parameter for a Web
service method.
Arrays Arrays of simple types, structures, and classes require no special treatment.
However, if you pass in or return an array of object references that include
references to derived objects, you must explicitly specify all the possible types
for objects that can be in the array. The types are specified by using the
XmlInclude attribute. If the types are not specified, then an exception will be
thrown when the array is serialized.
Consider the following class definitions.
C# code example public class Acct
{
public string Description;
public string Number;
public string Type;
public decimal Balance;
public string Status;
}
Collections You must treat collections in the same way as arrays of objects. The following
code is an example of a Web service method returning an ArrayList of Acct,
where the actual elements are derived from Acct.
C# code example [WebMethod]
[XmlInclude(typeof(CreditCardAcct))]
[XmlInclude(typeof(SavingsAcct))]
[return:XmlArray("AccountList")]
[return:XmlArrayItem("Account")]
public ArrayList GetAllAccounts()
{
SavingsAcct a = new SavingsAcct();
CreditCardAcct cc = new CreditCardAcct();
// populate accounts
ArrayList listOfAccts = new ArrayList();
listOfAccts.Add(a);
listOfAccts.Add(cc);
return listOfAccts;
}
Visual Studio .NET provides the following tools to generate typed DataSets:
! The Component Designer
! The XML Designer
To select the correct tool for your requirements, you must be aware of the
limitations of both of these tools.
The disadvantages of using the Component Designer are:
! Initially, you have no direct control over the schema. You can control a
DataSet definition only by configuring the data adapter from which Visual
Studio .NET generates the schema. After generating the schema, you can
edit it by using the XML Designer.
! You must manually regenerate the schema and its corresponding DataSet
class file after changing a data adapter.
For example, if you change the Structured Query Language (SQL) statement
that is used to fill a DataSet, then you must change the schema of the
DataSet also.
! There are some DataSet functions that you cannot perform by using the
Component Designer, such as defining DataRelation objects. In such cases,
you must use the XML Designer.
The following example code shows a Web service method returning a typed
DataSet.
C# code example [WebMethod]
public TransactionHistory GetTransactionHistory
(int accountID, DateTime startDate,DateTime endDate)
{
string connString = (string)
ConfigurationSettings.AppSettings["connectString"];
adapter.SelectCommand = cmd;
TransactionHistory ds = new TransactionHistory();
adapter.Fill(ds);
conn.Close();
return ds;
}
adapter.SelectCommand = cmd
Dim ds As New TransactionHistory()
adapter.Fill(ds)
conn.Close()
Return ds
End Function
26 Module 5: Implementing a Simple XML Web Service
Note One important issue that you must be aware of is that any changes to the
schema of a typed DataSet after it is created may not be passed between a Web
service and a client.
For example, if you have a typed DataSet containing typed tables named
Customers and Orders, then if you add a non-typed table named Table1 by
using the DataSet.Tables.Add method-for example, ds.Tables.Add("Table1") -
then Table1 may not be propagated back to the client.
Module 5: Implementing a Simple XML Web Service 27
d. When prompted, type the password again, and then click OK.
e. On the Choose Your Data Connection page, click Next.
f. On the Choose a Query Type page, select Use existing stored
procedures and click Next.
g. On the Bind Commands to Existing Stored Procedures page, in the
Select list, click _GetAccount. Leave the Insert, Update, and Delete
lists empty, and then click Next.
h. When prompted, enter the SQL Server user name and password again,
and then click OK.
i. On the View Wizard Results page, click Finish.
Two controls named SqlDataAdapter1 and SqlConnection1 appear in
the Design view of the .asmx page.
6. Click the XML tab to see the XML code that has been added:
<xs:simpleType name="stateCode">
<xs:restriction base="xs:string">
<xs:length value="2" />
</xs:restriction>
</xs:simpleType>
8. Click the XML tab to see the XML code that has been added to your .xsd
file.
You will see the following code:
<xs:complexType name="address">
<xs:sequence>
<xs:element name="street" type="xs:string" />
<xs:element name="state" type="stateCode" />
</xs:sequence>
</xs:complexType>
Application State
Using application state Application-state variables are global variables for a given ASP.NET
application. Just like client-side application developers, ASP.NET programmers
should always consider the impact of storing any data globally.
Because of the following considerations, the use of application state is generally
discouraged in a Web service that must scale. The following issues are
specifically important in the context of Web services:
! The memory that is occupied by variables stored in application state is not
released until the value is either removed or replaced.
Storing rarely-used, large DataSets in application state is not an efficient use
of system resources.
! Multiple threads within an application can access values stored in an
application state simultaneously. Therefore, you should always carefully
ensure that access to read/write data that is stored in application state is
always serialized.
! Because locks that protect global resources are themselves global, code
running on multiple threads and accessing global resources could experience
lock contention. Lock contention causes the operating system to block the
worker threads until the lock becomes available.
In high-load server environments, this blocking can cause severe thrashing
in the thread scheduler.
! The .NET application domain or a process hosting a .NET application can
be shut down and destroyed at any moment during application execution as
a result of failures, code updates, scheduled process restarts, and other
issues or processes.
Because global data stored in application state is not durable, you can
possibly lose the data if the AppDomain host is shut down. If you want to
prevent loss of state information due to these types of failures, then it is
recommended that you store it in a database or some other durable store.
! Application state is not shared across a Web farm (in which an application is
hosted by multiple servers) or a Web garden (in which an application is
hosted by multiple processes on the same server).
Variables stored in application state in either of these scenarios are global
only to the particular process in which the application is running. Each
application process can have different values. Therefore, you cannot rely on
application state to store unique values or update global counters in
scenarios that use Web farms or Web gardens.
Application state The HttpApplicationState class exposes two state collections: Contents and
collections StaticObjects.
The Contents collection exposes all variable items that have been added to the
application-state collection directly through code, as shown in the following
example.
C# code example Application["Message"] = "Bar";
Application["AppStartTime"] = DateTime.Now;
For compatibility with earlier versions of ASP, you can also access these
variables through an actual Contents property of the Application object, as in
the following example.
C# code example Application.Contents["Message"] = "Bar";
Application.Contents["AppStartTime"] = DateTime.Now;
Application state Multiple threads within an application can simultaneously access values that are
synchronization stored in an application state. The HttpApplicationState class provides two
methods, Lock and Unlock, which serialize access to application state
variables.
The following example code shows the use of locking to guard against race
conditions.
C# code example // Protecting shared application state via locking
Application.Lock();
Application["SomeGlobalCounter"] =
(int)Application["SomeGlobalCounter"] + 1;
Application.UnLock();
Visual Basic .NET code ' Protecting shared application state via locking
example Application.Lock()
Application("SomeGlobalCounter") = _
CInt(Application("SomeGlobalCounter")) + 1
Application.UnLock()
If you do not explicitly call the Unlock method, the .NET Framework
automatically removes the lock when either the request completes or times out,
or when an unhandled error occurs during request execution and causes the
request to fail. This automatic unlocking prevents the application from
deadlocking.
38 Module 5: Implementing a Simple XML Web Service
Session State
Most developers would not expect that in the preceding code, the balance
retrieved the second time would be unrelated to the balance that was initially
retrieved. Neither would they expect that the Deposit method invocation would
have no effect on the subsequent balance retrieval.
Building Web services that must maintain some cross-request state information
can be extremely difficult without assistance from tools.
Module 5: Implementing a Simple XML Web Service 39
ASP.NET support for ASP.NET provides the following support for session state:
session state
! A session-state facility that is easy to use, familiar to ASP developers, and
consistent with other .NET Framework APIs.
! A reliable session-state facility that can survive IIS restarts and worker-
process restarts without losing session data.
! A scalable session-state facility that administrators can use in both Web
farm and Web garden scenarios, and that enables administrators to allocate
more processors to a Web application to improve its scalability.
! A session-state facility that works with browsers that do not support HTTP
cookies.
Identifying a session Each active ASP.NET session is identified and tracked by using a 120-bit
SessionID string containing URL-legal ASCII characters. SessionID values are
generated by using an algorithm that guarantees uniqueness so that sessions do
not collide. The algorithm also guarantees randomness so that a malicious user
cannot use a new SessionID to calculate the SessionID of an existing session.
SessionIDs are communicated across client-server requests either by means of
an HTTP cookie or a modified URL, depending on how you set the
application’s configuration settings.
Using session state ASP.NET session state is an in-memory cache of object references that live
within the IIS process. However, the .NET state server stores chunks of binary
data, either in memory or in a SQL Server database. ASP.NET worker
processes are then able to take advantage of this simple storage service by
serializing and saving (using .NET serialization services) all objects within a
client’s Session collection at the end of each Web request. When the client
revisits the server, the relevant ASP.NET worker process retrieves these objects
from the state server as binary streams, de-serializes them into live instances,
and places them back into a new Session collection object exposed to the
request handler.
You can also use an ASP.NET application to store session-state in a SQL
Server database. ASP.NET worker processes then store serialized session data
in a temporary table, which an ASP.NET worker process accesses by a
combination of stored procedures in the database and the managed data access
components for SQL Server.
By cleanly separating the storage of session data from its use, ASP.NET
supports several powerful scenarios that were unavailable with earlier versions
of ASP. These include:
! Because the memory that session state uses is not within the ASP.NET
worker process, it can recover from application failure.
This means state is not lost if the process crashes due to an access violation,
or is forcibly restarted by the IIS Admin Service in the event of a deadlock
or a memory leakage.
40 Module 5: Implementing a Simple XML Web Service
! Because all state is stored separately from running user code, it is not lost
during the regular preventive restarts of each worker process after a
specified interval.
ASP.NET performs preventive restarts every 20 minutes or 5,000 requests
to help prevent problems resulting from memory leakages, handle leakages,
cache irregularities, and other similar issues. This automatic purging process
can dramatically improve the perceived availability and reliability of an
application, but it does not affect state information that is stored on a
separate server.
! Because all state is stored separately from worker processes, you can
cleanly partition an application across multiple processes.
Such partitioning can dramatically improve both the availability and the
scalability of an application on multi-processor computers. Moreover,
because it associates each worker process with a single computer, ASP.NET
is able to eliminate cross-processor lock contention, which is one of the
major scalability bottlenecks in the earlier versions of ASP.
! Because all state is stored separately from worker processes, you can
partition an application across multiple worker processes running on
multiple computers.
The model for communicating state between a worker process and a state
service running on different computers is almost the same as that for
processes and servers running on the same computer.
Session state The SessionState class exposes two state collections: Contents and
collections StaticObjects. The syntax for using these two collections is very similar to the
syntax for their counterparts in the HttpApplicationState class.
Session state The session state module is inserted in the HTTP request. By default, it is
configuration inserted at the root of the configuration hierarchy in the Machine.config file.
<httpmodules>
<add name="Session" type =
"System.Web.SessionState.SessionStateModule, System.Web"
/>
</httpmodules>
Run-time parameters for the session state service are set as attributes of the
sessionState element.
Cookieless sessions Using session state no longer requires that the client support cookies. You can
enable cookieless sessions by setting the following attribute of sessionState:
<configuration>
<system.web>
<sessionState cookieless="true"/>
</system.web>
</configuration>
Module 5: Implementing a Simple XML Web Service 41
C# and Visual Basic The following example shows how to access existing session-state data in a
.NET code examples read-only manner. In this example, a customer’s current account balances are
stored in session state.
C# code example <%@ WebService Language="C#" EnableSessionState="true" %>
[WebMethod]
public DataSet GetCurrentBalances(string acctID)
{
DataSet balances;
balances = (DataSet) Session["CurrentBalances"];
if (balances == null)
{
// retrieve current balances from database
balances = GetCurrentBalancesLive(acctID);
Session["CurrentBalances"] = balances;
}
return balances;
}
Trace switches A trace switch is an object, which is an instance of the Switch class. One type
of Switch class is the BooleanSwitch class, which acts as a toggle switch, by
either enabling or disabling a variety of trace statements. Another type of switch
class is the TraceSwitch class, which allows you to enable a trace switch for a
particular tracing level so that the trace messages specified for that level and all
levels below it will be output. If you disable the switch, the trace messages will
not be output.
Typically, a deployed application is executed with its switches disabled, so that
the users do not find irrelevant trace messages appearing on a screen or filling
up a log file as the application runs. If a problem arises during program
execution, you can stop the application, enable the switches, and restart the
application. Then the tracing messages are displayed.
The TraceSwitch Class A TraceSwitch object has four properties that return Boolean values indicating
whether the switch is set to at least a particular level:
! TraceError
! TraceWarning
! TraceInfo
! TraceVerbose
Note The TraceSwitch properties indicate the maximum trace level for the
switch. That is, tracing information is written for the level specified and for all
the lower levels under the specified level.
Assert The specified text; or, if none is specified, the call stack
Fail The specified text, written to the default Trace output
Write The specified text
WriteIf The specified text, if the condition specified as an argument
in the WriteIf method is satisfied
WriteLine The specified text and a carriage return
WriteLineIf The specified text and a carriage return, if the condition
specified as an argument in the WriteLineIf methods
satisfied
Module 5: Implementing a Simple XML Web Service 45
Debug and Trace share the same Listeners collection, so if you add a listener
object to a Debug.Listeners collection in your application, it is added to the
Trace.Listeners collection also. As a result, any listener in the Listeners
collection receives the same message from the trace output methods.
The following code shows how to add two listeners, one to send debug output
to the console, and the other to send debug output to a text file.
C# code example Trace.Listeners.Clear();
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
Trace.Listeners.Add
(new TextWriterTraceListener(File.Create("output.txt")));
Note It is recommended that you enable the debug attribute only when you are
debugging an application, because it significantly affects the performance of the
application.
You can also specify the debug attribute in the Machine.config file that is
located in the directory for the .NET common language runtime. This setting
will then affect all the applications that are running on your computer.
Module 5: Implementing a Simple XML Web Service 47
Tracing You can enable or disable tracing in your Web service by using the trace
element as follows:
<configuration>
<system.web>
<trace
enabled="true"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"
/>
</system.web>
</configuration>
Configuring a When an application executes the code that creates an instance of a switch for
TraceSwitch the first time, it checks the configuration system for trace-level information
about the named switch. The tracing system examines the configuration system
only once for any particular switch, which happens the first time that the
application creates the switch.
In a deployed application, you can control your tracing code by reconfiguring
switch objects between the runs of your application. Typically, this involves
turning the switch objects on and off or by changing the tracing levels, and then
restarting your application.
To set the level of your switch, edit the configuration file that corresponds to
the name of your application. In the following code, entries for two switches
have been added.
<configuration>
<system.diagnostics>
<switches>
<add name="acctInfo" value="0" />
<add name="acctUpdates" value="4" />
</switches>
</system.diagnostics>
</configuration>
Note To improve performance, you can make Switch members static (Shared)
in your class.
48 Module 5: Implementing a Simple XML Web Service
Trace.WriteLineIf(tsInfo.TraceVerbose,
"Writing all acctInfo traces.");
Trace.WriteLineIf(tsUpdate.TraceVerbose,
"Writing all acctUpdate traces.");
...
tsInfo.Level = TraceLevel.Warning;
Trace.WriteLineIf(tsInfo.TraceWarning,"some warning...");
...
tsInfo.Level = TraceLevel.Error;
Trace.WriteLineIf(tsInfo.TraceWarning,"another warning...");
Visual Basic .NET code Dim tsInfo As New TraceSwitch("acctInfo", "Info traces")
example Dim tsUpdate As New TraceSwitch("acctUpdate", "Update traces")
Trace.WriteLineIf(tsInfo.TraceVerbose, _
"Writing all acctInfo traces.")
Trace.WriteLineIf(tsUpdate.TraceVerbose, _
"Writing all acctUpdate traces.")
...
tsInfo.Level = TraceLevel.Warning
Trace.WriteLineIf(tsInfo.TraceWarning, "some warning...")
...
tsInfo.Level = TraceLevel.Error
Trace.WriteLineIf(tsInfo.TraceWarning, "another warning...")
The level of the tsInfo switch is initialized to 0 (Off), and the level of the
tsUpdate switch is initialized to 4 (Verbose). In the latter part of the preceding
code, the level of the tsInfo switch is programmatically modified.
Configuring listeners To set the level of a listener, edit the configuration file that corresponds to the
name of the application. For Web services, this is Web.config. Within this file,
you can add a listener, set its type and parameters, remove a listener, or delete
all the listeners that the application previously added. The following XML is an
example of how to configure listeners:
<configuration>
<system.diagnostics>
<listeners>
<add name="myTextListener"
type="TextWriterTraceListener"
initializeData="c:\myListeners.log" />
</listeners>
</system.diagnostics>
</configuration>
Module 5: Implementing a Simple XML Web Service 49
The following is an example of the resulting output. Note that you can see the
complete SOAP request and response:
========================== Request at 7/24/2001 11:53:49 AM
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope namespaces omitted for brevity >
<soap:Body>
<GetTransactionHistory xmlns="http://tempuri.org/">
<startDate>2001-01-01T00:00:00.0000000-08:00</startDate>
<endDate>2002-01-01T00:00:00.0000000-08:00</endDate>
</GetTransactionHistory>
</soap:Body>
</soap:Envelope>
<configuration>
<system.web>
<trace enabled="true" requestLimit="10"
pageOutput="false" traceMode="SortByTime"
localOnly="true" />
</system.web>
</configuration>
These settings affect the results that are displayed when you use the Trace.axd
utility. Trace.axd is a utility that can be used to retrieve application-level tracing
information. If you type the following URL in a browser address box, tracing
has been enabled, and the localOnly attribute is set to false:
http://servername/applicationname/trace.axd
If you click one of the View Details links, the details that you see resemble the
following:
Writing to an Event Log An important tool for monitoring an application is the Microsoft Windows®
event log. The .NET Framework makes it very easy to write information to
event logs. The following code illustrates how to write a warning to a custom
event log named ContosoLog.
58 Module 5: Implementing a Simple XML Web Service
It is not a good idea to make frequent calls to the event log because of the
performance implications, but it is recommended that you use the event log if
you want to log exceptions.
Performance counters Performance counters provide an excellent way to monitor the performance of
your Web service at run time. The .NET Framework makes it easy to access
performance counters in addition to creating custom counters specifically for
Web services.
Module 5: Implementing a Simple XML Web Service 59
You will now look at how to create a new category and custom performance
counter at design time.
To create custom performance counters:
1. Open Server Explorer and expand the node for the server that you want to
view. The contents on your screen should resemble the following:
4. Click New, and then enter the required information, as shown in the
following illustration:
Tip Before you exit the dialog box, you can select any of the counters in the
Counters list and edit their values, or delete the counters.
The counters and categories that you create in the dialog box are read-write
enabled by default, but your interaction with them through an instance of the
PerformanceCounter component will be restricted to read-only unless you
specify otherwise.
Module 5: Implementing a Simple XML Web Service 61
The following procedure and code samples show how to use a performance
counter:
1. In Global.asax, create an instance of the PerformanceCounter class to give
users access to the performance counter. Store the object reference in the
Application object for later use.
C# code example protected void Application_Start(Object sender,
EventArgs e)
{
PerformanceCounter perf = new PerformanceCounter(
"Contoso","NumberOfActiveRequests",
"Contoso Web Service", false);
Application.Add("perf",perf);
}
Review
3. Which properties and fields of a class are serialized when a Web service
method returns an instance of a class?
All public, read/write properties and all public, read/write fields.
4. If your Web service will be deployed on a Web farm, what kind of data can
be stored appropriately in Application state?
Read-only data that can be restored exactly in the event of a Web
service being restarted.
Module 5: Implementing a Simple XML Web Service 63
5. You deploy a Web service in production, and you want to store trace
information in a disk file on the server hosting the Web service. Which two
classes could you use to do this?
• Trace to emit trace output
• TextWriterTraceListener to write the trace output to disk
6. Which .NET Framework class is provided to allow you to hook into various
stages of SOAP message processing?
SoapExtension
64 Module 5: Implementing a Simple XML Web Service
Note This lab focuses on the concepts in this module and, as a result, may not
comply with Microsoft security recommendations. For instance, this lab does
not comply with the recommendation that you not specify hard-coded values
for authentication information. Also, the lab has you save passwords for
database access in clear text when generating typed datasets.
Lab Setup For each lab exercise in this course, you have the option of coding in either C#
or Visual Basic .NET. To avoid unnecessary instructions, the following
placeholders will be used throughout the lab exercises:
install_folder The install folder for the course content. Usually this will
be the folder C:\Program Files\Msdntrain\2524.
lab_root The folder install_folder\Labfiles\CS or
install_folder\Labfiles\VB, depending on the language you
are using for the lab exercises.
It is recommended that you select only one language for the lab exercises.
Module 5: Implementing a Simple XML Web Service 65
There are starter and solution files that are associated with this lab. The starter
files are in the folder lab_root\Lab05\Starter. The solution files for this lab are
in the folder lab_root\Lab05\Solution.
Scenario In this lab, you will create the initial version of the Contoso Micropayment
Service. This is a Web service that manages accounts for users who do not want
to provide their personal financial information to all of the e-commerce sites
that they shop.
In this lab, you will also extend the Woodgrove and Contoso Account Manager
application to use the Contoso Micropayment Web Service. You will modify
the application to use the following Contoso Micropayment Web service
methods:
! GetAccount
! GetTransactionHistory
Estimated time to
complete this lab:
75 minutes
66 Module 5: Implementing a Simple XML Web Service
Exercise 0
Setting up the Woodgrove Web Service
If you did not previously create a virtual directory for the Woodgrove Web
service, do so now.
Exercise 1
Creating the Contoso Micropayment Web Service
In this exercise, you will implement the skeleton code for the Contoso
Micropayment Web service by using Visual Studio .NET. You will also
configure an application setting for a SQL Server connection string in the
Web.config file for the Web service.
[WebMethod]
public TransactionDataSet GetTransactionHistory
(DateTime startDate, DateTime endDate)
{
}
<WebMethod()> _
Public Function GetTransactionHistory(startDate As _
DateTime, endDate As DateTime) As TransactionDataSet
End Function 'GetTransactionHistory
At this point, you can ignore the undefined types AccountDataSet and
TransactionDataSet. You will define these types in Exercise 2.
Note In C#, if you add a class definition before the WebService class
definition, you will not be able to open the code-behind page from the
Visual Studio .NET designer.
Exercise 2
Accessing the Database
In this exercise, you will add functionality to the GetAccount and
GetTransactionHistory methods to call the existing stored procedures in the
SQL Server Contoso database that return account data and transactions,
respectively.
4. When prompted, type the password again, and then click OK.
Exercise 3
Using the Contoso Web Service in the Woodgrove and Contoso
Account Manager
In this exercise, you will add a Contoso Web reference to the client application
for the Woodgrove and Contoso Account Manager, and add code to invoke the
proxy class methods for the Contoso Micropayment Web Service.
Note If you did not complete Lab 4, use the WebServiceClient project
found in the
lab_root\Lab05\Starter\Woodgrove and Contoso Account Manager folder.
Otherwise, continue to use the WebServiceClient project that you worked
on in Lab 4 (in the
lab_root\Lab04\Starter\Woodgrove and Contoso Account Manager folder).
2. In Solution Explorer, right-click the References node and click Add Web
Reference.
3. In the Add Web Reference dialog box, type
http://Localhost/Contoso/Micropayment.asmx in the address field and
click Go.
You should see the Service Help page for the Contoso Web service.
4. Change the name to Micropayment, and then click Add Reference to
complete adding a Web reference.
Module 5: Implementing a Simple XML Web Service 73
Exercise 4
Debugging the Contoso Micropayment Service
In this exercise, you write code to output debug statements and add
performance counters to a Web service.
4. Click New to add a new performance counter to the Contoso category. Set
the following information.
Field Value
Name NumberOfActiveRequests
Type NumberOfItems32
Description Number of active GetAccount requests
5. Click OK.
6. Open the code-behind file for Global.asax.
7. C# programmers must import the System.Diagnostics namespace. This is
unnecessary for Visual Basic .NET programmers.
Module 5: Implementing a Simple XML Web Service 77
Overview 1
Lesson: Deploying Web Services 2
Lesson: Overview of UDDI 11
Lesson: Publishing a Web Service 24
Lesson: Using UDDI 37
Review 46
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.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 6: Deploying and Publishing XML Web Services iii
Instructor Notes
Presentation: This module teaches students how to deploy and publish XML (Extensible
90 Minutes Markup Language) Web services and locate Web services by using the
Microsoft Universal Description, Discovery, and Integration (UDDI) software
Lab: development kit (SDK). A local development UDDI registry is used in the
00 Minutes demonstrations for this module, but the mechanics of publishing and finding
Web services is no different on the public UDDI registry nodes.
After completing this module, students will be able to:
! Deploy a Web service.
! Explain the role of UDDI in Web services.
! Explain the various options for publishing a Web service on an intranet.
! Explain some of the options for modifying the default configuration of a
Web service.
! Publish a Web service in a UDDI registry by using the Microsoft UDDI
SDK.
! Search a UDDI registry to locate Web services by using the UDDI SDK.
Required Materials To teach this module, you need the Microsoft® PowerPoint® file 2524C_06.ppt.
Preparation Tasks To prepare for this module:
! Read all of the materials for this module.
! Practice all of the demonstrations.
! Review the demonstration code in
install_folder\Democode\language\Mod06.
! Install UDDI SDK 2.0.
! Register a Web service with the http://test.uddi.microsoft.com UDDI
registry.
iv Module 6: Deploying and Publishing XML Web Services
Module Strategy
Use the following strategy to present this module:
! Files Needed to Deploy Web Services
Discuss the files that are needed to deploy Microsoft ASP.NET Web
applications. For each file type, describe the reasons why the file type is
needed or not needed to deploy ASP.NET Web applications.
! Deploying Web Services Manually
Discuss the two methods that can be used for deploying ASP.NET Web
applications manually. Describe the circumstances in which a developer
would choose to deploy the ASP.NET Web applications manually. Do not
forget to mention that the Microsoft Internet Information Services (IIS)
settings are copied to the target Web server when deploying a Web service
manually.
! Deploying Web Services Using Windows Installer Files
Describe how ASP.NET Web applications can be deployed by using
Microsoft Windows® Installer files. Discuss how Windows Installer files
can be created by using the Web Setup project. Describe the circumstances
in which a developer would choose to deploy the ASP.NET Web
application by using Windows Installer files. Do not forget to mention the
following key points:
• IIS security settings will not get configured when ASP.NET Web
applications are deployed by using Windows Installer files. Direct the
student's attention to the related Note in the student notes.
• The Web Setup project will not automatically install the Microsoft .NET
Framework on the target Web server. Direct the students’ attention to the
related note in the Student Notes.
Do not demonstrate the Web Setup project in this topic as the following
topic is a demonstration of creating a Web Setup project.
! Demonstration: Creating a Web Setup Project
In this demonstration, the students will see the steps that are involved in
creating a simple Web Setup project that is used to deploy an ASP.NET
Web application.
You may want to show the students the files that are listed in the Outputs
dialog box for each Project Output group.
! Overview of UDDI
This topic provides an overview of the role of UDDI registries in the
process of Web service discovery. The UDDI data structures and application
programming interfaces (APIs) are explained. Ensure that you cover each of
the elements in the UDDI data structure and describe how they are used.
Many students might have difficulty understanding the tModel element.
Explain that the tModel element is deliberately generically defined because
it can be used in multiple ways in UDDI. Explain that using tModel to
represent Web Services Description Language (WSDL) documents is just
one of its uses. Provide only a brief overview of publisher assertions.
Explain the publisher and inquiry APIs. Emphasize that each of these APIs
is a Web service operation that can be invoked by using Simple Object
Access Protocol (SOAP). Explain how the UDDI SDK encapsulates these
operations.
Module 6: Deploying and Publishing XML Web Services v
Note You can only register one business (or provider) on the
http://test.uddi.microsoft.com UDDI registry. You can register multiple
Web services, but they all must be part of the one business.
12. Click the new provider in the tree-view control in the left pane.
13. Click the Services tab, and then click Add Service.
14. Enter information about the service including the URL to the Web service
on the Bindings tab.
For more information on how to create a service, click Publishing a service
on the Quick Help menu.
15. To search for your new Web service, on the UDDI Test Site page, click
Search.
16. On the Services tab, enter the name of the Web service you just registered,
and click Search.
17. In the Results pane, click a Web service to see information about the found
Web service.
• Publishing a Web Service with the UDDI Publish Wizard
The UDDI Publish Wizard is just another interface for registering a
business and a Web service with a public or private UDDI registry. To
use the UDDI Publish Wizard, you must already have an account with
the UDDI registry.
• Publishing a Web Service Programmatically
All of the code in this topic is in the PublishWebServices.txt text file in
the install_folder\DemoCode\language\Mod06 folder.
• Lesson: Using UDDI
All of the code in this lesson is in the FindWebServices.txt text file in
the install_folder\DemoCode\language\Mod06 folder.
• Finding a UDDI Registry
An application can be hard-coded to use a particular public or private
UDDI registry, or you can programmatically find a UDDI registry at
run-time.
Module 6: Deploying and Publishing XML Web Services vii
If you have Internet access in the classroom, you can run the FindWebServices
application, in the install_folder\DemoCode\language\Mod06\
FindWebServices folder, to search for existing Web services on the
http://test.uddi.microsoft.com UDDI registry. A version of the Northwind Web
service that uses UDDI to find Contoso and Woodgrove Web services in the
http://test.uddi.microsoft.com UDDI registry is included in the
install_folder\DemoCode\language\Mod06\Northwind folder. To demonstrate
this version of the application, you will need Internet access in the classroom,
and you must register your own versions of the Contoso and Woodgrove Web
services with the http://test.uddi.microsoft.com UDDI registry.
Module 6: Deploying and Publishing XML Web Services 1
Overview
Note You must copy the code-behind files if you are using dynamic
compilation in your Web service. Dynamic compilation is enabled by using
the src attribute in the @ Page directive.
4 Module 6: Deploying and Publishing XML Web Services
Files needed to deploy The files that are needed to deploy the Web services include:
Web services
! The \bin directory and the DLL files that are within it.
The \bin directory and the DLL files are the compiled resource files and the
code-behind files.
! All Web Form, user control, and Web service files (.aspx, .ascx, .asmx).
The Web Form, user control, and Web service files are the user and Web
application interface files.
! Configuration files, including Web.config and Global.asax.
If you change the configuration settings in the machine.config file on the
development computer, you must make the same changes in the
machine.config file on the production server.
! Any additional support files, such as XML files, which are in the directory.
Module 6: Deploying and Publishing XML Web Services 5
When to deploy Web You can manually deploy a Web service if:
services manually
! You deploy the Web service files to the same Web server.
! You test the Web service before final deployment.
! Your Web service is relatively simple.
6 Module 6: Deploying and Publishing XML Web Services
Deploying Web services You can copy Web service files and resources to the target Web server by
manually manually copying the files, or by using the Visual Studio .NET Copy Project
command:
! To deploy a Web service by copying files.
You can copy the files directly to the target Web server by using Windows
Explorer, File Transfer Protocol (FTP) operations, or the command
prompt’s XCOPY command.
! To deploy a Web service by using the Visual Studio .NET Copy Project
command:
a. Open your Web service in Visual Studio .NET.
b. On the Project menu, click Copy Project.
c. Select the destination project folder.
d. Select the Web access method.
e. Select the files to be copied.
f. Click OK.
Deployment and IIS If you choose to deploy your Web service by copying files manually, you will
settings need to configure IIS to use the destination folder as a Web application. You
can configure IIS manually by using the IIS console or by writing IIS scripts.
If you use the Visual Studio .NET Copy Project command to deploy a Web
service, a new virtual directory is created for you during the copy process.
However, any custom IIS settings that you have for the source Web application
are not applied to the production copy of your Web service. The new virtual
directory inherits all of the default settings from the Web application. You must
apply the appropriate IIS settings separately, either by developing and running
IIS scripts or by manually applying the IIS settings that your Web application
requires.
Module 6: Deploying and Publishing XML Web Services 7
Note Although you can configure virtual directory access settings, you
cannot configure IIS authentication settings. To configure IIS authentication
settings, you must use a script file.
A Web Setup project A Web Setup project creates a Windows Installer file that can be deployed to a
Web server so that users can later download and run the file from a Web site.
The following are the main steps to deploying a Web application by using the
Web Setup project:
1. Create a new solution file and add new projects.
Create a blank Visual Studio .NET solution and add a new Web Setup
project, and your existing Web service project, to that solution. Alternately,
you can add a Web Setup project to an existing Web service Visual Studio
.NET solution.
2. Configure the Web Setup project.
Configuring the Web Setup project involves specifying Web service
properties, such as the virtual directory name, script access, indexing, and
logging. Configuring the Web Setup project also involves selecting the Web
service files that must be deployed to the Web server.
3. Build the Web Setup project.
To create the Windows Installer file, on the Build menu, click Build
ProjectName.
Note You cannot use a Web Setup project to automatically install the
Microsoft .NET Framework on the target Web server. To install the Microsoft
.NET Framework, you must create a setup program. For more information, see
the Microsoft MSDN® article, “Deploying .NET Applications: Lifecycle
Guide,” which is available at the following Uniform Resource Locator (URL):
http://msdn.microsoft.com/library/default.asp?url=/library/
en-us/dnbda/html/DALGDeploy.asp
Module 6: Deploying and Publishing XML Web Services 9
Configure the Web 4. In the File System window, select Web Application Folder.
Setup project
5. In the Properties window, show the properties that you can set for the Web
application, including the virtual directory name, script access, indexing,
and logging properties.
6. In the left pane of the File System window, right-click the Web Application
Folder, point to Add, and then click Project Output.
10 Module 6: Deploying and Publishing XML Web Services
7. Explain each of the outputs that can be added to the Web application folder.
Refer to the following table for details on the items.
Outputs Purpose
8. Select Primary output and Content Files, and then click OK.
9. To see the content files that will be included in the setup project, in Solution
Explorer, right-click Content Files from Woodgrove, and then click
Outputs.
Notice that the typed DataSet files will be included by default.
To close the Outputs dialog box, click OK.
10. To set an Exclude filter on the Content Files to exclude the .xsd files,
perform the following steps:
a. In Solution Explorer, right-click Content Files from Woodgrove, and
then click ExcludeFilter.
b. In the Filter dialog box, click Add Filter.
c. In the Add Filter dialog box, type *.xsd and then click OK.
d. Click OK.
11. View the Outputs for the Content Files again.
The .xsd files will no longer be included.
Build the Web Setup 12. In Solution Explorer, right-click SetupDemo and then click Build.
project
13. Open Windows Explorer and browse to
install_folder\Democode\WebSetupDemo\SetupDemo\Debug.
Copy and test the Web 14. Double-click SetupDemo.msi to run the installer package and install the
service deployment new Web service.
Keep the default settings in the installation wizard. This will install the
Woodgrove Web service to the C:\Inetpub\wwwroot\SetupDemo folder and
create a virtual directory named SetupDemo.
15. Open Microsoft Internet Explorer and browse to:
http://localhost/SetupDemo/bank.asmx
16. Verify that the Web service works by invoking the Web methods.
Show the deployed files 17. In Windows Explorer, browse to C:\Inetpub\wwwroot\SetupDemo.
Remove the Web service 18. In Control Panel, double-click the Add or Remove Programs icon and
show that SetupDemo is listed as an installed program.
19. Uninstall the Web service.
Module 6: Deploying and Publishing XML Web Services 11
What Is UDDI?
Note All the information about the UDDI Programmer’s API and UDDI Data
Structure Specifications is based on version 2.0 of the specifications.
The UDDI Programmer’s The UDDI Programmer’s API Specification defines functions that provide a
API Specification simple request/response model for accessing UDDI registries. There are two
types of API defined in the API reference:
! A publisher’s API that allows you to publish data in a registry.
! An inquiry API that allows you to read information from a registry.
UDDI registry UDDI is also a set of implementations of the specifications that allow
implementations businesses to register information about the Web services that they offer so that
other businesses can find them. These implementations are publicly accessible.
Also, UDDI registries are themselves available as Web services.
At the time of this writing, there are two public implementations of these
specifications. They can be located at http://uddi.microsoft.com and
http://www-3.ibm.com/services/uddi.
14 Module 6: Deploying and Publishing XML Web Services
In this module, you will learn how to use all three methods of publishing a Web
service in a UDDI registry.
Discovering a Web To use a Web service, you create a Web service consumer that:
service
1. Discovers Web services with the desired functionality in a UDDI registry on
an intranet, extranet, or on the Internet.
2. Retrieves a WSDL service description by using the information found in the
UDDI registry.
You can either do this programmatically or by using the Add Web
Reference command in Visual Studio .NET.
Module 6: Deploying and Publishing XML Web Services 17
3. Creates a proxy class, which uses SOAP messaging, from the WSDL
service description.
You can either do this by using the wdsl.exe utility or by using the Add
Web Reference command in Visual Studio .NET, which creates a proxy
class automatically.
4. Calls Web service methods from the client application.
18 Module 6: Deploying and Publishing XML Web Services
The BusinessEntity The BusinessEntity class describes a business or provider that has registered a
class Web service within UDDI. The BusinessEntity is the top-level class that
contains descriptive information about a business. This class supports standard
information such as name, description, and contacts, in addition to metadata
information such as identifiers and categories. The latter information is used for
standard taxonomies of business identifiers (tax identifiers, D-U-N-S numbers,
and other identifiers). D-U-N-S numbers are unique nine-digit numbers of
single business entities) and categories (industry codes, geography codes, and
other similar codes). Service descriptions and technical information are related
to a BusinessEntity by using containment.
The BusinessService The BusinessService class describes a Web service that a business exposes.
class This class supports naming a Web service and associating it with a business and
binding information. It also supports the assignment of categories (industry,
product, geographic codes, and other categories) to the Web service.
The BindingTemplate The BindingTemplate class describes the technical information that is
class necessary for binding to a particular Web service. The binding information is
described as an access point.
The AccessPoint class The AccessPoint class describes a Web service entry point. The AccessPoint
class has an attribute named UrlType, which is used to specify one of the seven
entry point types:
! mailto-the access point is an e-mail address.
! Http-the access point is an Hypertext Transfer Protocol (HTTP) compatible
URL.
! Https-the access point is an HTTP Secure (HTTPS) compatible URL.
! Ftp-the access point is a File Transfer Protocol (FTP) directory address
URL.
! Fax-the access point is a telephone number that is answered by a fax
machine.
! Phone-the access point is a telephone number that is answered by a human
or voice response system.
! Other-the access point is any format other than the preceding ones. When
this URL type is specified, the specification information (in the TModel
class) must suggest a transport type.
The UDDI SDK and the UDDI Publish Wizard are installed by default to
%ProgramFiles%\Microsoft SDK\Bin\. They must be registered using the
UddiSdkRegister utility. This utility adds the Microsoft.Uddi assembly to the
.NET Framework Global Assembly Cache and to the Visual Studio .NET
components list, and adds the UDDI Publish Wizard to the Visual Studio .NET
Tools menu. To register these components:
1. On the Start menu, point to Programs, then point to Visual Studio .NET
2003, then point to Visual Studio .NET Tools, and then click Visual
Studio .NET 2003 Command Prompt.
2. Navigate to the \Program Files\Microsoft SDK\Bin folder.
3. Type UddiSdkRegister and then press ENTER.
The Microsoft UDDI SDK To make using UDDI APIs easier, the UDDI SDK from Microsoft provides
managed wrappers for the UDDI data structures and APIs. All the wrappers
reside within the Microsoft.UDDI namespace. The UDDI data structures are
represented as Microsoft .NET classes with many properties. Each of the UDDI
API functions is implemented as a managed class with a Send() method.
The UDDI SDK contains the following namespaces:
Namespace Description
Permissions and A security policy is a configurable set of rules that the .NET common language
security policy runtime follows when determining the permissions to grant to any code. The
runtime examines identifiable characteristics of the code, such as where the
code originates, and what the identity of the current caller is, to determine the
level of access that the code can have to resources. During execution, the
runtime ensures that the code accesses only those resources that it has
permission to access. These permissions determine if a Web service can write to
an event log, if a Web service can access the file system, and other similar
issues.
Assembly permissions A Web service developer is typically not responsible for configuring the
security policy on a production Web server. Therefore, it is unlikely that the
security policy in the development environment will match the security policy
in the production environment. Because of this reason, it is a good idea for a
Web service developer to explicitly specify which permissions are required for
a Web service to correctly function.
By requesting permissions, you inform the runtime about the types of things
your code must be allowed to do. You can request permissions for an assembly
by placing attributes at the assembly scope of your code. For example, you can
request the file I/O permission by adding the FileIOPermissionAttribute.
When you create an assembly, the language compiler stores the requested
permissions in the assembly manifest. At load time, the runtime examines the
permission requests, and applies security policy rules to determine which
permissions to grant to the assembly. Permission requests can only influence
the runtime to deny permissions to your code and can never influence the
runtime to grant additional permissions to your code. The local administration
policy always has the final control over the maximum permissions that your
code is granted.
For more information about some of the security concepts relevant to Web
services, see Module 7, “Securing XML Web Services,” in Course 2524,
Developing XML Web Services Using Microsoft ASP.NET. However, full
coverage of the details on assembly security and deployment is beyond the
scope of this course. For more information about these topics, see Course 2350,
Securing and Deploying Microsoft .NET Assemblies.
Configuring assemblies To successfully deploy a Web service, you must understand how the common
language runtime locates and binds to the assemblies that make up your service.
By default, the runtime attempts to bind with the exact version of an assembly
with which a service is built. Configuration file settings can override this
default behavior.
The common language runtime performs a number of steps when attempting to
locate an assembly and resolve an assembly reference. The term probing is
often used when describing how the runtime locates assemblies. Probing is the
set of heuristics that are used to locate an assembly based on its name, version,
and culture.
You can configure assembly-binding behavior at different levels based on three
XML-based files:
! The application configuration file.
! The publisher policy configuration file.
! The machine configuration file.
Module 6: Deploying and Publishing XML Web Services 27
All the preceding files follow the same syntax and provide information such as
binding redirects, the location of the assemblies, and binding modes for specific
assemblies. Each configuration file can contain elements that redirect the
binding process.
For complete coverage about configuring assemblies, see Course 2350,
Securing and Deploying Microsoft .NET Assemblies.
Localizing a Web service It is possible that you may need to localize a Web service. Localizing a Web
service is typically done by separating out the culture-specific resources into
separate resource-only assemblies, which are known as satellite assemblies.
Each satellite assembly contains the resources for a single culture, but does not
contain any code. There are several advantages to this model:
! You can incrementally add resources for new cultures after you deploy an
application.
Because development of culture-specific resources can require a significant
amount of time, adding resources for a new culture after application
deployment allows you to deploy your Web service for the primary culture
that you want to support, and then deliver other culture-specific resources at
a later date.
! You can update and replace the satellite assemblies of a Web service
without recompiling the Web service.
! At run time, a Web service only needs to load the satellite assemblies that
contain the resources that are required for a specific culture. This can
significantly reduce the use of system resources.
For more information about localizations and building and deploying satellite
assemblies, see Course 2350, Securing and Deploying Microsoft .NET
Assemblies.
28 Module 6: Deploying and Publishing XML Web Services
Accessing Windows Visual Studio .NET includes a user interface to publish to the
Server 2003 UDDI http://uddi.microsoft.com UDDI registry.
Services through
Visual Studio .NET To access the UDDI Services through Visual Studio .NET:
1. On the Start page, click the Online Resources tab, and then click XML
Web Services.
2. On the Register a Service tab, click Register your XML Web Service
today.
3. Select either the production or test UDDI registry hosted by Microsoft, and
then click Submit.
Module 6: Deploying and Publishing XML Web Services 29
Windows Integrated The wizard will use your current Windows credentials
Authentication to interact with the site. This type of authentication
typically applies only to UDDI Services sites.
UDDI Authentication The wizard will use UDDI authentication to interact
with the site. This type of authentication is commonly
used by UDDI sites on the Internet, such as the
Microsoft UDDI Business Registry.
4. On the UDDI Site screen, specify the URL of the UDDI site to which you
want to publish the Web service, and then click Next.
The UDDI site URL options are described in the following table.
Option Description
Use existing site Select a site from the list of known UDDI servers. This
list includes the public Microsoft UDDI sites and the
UDDI Services sites that have been registered in the
Active Directory® directory service.
Specify URL Type the UDDI Publish API URL of the UDDI site.
For example, for a UDDI Services site, type:
http://servername/uddi/publish.asmx
5. On the Web Service Provider screen, select a provider for the Web service
or create a new one. This provider represents the group or organization that
is responsible for the Web service you are publishing. When finished, click
Next.
The Web service provider options are described in the following table.
Option Description
Existing provider Select a provider from the list. This list includes all of
the providers that you own in this UDDI site.
New provider Create a new provider for the Web service.
Provider name: Type a name for this provider.
Provider description: Type a description for this
provider. (Optional)
Categorize Assigns categories to this provider. Adding
categorizations to your provider will assist other users
and applications in discovering it in UDDI. This option
is only available when publishing to a Microsoft UDDI
site.
32 Module 6: Deploying and Publishing XML Web Services
6. On the Web Service Details screen, type a name, description, and URL to
the access point for the Web service, and then click Next.
The Web service details options are described in the following table.
Option Description
8. On the Summary screen, review the details of your Web service as it will
be published in the UDDI site. Click Back to correct any errors or click
Publish to publish your Web service in the UDDI site.
Module 6: Deploying and Publishing XML Web Services 33
Connect to a UDDI All the operations that are related to publishing a Web service require an
registry authentication token when connecting to a UDDI registry.
C# code example UddiConnection myConn = new
UddiConnection("http://test.uddi.microsoft.com/inquire",
"https://test.uddi.microsoft.com/publish");
myConn.AuthenticationMode =
AuthenticationMode.UddiAuthentication;
myConn.Username = "username";
myConn.Password = "password";
34 Module 6: Deploying and Publishing XML Web Services
When any publication action is taken, if an authentication token has not already
been obtained, the wrapper classes automatically make the call to
get_authToken to obtain the authentication token.
Publishing a tModel The first step in publishing a Web service is to publish the tModels that the
Web service supports. The following code provides an example of publishing a
tModel method.
C# code example TModel tMod = new TModel();
tMod.Name = new Name("Micropayment TModel");
tMod.Descriptions.Add("TModel for Micropayment service");
tMod.OverviewDoc.OverviewUrl =
"http://www.contoso.com/Contoso/overview.htm";
tMod.CategoryBag.Add(CommonCanonical.UddiOrgTypes,
"wsdlSpec",
"WSDL Specification for a web service");
tMod.CategoryBag.Add(CommonCanonical.UddiOrgTypes, _
"wsdlSpec", "WSDL Specification for a web service")
Publishing a Before you can publish a Web service, you must publish the BusinessEntity
BusinessEntity that the service will be associated with. The following code provides an
example of how to publish a BusinessEntity.
Module 6: Deploying and Publishing XML Web Services 35
// create a contact
Contact contact = new Contact();
contact.PersonName = "Adam Barr";
contact.Emails.Add("[email protected]");
contact.Phones.Add("(425)555-0101");
contact.Descriptions.Add("Web Site Administrator", "en");
myBiz.Contacts.Add(contact);
Windows Integrated Windows integrated authentication uses the credentials of the current user for
authentication publishing operations. This is the default form of authentication used by UDDI
Services. Using Windows integrated authentication, the authentication
handshake between the client and the UDDI server is automatic and does not
require that a GetAuthToken request be sent.
The following example shows you how to set up a connection to a UDDI server
using Windows integrated authentication:
C# code sample UddiConnection myConn = new UddiConnection(
"http://mySite/uddi/inquire",
"https://mySite/uddi/publish",
"http://mySite/uddi/extension.asmx");
Note Windows integrated authentication will be more secure but can only be
used in an intranet or extranet environment.
Module 6: Deploying and Publishing XML Web Services 41
UDDI Authentication UDDI authentication requires that the username and password credentials be set
before attempting any publishing operations. The AuthenticationMode
property can either be set explicitly, or it will be set implicitly when a username
and password are provided in the constructor method of the UddiConnection
object. By default, under the control of the AutoGetAuthToken property, the
UDDI operation will automatically send a GetAuthToken request to retrieve
an AuthToken that contains the authentication token. The authentication token
will be stored in the AuthInfo property and used with each publish message on
this connection. Also under the control of the AutoGetAuthToken property,
the UDDI operation will automatically retrieve an updated authentication token.
C# code sample // Create a connection to the UDDI Registry
UddiConnection myConn = new UddiConnection(
"http://test.uddi.microsoft.com/inquire",
"https://test.uddi.microsoft.com/publish",
"http://test.uddi.microsoft.com/extension.asmx");
myConn.AuthenticationMode =
AuthenticationMode.UddiAuthentication;
myConn.Username = szUsername;
myConn.Password = szPassword;
Visual Basic .NET code ' Create a connection to the UDDI Registry
sample Dim myConn As New UddiConnection _
("http://test.uddi.microsoft.com/inquire", _
"https://test.uddi.microsoft.com/publish", _
"http://test.uddi.microsoft.com/extension.asmx")
Locate businesses Locate a business by using the FindBusiness class. The Send method of the
FindBusiness object returns a BusinessList object with an entry for each
business that matches the search criteria.
The following code example locates all businesses with the name "Contoso".
C# code example FindBusiness fb = new FindBusiness("Contoso");
BusinessList bizList = fb.Send(myConn);
Note The search criterion is not restricted to a simple name. You could also
use a list of business identifiers, category references, discovery URLs, or
tModel references in your search criteria.
Locate services After obtaining a list of businesses that satisfy your search criteria, you can
retrieve a list of services that the business entity supports. The following code
demonstrates how you can extract service information from a BusinessInfo
object.
C# code example foreach (BusinessInfo bizInfo in bizList.BusinessInfos)
{
//iterate through services supplied by each business
foreach (ServiceInfo myServ in bizInfo.ServiceInfos)
{
//Service name is myServ.Names[0].Text
//Service key is myServ.ServiceKey
}
}
You can also locate a service by using the FindService class. The Send method
of the FindService object returns a ServiceList object with an entry for each
service that matches the search criteria.
44 Module 6: Deploying and Publishing XML Web Services
The following code example locates all services with the name "Bank".
C# code example FindService fs = new FindService("Bank");
ServiceList sl = fs.Send(myConn);
Bind to the Web service After you find the binding information, it is easy to set the URL property of the
Web service proxy and invoke Web service methods. The following code
shows how to do this.
C# code example ContosoMicropaymentService microServ = new _
ContosoMicropaymentService ();
microServ.Url = strURL;
//call a Web method from the Web service
Review
1. Why is it important to copy only required files to the Web server when
deploying a Web service?
By not copying unnecessary files, you increase the security of your
production environment by limiting the exposure of uncompiled code.
2. Which of the following file types are not required when deploying a Web
service?
• .resx
• .asmx
• .vsdisco
• Web.config
• .xml
• \Web References folder and files
• \bin directory and .dll(s)
The following files are not required when deploying a Web service:
.resx, .vsdisco, and \Web References folder and files.
Module 6: Deploying and Publishing XML Web Services 47
5. Which UDDI data structure is used to store the endpoint for a Web service?
bindingTemplate
6. Why would you disable the dynamic discovery document in the root
directory of your Web site?
To prevent all the Web services on your site from automatically
exposing information.
48 Module 6: Deploying and Publishing XML Web Services
Contents
Overview 1
Lesson: Overview of Security 2
Lesson: Built-In Authentication 10
Lesson: Custom Authentication Using
SOAP Headers 18
Lesson: Authorization Using
Role-Based Security 25
Lesson: Authorization Using Code
Access Security 39
Lesson: Encryption 46
Review 54
Lab 7: Securing XML Web Services 56
Course Evaluation 72
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.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 7: Securing XML Web Services iii
Instructor Notes
Presentation: This module teaches students how to use the security services of the Microsoft®
120 Minutes Windows® operating system, Microsoft Internet Information Services (IIS), and
the Microsoft .NET Framework and common language runtime to secure XML
Lab: (Extensible Markup Language) Web services.
60 Minutes
After completing this module, students will be able to:
! Identify the differences between authentication and authorization.
! Explain how to use the security mechanisms that IIS and Windows provide
for authentication.
! Use Simple Object Access Protocol (SOAP) headers for authentication in a
Web service.
! Use role-based security and code access security for authorization in a Web
service.
! Encrypt the communication between a Web service consumer and a Web
service.
Required Materials To teach this module, you need the Microsoft PowerPoint® file 2524C_07.ppt.
Preparation Tasks To prepare for this module:
! Read all of the materials for this module.
! Practice all of the demonstrations.
! Review the walkthrough code files in the
<install folder>\Democode\<language>\Mod07.
! Complete the lab.
iv Module 7: Securing XML Web Services
Dual-language The PowerPoint file for this module contains macros that allow you to switch
PowerPoint macros the displayed code between C# and Microsoft Visual Basic® .NET. To run the
macros, you must install the full version of PowerPoint.
To switch a single slide to C#, perform the following steps:
1. Open the PowerPoint deck in PowerPoint.
2. On the Slide Show menu, click View Show.
3. Locate the slide that you want to switch to C#.
4. Click C# on the slide.
To switch a single slide to Visual Basic .NET, perform the following steps:
1. Open the PowerPoint deck in PowerPoint.
2. On the Slide Show menu, click View Show.
3. Locate the slide that you want to switch to Visual Basic .NET.
4. Click Visual Basic .NET on the slide.
Note You can switch a slide to C# or Visual Basic .NET at any time while
displaying the slides. Just click C# or Visual Basic .NET to switch between the
languages.
Module 7: Securing XML Web Services v
Module Strategy
Use the following strategy to present this module:
! Overview of Security
Ensure that students understand the difference between authentication and
authorization. Also, explain why encryption might be necessary even with
authenticated clients. Explain that the .NET Framework can assist with
authorization and authentication. Explain the limitations of using Windows
authentication and the IIS-supported authentication mechanisms.
! Built-In Authentication
Explain the authentication support that is built into the Windows operating
system and IIS. Explain the scenarios where Windows authentication is
appropriate and where it is inappropriate for Web services.
! Custom Authentication Using SOAP Headers
Explain how students can use SOAP headers to send authentication
information to a Web service. Explain the mechanics of using SOAP
headers. Be sure to explain how students can use SOAP headers to
communicate information from a client to a Web service or from a Web
service to a client. Also, point out that students can make a SOAP header
optional for a Web service method.
The example code in the topic "Using a SOAP Header in a Web Service" is
also located in the
install_folder\Democode\language\Mod07\SOAPHeaderAuthentication.txt
file.
The WSDL file example in the topic "Using a SOAP Header in a Web
Service Consumer" is also located in the
install_folder\Democode\language\Mod07\SoapHeaderWSDL.txt file.
! Authorization Using Role-Based Security
In this module, you will explain how to implement a custom role-based
authorization mechanism. You must explain why Windows discretionary
access control list (DACL) based authorization is often not appropriate in
Web service scenarios. Focus on how students can use GenericPrincipal
and GenericIdentity objects to implement custom authorization mechanism
and how this would be useful in the context of Web services.
The HelloWorld example Web method in the topic "Using
WindowsIdentity and WindowsPrincipal Objects" is also located in the
install_folder\Democode\language\Mod07\UsingIdentity.txt file.
vi Module 7: Securing XML Web Services
Overview
Types of Authentication
You will learn the details of these authentication mechanisms and how to use
them to secure a Web service later in this module.
ASP.NET authentication ASP.NET supports two new authentication mechanisms, which Active Server
Pages (ASP) did not support:
! Forms authentication
! Passport authentication
Passport authentication Passport is a centralized authentication service that Microsoft provides and that
offers a single logon feature and core profile services for member Web sites.
Both Forms authentication and Passport authentication are mentioned for the
sake of completeness. You cannot easily use either of these mechanisms within
a Web service. Both of these mechanisms present a logon screen that requires
interaction with an end user, and both support logon timing out. But a Web
service consumer cannot programmatically process the logon screen or handle a
timed-out logon condition.
Because it is not recommended that you use Forms and Passport authentication
within Web services, this module does not cover these authentications in any
further detail. It may become possible to use Passport for Web service
authentication in the future.
Custom SOAP header If you do not want to use built-in authentication mechanisms, then you can
authentication implement a custom authentication mechanism instead. You might beware of
passing user credentials as part of the parameter list for every method in your
Web service. In such a situation, you would need another way to pass the
credentials. SOAP headers are a convenient way to accomplish this task. A
Web service consumer can add user credentials to the SOAP header. The Web
service can then retrieve this information to perform custom authentication.
6 Module 7: Securing XML Web Services
Types of Authorization
The folder that contains the root of an ASP.NET application is the root of a
logical Universal Resource Identifier (URI) namespace. You can configure an
ASP.NET application to further restrict access to the application’s URI
namespace based on user identity or role. For example, you could restrict access
to subfolders below your application root.
This topic examines each of these authorization techniques in more detail.
Windows NT security Microsoft Windows NT provides security features that are based on user
identity and that prevent unauthorized access to system resources. These
features are user authentication and object-based access control. It is important
to note that with Windows security, after a user is authenticated, most code that
the user runs has access to all the resources that he or she can access.
Windows administrators can create discretionary access control lists (DACL)
that control access to resources or objects on a network. Administrators can
assign security descriptors that contain DACLs that list the users and groups
that are granted access to objects such as a files, printers, or services.
Role-based security Role-based security is a security model where the specific identity of the user is
not important. What is important are the logical roles that a user can assume.
Role-based security uses the roles that are associated with a user to make
decisions about security authorizations.
Module 7: Securing XML Web Services 7
Code access security Code access security is a security mechanism that you can use to prevent code
from accessing protected resources. Just like role-based security, code access
security requires that the user first be authenticated before code access security
can operate.
Configuring You can further control authorization to parts of an ASP.NET application’s URI
authorization in an namespace with the <authorization> section of an ASP.NET application
ASP.NET application configuration file (Web.config). To use ASP.NET authorization, you place
either a list of users or roles, or both, in the allow or deny elements of the
<authorization> section of Web.config.
To define the conditions for accessing a particular folder, place a Web.config
file that contains an <authorization> section in that folder. The conditions set
for that folder also apply to its subdirectories, unless configuration files in a
subdirectory override them. The syntax for the <authorization> section is as
follows:
<[allow|deny] [users] [roles] [verbs] />
For an allow or deny element, you must specify either the users or the roles
attribute. You can include both attributes, but both are not required together in
an allow or deny element. The verbs attribute is optional.
The allow and deny elements grant and revoke access, respectively. Each of
these elements support three attributes, which are defined in the following table.
Attribute Description
The following example grants access to Mary, while denying it to Adam and all
anonymous users (“?” indicates anonymous users):
<configuration>
<system.web>
<authorization>
<allow users="CONTOSO\Mary"/>
<deny users="CONTOSO\Adam" />
<deny users="?" />
</authorization>
...
8 Module 7: Securing XML Web Services
Methods of Encryption
! No encryption
If the communicated data is not sensitive, a performance penalty should not
be incurred by encrypting any part of the communication.
! Partition your Web service
The idea here is to factor the service interface into groups of messages that
require encryption and those that do not. You can then implement the
interface by using two Web services—one for the methods that require
encryption and one for the methods that do not. Using two Web services
allows you to easily secure only the methods that require encryption, and to
avoid a performance penalty for those methods that do not.
Encryption options There are many different options for encrypting communications, two of which
are: Secure Sockets Layer (SSL) and custom SOAP extensions.
! Secure Sockets Layer
Using SSL is a simple way to encrypt the entire communication between a
Web service consumer and a Web service.
! Custom SOAP extensions
If you need more detailed control, you can implement a custom SOAP
extension to encrypt only sensitive data. You can transfer data that is not
sensitive unencrypted, therefore providing better performance than SSL.
10 Module 7: Securing XML Web Services
Not
Digest authentication The most recent industry standard development in Web security is the Digest
authentication specification. Digest authentication is slated to be a replacement
for the Basic authentication. The World Wide Web Consortium (W3C)
endorsed Digest authentication to fix the security gaps in the Basic
authentication mechanism.
Digest authentication uses a hashing algorithm to form a hexadecimal
representation of a combination of user name, password, the requested resource,
the HTTP method, and a randomly-generated value that the server returns.
Hashing is a one-way process of passing authentication credentials. The result
of this process is called a hash, or message digest, and it is not feasible to
decrypt it. That is, the original text cannot be deciphered from the hash.
Digest authentication is not as secure as Kerberos or a client-side key
implementation, but it does represent a stronger form of security than Basic
authentication.
Digest authentication is an HTTP 1.1 specification, which requires that a client
be compliant with this specification. Because a hashing function must encrypt
the user name and password, the browser must perform the hashing prior to
submitting it to the server. If an IIS 5.0 virtual directory has Digest
authentication enabled, a request from a browser that is not HTTP 1.1-
compliant will generate an error in the client request. Microsoft
Internet Explorer 4.0 was the first HTTP 1.1-compliant browser available from
Microsoft.
Module 7: Securing XML Web Services 13
For Kerberos v5 authentication to be successful, both the client and server must
have a trusted connection to a Key Distribution Center (KDC) and be Active
Directory directory services compatible. For more information about the
Kerberos protocol, see the Windows 2000 documentation.
14 Module 7: Securing XML Web Services
Limitations Although integrated Windows authentication is secure, it has its limitations too.
! Not all Web service clients support integrated Windows authentication.
However, Web service consumers using SoapHttpClientProtocol-derived
proxy classes (this includes proxy classes created with Wsdl.exe or
Microsoft Visual Studio® .NET) support integrated Windows authentication.
! Integrated Windows authentication does not work over HTTP proxy
connections.
! Additional TCP ports have to be opened in the firewall because Integrated
Windows authentication does not use port 80.
If you select Basic authentication, you must ensure that the accounts that can
access a Web service are granted permission to log on to the Web server that is
hosting the service. This is necessary because Basic authentication
impersonates a local user, and by default, domain accounts do not have
permission to log on to a Web server.
If you select Digest authentication, the Windows account that you configure
must be an account in a domain. The domain controller must also have a plain
text copy of the password that is used because it must perform a hashing
operation and compare the results with the hash that the browser sends.
If you select Integrated Windows authentication, the user will not be prompted
for credentials unless the authentication fails. Remember that Integrated
Windows authentication does not work across proxy servers or other firewall
applications.
Configuring an ASP.NET To use Windows (Basic, Digest, or Integrated Windows) authentication with a
Web service Web service, the authentication mode in the Web.config file must be set to
Windows, as shown in the following code:
<configuration>
<system.web>
<authentication mode = "Windows"/>
...
Accessing user identity Code in Web service methods can access identity information about an
in a Web service authenticated user by accessing the Context.User.Identity property. The
following sample code shows how to access the authenticated user’s name in a
Web service method.
C# code example [WebMethod]
public string HelloWorld()
{
return "Hello" + Context.User.Identity.Name;
}
Providing credentials Proxy classes that are created by using the Web Services Description Language
(WSDL) tool (Wsdl.exe) or when adding a Web reference in Visual Studio
.NET, derive from the SoapHttpClientProtocol class. These classes have a
Credentials property, which can be used to obtain or set security credentials for
Web service client authentication.
To use the Credentials property, a Web service client must create an instance
of a class implementing the ICredentials interface, such as the
NetworkCredential class. Then, the client must set credentials that are specific
to the authentication mechanism before making a call to a Web service method.
Module 7: Securing XML Web Services 17
1. Imports System.Web.Services
2. Imports System.Web.Services.Protocols
3.
4. Public Class AuthHeader
5. Inherits SoapHeader
6. Public Username As String
7. Public Password As String
8. End Class 'AuthHeader
9. Public Class AccountService
10. Inherits WebService
11. Public sHeader As AuthHeader
12. <WebMethod(), _
13. SoapHeader("sHeader")> _
14. Public Function GetAcctBalance(acctID As String) As Decimal
15.
16. End Function 'GetAcctBalance
17. End Class 'AccountService
Web services set the value of a header field for input headers before a method is
called, and retrieve the value for output headers when the method returns.
Disabling other To implement a custom authentication scheme by using SOAP headers, you
authentication types must also disable other authentication types in the Web.config file for your
Web service, as shown in the following code:
<configuration>
<system.web>
<authentication mode = "None"/>
</system.web>
</configuration>
Module 7: Securing XML Web Services 21
(continued)
57.
58. - <output>
59. <soap:body use="literal" />
60. </output>
61. </operation>
62. ...
63. </binding>
64. - <service name="Woodgrove Online Bank">
65. <documentation>Woodgrove banking services</documentation>
66. - <port name="Woodgrove Online BankSoap" !
67. binding="s0:Woodgrove Online BankSoap">
68. <soap:address location="http://www.woodgrovebank.com/!
69. woodgrove/bank.asmx" />
70. </port>
71. ...
72. </service>
73. </definitions>
The definitions that the preceding code implements can be described as follows:
! Lines 8 through 15 define a complex type named WoodgroveAuthInfo.
The type has two child elements, named Username and Password.
! Lines 6 through 7 define an element named WoodgroveAuthInfo of type
WoodgroveAuthInfo.
! Lines 30 through 33 define a message named
GetAccountWoodgroveAuthInfo.
! Lines 54 through 55 add a SOAP header, whose message is the
GetAccountWoodgroveAuthInfo, to the input communication of the
GetAccount operation.
Web service proxies and The following code shows part of the resulting proxy code that is generated for
SOAP headers the previous WSDL file.
C# code example [SoapHeaderAttribute("WoodgroveAuthInfoValue",
Required=false)]
//...other attributes omitted for brevity...
public Acct GetAccount(int acctID) {
...
Using SOAP headers After the proxy is generated, the consumer then directly sets the header for the
when invoking Web proxy class before making a method call that requires it. The following example
services shows how the header is populated with credential details.
C# code example WoodgroveOnlineBank bank = new WoodgroveOnlineBank();
WoodgroveAuthInfo authInfo = new WoodgroveAuthInfo ();
authInfo.Username = "Adam";
authInfo.Password = "password";
bank.WoodgroveAuthInfoValue = authInfo;
Acct acct = bank.GetAccount(1);
Identities
Principals
Principals and call All .NET Framework applications are hosted in an application domain. Each
context application domain has an object of type CallContext created for it.
A principal object is bound to a call context. When a new thread is created, the
call context will flow to the new thread. This means that the principal object
reference is automatically copied to the new thread’s call context. As a result,
there is always a principal and identity available on the current thread to allow
you to perform application-level authentication and authorization.
Note In role-based security, you can base the identity (and the principal it
helps to define) on either a Windows account or the identity can be a custom
identity unrelated to a Windows account. .NET applications can make
authorization decisions based on a principal's identity or role membership, or
both.
Module 7: Securing XML Web Services 29
You can also verify the role membership of a principal object by calling the
IsInRole method on that object, as shown in the preceding code. The preceding
code works, but it cannot be easily localized. The following example uses the
WindowsBuiltInRole enumeration instead, and can be more easily localized.
C# code example if (User.IsInRole(WindowsBuiltInRole.Administrator))
{
// only administrators can do this
}
The following Web service method returns identity and role information about
an authenticated user.
C# code example using System.Text;
using System.Security.Principal;
// Required for role-based security
...
[WebMethod]
public string HelloWorld()
{
// not required. Just shows the User property is an Identity
IIdentity identity = Context.User.Identity;
string name = User.Identity.Name;
bool isAuth = User.Identity.IsAuthenticated;
string identType = User.Identity.AuthenticationType;
bool isAdmin = User.IsInRole("Domain\\Administrators");
Implementing role-based The following procedure outlines the steps to implement role-based security
security in a Web within a Web service method by using GenericIdentity and GenericPrincipal
service objects.
To implement role-based security in a Web service method by using the
GenericIdentity and GenericPrincipal objects:
1. Create a new instance of the GenericIdentity class and initialize it with a
name that you want it to hold.
2. Create a new instance of the GenericPrincipal class and initialize it with
the GenericIdentity object that is created in the preceding step, and an
array of strings that represent the roles that you want to associate with this
principal.
3. Save the principal that is attached to the current thread.
4. Attach the principal that you created in step 2 to the current thread.
5. Execute code that requires a current principal context.
6. Reset the principal to the original value.
34 Module 7: Securing XML Web Services
To invoke your HttpModule for your Web service, the Web.config file must
contain the correct configuration information. The following is an example of
the required entries in Web.config.
<configuration>
<system.web>
<httpModules>
<add name="CustomAuthn"
type="WSHttpModule.CustomAuthenticationModule, WSHttpModule"
/>
</httpModules>
</system.web>
</configuration>
36 Module 7: Securing XML Web Services
Finally, you must handle the AuthenticateRequest event to set the principal for
the current Web operation invocation. The following code gives an example of
how this can be done.
C# code example public void OnAuthenticate(Object src, EventArgs e)
{
HttpApplication app = (HttpApplication)src;
HttpContext ctx = app.Context;
string soapUser;
string soapPassword;
XmlDocument dom = new XmlDocument();
Stream httpStream = ctx.Request.InputStream;
// Save the current position of stream.
long posStream = httpStream.Position;
try
{
dom.Load(httpStream);
httpStream.Seek(posStream,System.IO.SeekOrigin.Begin);
dom.Save(httpStream);
// Bind to the Authentication header.
soapUser =
dom.GetElementsByTagName("User").Item(0).InnerText;
soapPassword = dom.GetElementsByTagName
("Password").Item(0).InnerText;
// perform check for roles
string [ ] roles;
roles = GetRolesForUser(soapUser,soapPassword);
ctx.User = new GenericPrincipal(new
GenericIdentity(soapUser, "MyAuthType"), roles);
}
catch (Exception ex)
{
// Reset the position of stream.
httpStream.Position = posStream;
// Throw a SOAP exception.
XmlQualifiedName name = new XmlQualifiedName("Load");
SoapException soapException = new SoapException(
"Unable to read SOAP request", name, ex);
throw soapException;
}
}
Module 7: Securing XML Web Services 37
Authorization after After HttpModule has performed authentication, you can use .NET role-based
authentication security within the implementation of your Web service methods. The
following code is an example of how this can be done.
C# code example [WebMethod]
[SoapHeader("authentication")]
public string ValidUser()
{
if (!User.Identity.IsAuthenticated)
{
XmlQualifiedName name = new
XmlQualifiedName("AuthError");
SoapException soapException = new SoapException(
"Request denied", name);
throw soapException;
}
if (User.IsInRole("Customer"))
return string.Format("{0} is a customer",
User.Identity.Name);
if (User.IsInRole("Admin"))
return string.Format("{0} is an administrator",
User.Identity.Name);
return string.Format("{0} is a valid user",
User.Identity.Name);
}
Evidence-based security Evidence is a set of information about the identity and origin of an assembly.
Evidence might include any of the following:
! The assembly’s strong name, consisting of a unique public key, a simple
name, and a version.
! The assembly’s publisher, which is obtained from the Microsoft
Authenticode® signature.
! The zone from which the assembly originates, such as a local computer,
intranet, or Internet zones.
! The location from which the assembly originates, which can be in the form
of a URL, universal naming convention (UNC) path, or a local computer
folder.
! The cryptographic hash of the assembly.
Note When an assembly meets the membership condition for a code group, it
is said to be a member of that code group.
A membership condition for a code group can specify that the publisher of an
assembly is Microsoft. Therefore, only an assembly that provides evidence that
it is published by Microsoft will satisfy the membership condition and be
eligible to receive the permission set that is associated with the code group. For
this example, the permission set might represent the right to access the C:\Temp
directory and the USERNAME environment variable.
42 Module 7: Securing XML Web Services
Note The membership conditions closely match the evidence available for
assemblies, as shown in the preceding example.
Policy levels Security policy is organized into different policy levels. Each policy level
contains a hierarchy of code groups that determine the conditions for
permission grants. There are four policy levels:
! Enterprise-level policy. The network administrator specifies the enterprise-
level policy. This policy contains a code group hierarchy that applies to all
of the managed code on the entire network.
! Machine-level policy. The administrator of a local computer specifies the
machine-level policy. This policy contains a code group hierarchy that
applies to all managed code on the computer.
! User-level policy. The administrator or a user of a local computer specifies
the user-level policy. This policy contains a code group hierarchy that
applies to all managed code that a specific user runs.
! Application domain-level policy. An application domain host can specify
security policy to be applied to a code within an application domain,
provided that that host has been granted permission from the
SecurityPermission class. You can set application domain-level policy only
once for any application domain. After an application domain policy is set,
further attempts to set this policy fail.
In each security policy level, code groups are organized hierarchically. The root
of the hierarchy is a code group that matches all of the code. This root code
group has child code groups and, in turn, those code groups can have children.
When an assembly is loaded, the common language runtime checks the
membership condition for a code group. If the evidence that the assembly
provides satisfies the membership condition of a parent code group, then each
child code group of that parent will be evaluated against the assembly to see
whether their membership conditions satisfy the assembly. However, if an
assembly does not meet the membership condition for a parent code group, the
conditions of the descendants of that group will not be checked. Therefore, each
level of children in the hierarchy implies an AND condition with its parent in
the hierarchy.
When an assembly is loaded, the membership conditions for each code group
within each policy level are verified against the evidence of an assembly. For
most code groups, the union of the permission sets for the code groups that
have their conditions met is computed. This union of permission sets represents
the assembly’s permission set for that policy level. The intersection of these
permission sets across all the policy levels determines the final permission set
that an assembly receives.
Named permission sets An administrator can associate a set of permissions with a code group by using
a named permission set. A named permission set must consist of at least one
permission; must have a name; and must have a description. You can associate
more than one code group with a named permission set.
The common language runtime provides the following built-in named
permission sets: Nothing, Execution, Internet, LocalIntranet, Everything,
and FullTrust. You can also create custom-named permission sets.
Module 7: Securing XML Web Services 43
Identifying permissions You can identify the permissions that your code requires by using several
required by your code different approaches.
The .NET Framework SDK documentation lists the permissions that are
required to use each of the .NET Framework classes. By referring to the
documentation for the classes that are used in your Web service, you can have a
good estimate of the permissions that your Web service code will need.
Also, a familiarity with the built-in permission classes will help in determining
the permissions that your code requires. For example, if you know that a
MessageQueue permission exists, you can predict that your code will need this
permission to use the Microsoft Message Queue libraries.
Another means of determining the permissions that your code will need is to
test it with a limited set, such as the Internet permission set. You can then see
the security exceptions that the code throws.
After determining the permissions that your assembly needs, you can negotiate
with ISP administrators for a more liberal security policy specifically for your
assembly.
Requesting permissions It is possible to specify permission requests for your assembly by using the
in your code SecurityPermission attribute. This attribute is stored in the metadata of your
assembly. The assembly permission requests are examined when an assembly is
loaded. The .NET Framework proceeds based on the kind of permission request
that the assembly makes. The three kinds of permission requests are:
! Minimum permissions (RequestMinimum)
The permissions in these requests represent the minimum set of permissions
that an assembly needs to work effectively. If these permissions are not
available to an assembly when it is loaded, the .NET Framework will not
execute the code in that assembly and returns an exception to the caller. A
minimum permission request for an assembly documents the required
permissions for that assembly. Not making a minimum permission request
for an assembly is the equivalent of making a minimum permission request
of Nothing.
! Optional permissions (RequestOptional)
The permissions in these requests represent permissions that an assembly
can use, but the assembly can still run effectively without these permissions.
These permissions are granted to an assembly if they are available to that
assembly, but if they are not available, the assembly is still allowed to run.
Not making an optional permission request for an assembly is the equivalent
of making an optional permission request of FullTrust.
! Refused permissions (RequestRefused)
The permissions in these requests represent permissions that an assembly
can never be granted, even if a security policy allows these permissions to
be granted. Not making a refused permission request is the equivalent of
making a refused permission request of Nothing.
Module 7: Securing XML Web Services 45
Typically, you add the preceding code to the AssemblyInfo file in your Web
service project.
By using reflection, an administrator can view the permission set that an
assembly minimally requires and set the security policies accordingly.
It is a good practice to annotate your assembly by setting the
SecurityPermission attribute to a minimum permission set. This can be
particularly helpful if you deploy your assembly on a system where you do not
have any control over setting the security policy.
46 Module 7: Securing XML Web Services
Lesson: Encryption
Using SSL
How to enable SSL on a If you want to enable SSL on your Web server after you obtain a certificate,
Web server you must install the certificate. You install the certificate from the Directory
Security tab in the Properties dialog box for a Web site or a virtual directory,
as shown in the illustration:
Before using a SOAP extension for encryption, you must be familiar with some
of the .NET Framework classes that will help in implementing such an
extension.
The DESCryptoService- The DESCryptoServiceProvider class provides access to the Cryptographic
Provider class Service Provider (CSP) version of the Data Encryption Standard (DES)
algorithm. Using this encryption service provider, you can create an encryptor,
given a key and an initialization vector (IV).
C# code example encryptor = des.CreateEncryptor(key, IV);
The CryptoStream class A CryptoStream is a stream that links data streams to cryptographic
transformations. By simply writing or reading to this stream, you can encrypt or
decrypt data. You can create a CryptoStream object after you have an
encryptor or decryptor object. The following code shows how to do this.
C# code example ICryptoTransform encryptor;
ICryptoTransform decryptor;
encryptor = des.CreateEncryptor(key, IV);
decryptor = des.CreateDecryptor(key, IV);
CryptoStream cs;
cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
. . .
cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
Dim cs As CryptoStream
cs = New CryptoStream(ms, encryptor, CryptoStreamMode.Write)
. . .
cs = New CryptoStream(ms, decryptor, CryptoStreamMode.Read)
Encryption using SOAP The .NET Framework makes it possible to hook into the serializing and
extensions deserializing process for SOAP messages. You hook into these processes by
implementing:
! A class derived from the SoapExtension class, which is found in the
System.Web.Services.Protocols namespace.
! A custom attribute that references the custom SOAP extension class.
To encrypt and decrypt messages by using SOAP extensions, you must apply
the custom attribute that references the SOAP extension to the appropriate Web
service methods.
Note If you are implementing a Web service consumer by using the .NET
Framework, then you can also apply the custom attribute to the proxy class
methods that correspond to the Web service methods that have the custom
attribute applied.
Module 7: Securing XML Web Services 51
Note You can find the code that is used for this walkthrough in the file
install_folder\Democode\language\Mod07\EncryptionExtension (.cs or .vb).
52 Module 7: Securing XML Web Services
Note You can find the code that is used for this walkthrough in the file
install_folder\Democode\language\Mod07\EncryptionExtensionAttribute(.cs
or .vb).
Module 7: Securing XML Web Services 53
Note You can find the code that is used for this walkthrough in the file
install_folder\Democode\language\Mod07\UseEncryptAttribute.txt.
54 Module 7: Securing XML Web Services
Review
3. If the users of your Web service do not have Windows accounts, how can
you provide authentication information to the Web service?
By defining a SOAP header representing the required information and
requiring that a SOAP header be used in your Web service.
5. Which attribute should you use to request permissions for the assemblies in
your Web service?
SecurityPermission
6. Which class does the .NET Framework provide to allow the developer to
hook into the SOAP serialization/deserialization process?
SoapExtension
56 Module 7: Securing XML Web Services
Note This lab focuses on the concepts in this module and as a result may not
comply with Microsoft security recommendations. For instance, this lab does
not comply with the recommendation that you do not use weak passwords or
that you do not hard code passwords into an application.
Lab Setup For each lab exercise in this course, you have the option of coding in either C#
or Visual Basic .NET. In order to avoid unnecessary instructions, the following
placeholders will be used throughout the lab exercises:
install_folder The install folder for the course content. Usually this will
be the folder C:\Program Files\Msdntrain\2524.
lab_root The folder install_folder\Labfiles\CS or
install_folder\Labfiles\VB, depending on the language you
are using for the lab exercises.
It is recommended that you select only one language for the lab exercises
There are starter and solution files that are associated with this lab. The starter
files are in the folder lab_root\Lab07\Starter. The solution files are in the folder
lab_root\Lab07\Solution.
If you completed Lab 5, Implementing a Simple XML Web Service, in Module
5, “Implementing a Simple XML Web Service,” in Course 2524, Developing
XML Web Services Using Microsoft ASP.NET, skip the following procedures in
this section.
Module 7: Securing XML Web Services 57
! Set up Contoso Web service solution, if you did not complete Lab 5
• Copy the lab_root\Lab05\Solution\Contoso folder to C:\Inetpub\wwwroot
folder, and overwrite the Contoso project that you created in Lab 5.
! Set up Contoso Web service solution, if you did not start Lab 5
1. Copy the lab_root\Lab05\Solution\Contoso folder to the
C:\Inetpub\wwwroot\Contoso folder.
2. Create the virtual directory for the Contoso Web Service:
a. Click Start, click Control Panel, click Performance and
Maintenance, click Administrative Tools, and then double-click
Internet Information Services.
b. Expand the tree to Default Web Site.
c. Right-click Default Web Site, point to New, and then click Virtual
Directory.
d. Complete the Virtual Directory Creation Wizard by using the
information in the following table.
On this wizard page Do this
Scenario In this lab, you will modify the Contoso Micropayment Web Service to use
SOAP headers that contain authentication information. You will then modify
the Web service to encrypt these headers by using a SOAP Extension that is
provided to you.
You will also modify the Woodgrove and Contoso Account Manager
application to add encrypted SOAP headers to Web service method calls to both
the Contoso Micropayment and the Woodgrove Online Bank Web services.
Estimated time to
complete this lab:
60 minutes
58 Module 7: Securing XML Web Services
Exercise 0
Setting up the Woodgrove Web Service
If you did not previously create a virtual directory for the Woodgrove Web
service, do so now.
Exercise 1
Authenticating Using SOAP Headers
In this exercise, you will add the SoapHeader attribute to Contoso
Micropayment Web service methods to include authentication information in a
SOAP header. You will also modify the Woodgrove and Contoso Account
Manager to add authentication information to SOAP headers for the
Woodgrove and Contoso Web service methods.
Important If you did not start or complete Lab 5, refer to the Lab Setup
section at the beginning of this lab for additional instructions.
Notice that the SoapHeader attribute refers to the authInfo data member of
the Micropayment class. The authInfo data member is of type
ContosoAuthInfo. The ContosoAuthInfo data type was defined as follows
in Lab 5.
C# public class ContosoAuthInfo : SoapHeader
{
public string Username;
public string Password;
}
! Add SOAP headers to Web service method calls in the Woodgrove and
Contoso Account Manager application
1. In Visual Studio .NET, open the Woodgrove and Contoso Account Manager
project that you worked on in Lab 5.
Important If you did not start or complete Lab 5, then use the Woodgrove
and Contoso Account Manager project found in the folder
lab_root\Lab07\Starter. Otherwise, continue to use the Woodgrove and
Contoso Account Manager project that you worked on in Lab 5.
Note The Web reference must be updated. This allows the proxy class
generator to detect that the Web service methods GetAccount and
GetTransactionHistory now support a SOAP header. The proxy class
GetAccount and GetTransactionHistory will be re-created to also support
SOAP headers.
ContosoAuthInfo.Username contosoUserID
ContosoAuthInfo.Password contosoPassword
Important The code for steps 7 and 8 must be inserted before the
GetTransactionHistory method call.
Module 7: Securing XML Web Services 61
WoodgroveAuthInfo.Username woodgroveUserID
WoodgroveAuthInfo.Password woodgrovePassword
Important The code for steps 11 and 12 must be inserted before the
GetTransactionHistory method call.
If GetLogonInfo("Contoso", contosoUserID, _
contosoPassword) Then
Me.GetContosoAccountInfo()
End If
John Password
Jane Password
b. Similarly, use the following valid Contoso user IDs to verify that
authentication takes place.
UserID Password
John Password
Jane Password
3. To invoke the Woodgrove and Contoso Web service methods that use
SOAP header authentication, in the Contoso Micropayment Service
section, click Update Account Info and Get Transaction History.
If the Web method calls execute successfully, then the SOAP header
authentication was successful.
4. Enter invalid user IDs or passwords for both Woodgrove and Contoso. The
Web service methods will cause an exception to be thrown.
64 Module 7: Securing XML Web Services
Exercise 2
Encrypting Using the SOAP Encryption Extension
In this exercise, you will add functionality to encrypt SOAP authentication
headers that are sent from the client to the Contoso Web service and decrypt the
headers that the Web service receives.
! Encrypt SOAP headers sent from the Woodgrove and Contoso Account
Manager to the Contoso Web service
1. In the Woodgrove and Contoso Account Manager project, add a reference to
the provided EncryptionExtension assembly.
a. On the Project menu, click Add Reference.
b. In the Add Reference dialog box, on the .NET tab, click Browse.
c. Browse to lab_root\WebServicesSolution\Utils.
d. Click EncryptionExtension.dll, and then click Open.
e. Click OK to add the reference.
2. Open Class View.
3. Expand the ContosoMicropaymentService class in the
WebServiceClient.Micropayment namespace.
4. Double-click the GetAccount method to open the proxy class
implementation for this method in the Reference(.cs or .vb) file.
5. Add the following method attribute.
C# [EncryptionExtension(Encrypt=EncryptMode.Request,
!SOAPTarget=Target.Header)]
The Encrypt and SOAPTarget properties specify that the encryption target
is the SOAP header, which must be encrypted when a Web service method
request is sent.
The EncryptionExtension attribute must be applied after the
SoapDocumentMethodAttribute attribute.
6. Add the same EncryptionExtension attribute to the
GetTransactionHistory method of the ContosoMicropaymentService
proxy class.
7. Build the application.
Module 7: Securing XML Web Services 65
! Decrypt the SOAP headers that the Contoso Web service receives
1. Open the Contoso Micropayment Web service project.
2. Add a reference to the provided EncryptionExtension assembly.
a. On the Project menu, click Add Reference.
b. In the Add Reference dialog box, on the .NET tab, click Browse.
c. Browse to lab_root\WebServicesSolution\Utils.
d. Click EncryptionExtension.dll, and then click Open.
e. Click OK to add the reference.
3. Open the code-behind file for Micropayment.asmx.
4. Add the following method attribute to the GetAccount and
GetTransactionHistory Web methods, after the SoapHeader attribute:
C# [EncryptionExtension(Decrypt=DecryptMode.Request,
!SOAPTarget=Target.Header)]
The Decrypt and SOAPTarget properties specify that the decryption target
is the SOAP header, which must be decrypted when a Web service method
request is received.
5. Build the Web service.
! Test
1. Run the Woodgrove and Contoso Account Manager application.
2. To test the Contoso Micropayment Web Service functionality, in the
Contoso Micropayment Service section, click Update Account Info and
Get Transaction History.
If the Web method calls execute successfully, then the SOAP header
authentication was successful.
66 Module 7: Securing XML Web Services
Exercise 3
Using Role-Based Security
In this exercise, you will add a new method named DeleteAccount to the
Contoso Micropayment Web Service. Only Woodgrove administrators will be
authorized to delete a user account by using this method. The DeleteAccount
method will authenticate against the database and use role-based security to
authorize access to the code that deletes the account.
The DeleteAccount method will call the _AuthenticateAdmin stored
procedure to authenticate an administrator against a table in the Contoso
database. This stored procedure returns a set of application-defined roles that
are associated with the authenticated administrator. You will use these roles to
create a GenericPrincipal object and implement role-based security. You will
then associate this GenericPrincipal object with the current thread and call a
method in an external assembly, named ContosoAdminDB.dll, to actually
delete the account. The method in the external assembly will test that the user
associated with the current thread has the correct role membership authorized to
delete an account.
Note The ContosoAdminDB.dll provided as a part of the starter files will not
actually delete the accounts.
\
! If you did not create a data connection in Lab 5, add a new database
connection
Note Only complete this section if you did not create a data connection in
Lab 5.
4. When prompted, type the password again, and then click OK.
5. Locate the test of the nRecords variable at the bottom of the copied code. If
the returned dataset contains records (nRecords is not equal to zero), then
allocate an array of strings that is the length of the numbers of records.
6. Loop through the RolesDataSet and add an element in the string array for
each role in the RolesDataSet.
The role is specified by the Role property of the item in the
RolesDataSet._AuthenticateAdmin collection. The following code is an
example of how to store the list of roles in a string array.
C# if (nRecords != 0)
{
string [] roles;
roles = new string[nRecords];
for (int i = 0; i < nRecords; i++)
{
roles[i] = ds._AuthenticateAdmin[i].Role;
}
. . .
10. Add a finally clause that restores the current thread principal to the saved
reference.
The following code is an example of how to perform these steps.
C# GenericIdentity ident = new GenericIdentity(AdminUserName);
GenericPrincipal principal = new GenericPrincipal(ident,
roles);
IPrincipal principalSave =
System.Threading.Thread.CurrentPrincipal;
try {
System.Threading.Thread.CurrentPrincipal = principal;
AdminUtil.DeleteAccount(AccountID.ToString());
return true;
}
catch(Exception e) {
return false;
}
finally {
System.Threading.Thread.CurrentPrincipal =
principalSave;
}
Try
System.Threading.Thread.CurrentPrincipal = principal
ContosoAdminDB.AdminUtil.DeleteAccount _
(AccountID.ToString())
Return True
Catch e As Exception
Return False
Finally
System.Threading.Thread.CurrentPrincipal = principalSave
End Try
Course Evaluation
Contents
Overview 1
Data Type Constraints 2
Lesson: Performance 11
Lab 8.1: Implementing Caching in an
XML Web Service 28
Reliability 35
Versioning 39
Lesson: HTML Screen Scraping
Web Services 41
Lesson: Aggregating Web Services 49
Review 55
Lab 8.2: Implementing an Aggregated
XML Web Service 57
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.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 8: Designing XML Web Services iii
Instructor Notes
Presentation: This module teaches students which design issues to consider when designing
60 Minutes real-world XML (Extensible Markup Language) Web services. The issues
discussed are related to data type constraints, performance, reliability,
Labs: versioning, deployment in Internet Service Provider (ISP) and Application
100 Minutes Service Provider (ASP) scenarios, and aggregating Web services. The module
also discusses HTML screen scraping as a pseudo Web service.
After completing this module, you will be able to:
! Identify the restrictions that the various Web services protocols impose on
data types.
! Explain how the use of Application and Session state can affect the
performance and scaling of Web services.
! Explain how to use output and data caching to improve Web service
performance.
! Explain how to implement asynchronous Web methods.
! Explain the need for instrumenting Web services.
! Identify the components of a Web service that can be versioned.
! Explain how to implement a virtual Web service by using screen scraping.
! Implement a Web service that uses multiple Web services.
! Identify the tradeoffs in the techniques that are used for exposing aggregated
Web services.
Required Materials To teach this module, you need the Microsoft® PowerPoint® file 2524C_08.ppt.
Preparation Tasks To prepare for this module:
! Read all of the materials for this module.
! Practice all of the demonstrations.
! Review the walkthrough code files in the
install_folder\Democode\language\Mod08.
! Complete the labs.
iv Module 8: Designing XML Web Services
This section provides demonstration procedures that are not appropriate for the
student notes.
This creates a file named sales (.cs or .vb) that implements the proxy class
for the Scrape Web service.
Module Strategy
Use the following strategy to present this module:
! Data Type Constraints
Explain that even though Microsoft ASP.NET Web services support a rich
set of data types, not all of the Microsoft .NET Framework data types are
appropriate for Web services. Tell the students that Simple Object Access
Protocol (SOAP) is the preferred protocol for Web services. Explain how
using Hypertext Transfer Protocol (HTTP)-GET and POST methods limit
the types of data that a Web service can support. Teach the module as a set
of tradeoffs. Explain to the students that circumstances may dictate different
choices in different scenarios.
! Performance
Start out by discussing general performance considerations. Then, examine
the issues that the students must consider when implementing Web services
by using Microsoft ASP.NET. Finally, discuss the ASP.NET output and
data caching capabilities and how they can be used in Web services.
! Reliability
In this topic, discuss how the .NET common language runtime enables
better application reliability without compromising on performance. Also,
explain how the ASP.NET process recovery model enhances reliability by
supporting automatic restart of applications if the Aspnet_wp.exe worker
process fails, and by allowing scheduled restarts to reclaim leaked
resources. Also, emphasize the importance of having the ability to monitor
the health of a running Web service to support early detection of impending
application failure.
! Versioning
Explain that all developers of Web services will have to address issues with
versioning. Emphasize that Web Services Description Language (WSDL)
documents should not be versioned for production Web services. Discuss
strategies for handling evolving interfaces by using generic XML fragments.
Do not get into an in-depth discussion on assembly versioning. Rather, refer
the students to Course 2350, Securing and Deploying Microsoft .NET
Assemblies.
viii Module 8: Designing XML Web Services
Overview
The key points to remember when choosing the protocol for your Web service
are:
! GET and POST support only primitive data types (int, string, and others),
enumerations, and arrays of primitives.
These data types are passed as name/value pairs.
! SOAP supports rich data types by packaging data in XML and standardizing
the call format.
! SOAP provides for a rich extensibility mechanism.
It might seem obvious that it is best to choose SOAP as the protocol for your
Web service, but there are a few other issues to consider:
! HTTP-GET and HTTP-POST are much more widely used than SOAP, and
therefore, you are limiting the clients that can use your Web service.
! SOAP requests use a lot more bytes to transmit data than HTTP-GET or
HTTP-POST requests.
! By default, ASP.NET-based Web services support all of the three protocols
as long as you restrict the Web service methods to use only simple data
types.
4 Module 8: Designing XML Web Services
If you want to restrict the protocols that your Web service supports, you can
make an entry in Web.config. The following code shows how to remove HTTP-
GET and HTTP-POST protocols, so that the Web service supports only SOAP.
<configuration>
<system.web>
<webServices>
<protocols>
<remove name="HttpGet" />
<remove name="HttpPost" />
</protocols>
</webServices>
</system.web>
</configuration>
Note If you remove the HTTP-GET protocol, you will not be able to test your
Web service methods by using the Web Service Method Description page
provided for a Web service project in Microsoft Visual Studio® .NET.
Structures vs. classes It is very important to remember that Web services are not about object
remoting. When a Web service method returns an object, the public fields and
properties of the object are remoted. None of the functionality of the class is
remoted. As a result, from a Web service consumer’s perspective, classes and
structures are superficially indistinguishable.
The following code demonstrates how the XML Schema Definition Language
(XSD) allows you to define derived data types.
C# code example public class Acct
{
public string description;
public string number;
public string type;
public decimal balance;
public string status;
}
<s:complexType name="CreditCardAcct">
<s:complexContent mixed="false">
<s:extension base="s0:Acct">
<s:sequence>
<s:element minOccurs="1" maxOccurs="1"
name="payperiod" type="s:int" />
</s:sequence>
</s:extension>
</s:complexContent>
</s:complexType>
Even though you can define derived types by using XSD in the .NET
environment, you may not derive a new type from a structure. Because a class
and a structure are so similar and structures have additional restrictions, classes
are generally preferred to structures as data types in Web service methods.
6 Module 8: Designing XML Web Services
Typed vs. untyped Datasets can be typed or untyped. A typed dataset is a dataset that is derived
datasets from a base DataSet class and has an XML schema file (an .xsd file) that
defines the tables and fields that the dataset encapsulates. You typically use the
schema when generating a typed dataset to define strongly typed accessors for
the tables and fields that the dataset encapsulates.
Because a typed DataSet class inherits from a base DataSet class, the typed
class inherits all of the functionality of the base class and can be used with
methods that take a dataset as a parameter.
In contrast, an untyped dataset has no corresponding built-in schema. Similar to
a typed dataset, an untyped dataset contains tables, columns, and other similar
elements, but these are exposed only as collections.
You can use either typed or untyped datasets in your Web service. However,
using typed datasets makes programming with datasets easier and less error-
prone.
Data access using typed The class for a typed dataset has an object model in which its tables and
vs. untyped datasets columns become first-class objects in the object model. For example, if you are
working with a typed dataset, you can refer to a column in a table contained in
the dataset by using code similar to the following.
C# code example string s;
s = dsCustomersOrders.Customers[0].CustomerID;
In contrast, if you are working with an untyped dataset, the equivalent code is
the following.
C# code example string s;
s = (string)dsCustomersOrders.Tables["Customers"].
Rows[0]["CustomerID"];
Accessing tables and columns in a typed dataset is also slightly faster at run
time because the access path is determined at compile time. This eliminates the
need to look up tables and columns in collections at run time.
Module 8: Designing XML Web Services 7
When to use untyped Even though typed datasets have many advantages, there are a variety of
datasets circumstances in which an untyped dataset is useful. Some of these
circumstances are when:
! There is no schema available for the dataset.
There may not be an available schema if you are using a third-party
component that returns a dataset.
! The data you are working with does not have a static, predictable structure.
! A dataset might be created dynamically, and you do not want to define a
schema.
Arrays vs. collections The .NET Framework provides a number of collection classes like HashTable,
ArrayList, and other classes. A collection is just an unordered set of object
references. When you return an instance of a collection class to a Web service
consumer, it is no different than returning object[].
In general, it is preferable to make your Web service interface as strongly typed
as possible. If you decide to use a collection in your Web service, it is still very
easy to return an array of the stored type.
The following code returns strongly typed arrays of type Acct instead of type
object.
C# code example [WebMethod]
[XmlInclude(typeof(CreditCardAcct))]
[XmlInclude(typeof(SavingsAcct))]
[return:XmlArray("AccountList")]
[return:XmlArrayItem("Account")]
public Acct[] GetAllAccounts()
{
SavingsAcct a = new SavingsAcct();
CreditCardAcct cc = new CreditCardAcct();
return (Acct[])listOfAccts.ToArray(typeof(Acct));
}
8 Module 8: Designing XML Web Services
Almost the only time that there is a need to return collections or arrays of type
object is when a collection contains a heterogeneous list of objects. However,
this is not a very common design pattern and in such cases, the returned
collection can be an instance of a class or structure.
Exceptions When implementing a Web service method, if an error occurs, you can either
return an error code or throw an exception. Depending on the error handling
method that you choose, there are certain advantages and disadvantages.
If you simply return error codes, the code values will be reliably returned, but
developers often fail to check return codes.
On the other hand, if you throw an exception and the protocol that is used to
access the Web service is not SOAP, the Web service consumer will only
receive an HTTP error with the error code value of 500.
If a Web service consumer invokes a method by using SOAP, the exception is
caught on the server and wrapped inside a new object of a type SoapException.
A SoapException can either be thrown by the common language runtime or by
a Web service method. The common language runtime can throw a
SoapException if a response to a request is not formatted correctly. Web
service methods can generate a SoapException by simply throwing an
exception within the method. The following code shows a Web service method
that throws a custom exception.
Module 8: Designing XML Web Services 9
The following code shows a Web service consumer that catches the exception.
Note that the exception is a SoapException and is not a ContosoException.
C# code example ContosoBank.PaymentService ps;
ps = new ContosoBank.PaymentService();
try {
double amt = ps.LoanPayments(205000.0, 0.0712, 30, 0);
Console.Writeline("Monthly payments are {0}", amt);
}
catch (SoapException se) {
MessageBox.Show(se.Message,"LoanPayment Exception");
}
Also, note that the exception that the Web service throws is not lost. The
Message property of the custom exception is propagated as part of the Message
property of the SoapException.
Module 8: Designing XML Web Services 11
Lesson: Performance
General Considerations
Locking Locking is not usually a problem in Web services unless you are using the
Application object to store updateable state. The locks that are acquired on
resources, such as database tables, will probably cause more problems.
The easiest way to protect read/write data is to use a single lock for all the data
that you must protect. This is a simple approach, but results in serialization
problems. Every thread that attempts to manipulate the data must wait in line to
acquire the lock. If a thread is blocked on a lock, it is not doing useful work. If
a server is underutilized, multiple threads that are blocked on a lock are seldom
a problem because only one thread is likely to acquire the lock at a time. If a
server is under a heavy load, a high-contention lock can become a huge
problem.
There are several techniques that can reduce lock contention:
! Do not be overprotective of your data, that is, do not lock data when it is not
required. Hold locks for the duration necessary, and no longer. It is
important not to hold locks unnecessarily for large sections of code or
frequently executed sections of code.
! Partition your data so that you can use a disjoint set of locks to protect the
partitioned data. For example, you could partition a customer list on the first
letter of the customer’s company name, and you could use a separate lock to
protect each partition.
! Use the Interlocked class in the System.Threading namespace to
atomically modify data without acquiring a lock.
! Use multireader/single-writer locks when the data is not modified often.
Using this strategy, you can achieve better concurrency, though the lock
operations will be more expensive and you risk starving writers.
Making asynchronous If you must execute an operation that takes a significant amount of time, then
calls use asynchronous calls to execute the operation. For example, if your Web
service calls another Web service in a method named GetAccountHistory, then
you should use the Beginxxxx/Endxxxx methods of the proxy for the second
Web service. If the GetAccountHistory method does not immediately require
the data from the second Web service, then you could call the Beginxxxx
method at the start of the GetAccountHistory method, and then call the
Endxxxx method at the point that you require the data.
The following code demonstrates how an asynchronous call to a Web service
method can be made from within another Web service method.
C# code example Contoso.PaymentService ps = new Contoso.PaymentService();
IAsyncResult res = ps.BeginGetAccountInfo(1234,callback,null);
Account acct;
if (res.IsCompleted)
acct = ps.EndGetAccountInfo(res);
Measuring performance Without measurements, you do not understand your application's behavior. The
and behavior .NET Framework provides a number of tools for measuring the performance
and behavior of your Web service.
Measurement encompasses black-box measurement and profiling. Black-box
measurement is gathering the numbers that are exposed by external testing tools
(throughput, response times) and performance counters (memory usage, context
switches, CPU utilization). Many of the metrics that are measured are external
to your code, but it is a good practice to instrument your code to allow for
performance measurement, even when your Web service is deployed.
When you consider how much instrumentation to build into your Web service,
there are a number of tradeoffs. It is true that instrumenting your code results in
some performance degradation. However, the possibility of performance
degradation must be balanced with an evaluation of the risk inherent in not
instrumenting your code. Instrumentation in code is not just a feature of debug
builds of applications. Even after your Web service is deployed into production,
you must monitor the performance of the Web service.
Unnecessary code It is common for developers to not revisit code that has been written if it
functions correctly. However, this often means that unnecessary code and
inefficient code remains in the application. The following code contrasts two
functionally equivalent calls to the Trace.Write method. In the second call, the
WriteIf function is called whether or not the message is written. In this
example, the code that tests the switch before making the call to Trace.Write is
preferred.
C# code example if (mySwitch.TraceVerbose) Trace.Write("Deposit failed");
Trace.WriteIf(mySwitch.TraceVerbose,"Deposit failed");
.NET-Specific Considerations
You can also disable session state for each Web service method. To disable
session state for an application, set the mode attribute to off in the sessionstate
configuration section in the application’s Web.config file.
<sessionstate mode="off" />
16 Module 8: Designing XML Web Services
Avoid exceptions Because exceptions cause significant performance degradations, you should
never use them as a way to control normal program flow. If it is possible to
detect a condition that would cause an exception in your code, then you should
do that instead of waiting to catch the exception itself before handling that
condition.
Use native database The .NET Framework provides two data providers: the OLE DB data provider
providers and the SQL) data provider. The SQL data provider is recommended for
building high-performance Web applications.
Stored procedures vs. When using the managed Microsoft SQL Server provider, you can receive an
ad-hoc queries additional performance boost by using compiled stored procedures instead of
ad-hoc queries. For information about using SQL Server stored procedures, see
Course 2389B, Programming with ADO.NET.
Use the SqlDataReader class for a fast forward-only data cursor. The
SqlDataReader class provides a means to read a forward-only data stream that
is retrieved from a SQL Server database. While creating an ASP.NET Web
service, you might encounter situations that allow you to use SqlDataReader.
The SqlDataReader class offers higher performance than the DataSet class.
This is because SqlDataReader uses the Tabular Data Stream (TDS) protocol
to read data directly from a database connection.
Use ASP.NET Web The ASP.NET process recovery model enables scalability on multiprocessor
gardening computers by distributing work to several processes, one per CPU, each with
processor affinity set to its CPU. This technique is called Web gardening, and
can dramatically improve the performance of certain applications.
Disable debug mode Always remember to disable debug mode before deploying a production
application or conducting any performance measurements. The following
example code shows how to disable the debug mode:
<configuration>
<system.web>
<compilation defaultLanguage="c#" debug="false" />
</system.web>
</configuration>
Module 8: Designing XML Web Services 17
In output caching, note that each unique set of input parameters results in a
unique cached result.
18 Module 8: Designing XML Web Services
Data caching Data caching is implemented by the Cache class in the System.Web.Caching
namespace. Each ASP.NET application has an instance of the Cache class that
is private to that application, and whose lifetime is bounded by the lifetime of
the application. When an application is restarted, the instance of its Cache
object is re-created.
You can place items in a cache and later retrieve them by using key-value pairs.
In a Web service, the Cache object can be accessed through the Context object.
The following code example demonstrates this functionality.
C# code example Context.Cache["ListOfSources"] = dsSources;
Note A cache has no information about the contents of the items that it
contains. It merely holds a reference to those objects. A caching system can also
provide a way to track the dependencies of those objects and set expiration
policies.
File and key-based You can define the validity of a cached item based on an external file, a
dependencies directory (file dependencies), or another cached item (key dependencies). If a
dependency changes, the cached item is invalidated and removed from a cache.
You can use this technique to remove items from the cache when their data
source changes. For example, if you store the list of current employees in an
XML file for a Human Resources application, you can store a reference to an
XmlDocument object that represents the XML file in the cache. When the
source file is updated, the reference is removed from the cache. When required,
the application reads the XML file and a new version of the XML document is
inserted into the cache.
You can add an item to a cache by passing an instance of the
CacheDependency class to the Add or Insert method. The following example
demonstrates how to use the Insert method to add an item to the cache with a
dependency on an XML file.
Module 8: Designing XML Web Services 19
The CacheDependency class also allows you to monitor arrays of files and
directories, cache keys, or both.
Expiration policies You can add an item to the cache and include an expiration time. You can set
absolute time-out periods or timeouts relative to the last access of the cached
item. The following code uses the Insert method to add an item to the cache
with an absolute expiration of two minutes from the time of insertion into the
cache.
C# code example Context.Cache.Insert("Employees", doc, null,
DateTime.Now.AddMinutes(2), Cache.NoSlidingExpiration);
The following code uses the Insert method to add an item to the cache with a
sliding expiration of 30 seconds.
C# code example Context.Cache.Insert("Employees", doc, null,
Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(30));
Note You can either define an absolute expiration or a sliding expiration, but
not both.
Whichever expiration parameter you use, you must set the other parameter to
zero. The Cache class defines two fields that do this automatically:
NoAbsoluteExpiration and NoSlidingExpiration. When you define an
absolute or a sliding expiration, set the appropriate parameter to its
corresponding field value.
20 Module 8: Designing XML Web Services
Item priorities All items in the cache will eventually be removed from the cache. This may
happen because the specified duration for the lifetime of an object in the cache
has exceeded, or because of memory shortage. If items must be removed from
the cache because of memory shortage, the common language runtime uses a
least-recently used (LRU) algorithm to decide which items must be removed
first. If you think that that not all of the items in the cache are of equal
importance, then you might prefer to have the less important cached items
removed first from the cache during a memory shortage. You can accomplish
this by assigning priority values (from the CacheItemPriority enumeration) to
the items when they are cached. As a result, the lower priority items are
released first from the cache.
The following example uses the Add method to add an item to the cache with a
priority value of High.
C# code example Context.Cache.Add("Employee", doc, null,
Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(30),
CacheItemPriority.High, null);
Removal notification An item may be removed from the cache for any of the following reasons:
! The item’s time-out expired.
! An object that the cached item was dependent on changed.
! The item was explicitly removed by using the Remove method of the
Cache class.
! The common language runtime was scavenging for memory and the item
became eligible for removal.
When an item expires, it is removed from the cache. Attempts to retrieve its
value will return null unless the item has been added to the cache again. When
an item is removed from the cache, a specified function can execute. The reason
for removal is provided as an argument to this function, and in this function,
you can perform some appropriate action. For example, you might want to
update the data that was cached and recache it.
Using removal notification in Web services requires a little additional work.
Because the object that encapsulates your Web service might be recycled at the
end of each Web service method, the callback function will not necessarily be
invoked on a thread that is in the middle of responding to a request. Therefore,
the callback function cannot be an instance method. Instead, it must be a static
method. However, the Context object, which gives you access to the Cache
object, is only available in instance methods. As a result, you cannot recache
items in the callback function, unless you find a way to pass a reference to the
Cache object into the callback function.
Module 8: Designing XML Web Services 21
The following code shows how you might implement removal notification. All
of the following code would be part of the class implementing a Web service.
C# code example
1. internal class CacheData {
2. internal XmlDocument doc;
3. internal string path;
4. internal Cache c;
5. }
6.
7. private static CacheItemRemovedCallback onRemove = null;
8.
9. public static void RemovedCallback(string key, Object v,
CacheItemRemovedReason r)
10. {
11. CacheData cd = (CacheData) v;
12. cd.doc.Load(cd.path);
13. HttpRuntime.Cache.Insert(key, cd,
new CacheDependency(cd.path),
Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
CacheItemPriority.Default,
new CacheItemRemovedCallback(
Service1.RemovedCallback));
14. }
15.
16. [WebMethod]
17. public string GetEmployees()
18. {
19. CacheData cd = (CacheData)Context.Cache["Employees"];
20. return cd.doc.DocumentElement.OuterXml;
21. }
22 Module 8: Designing XML Web Services
The following code provides an example of how to initialize the cache when the
application starts. The event handler is found in Global.asax.
C# code example
1. protected void Application_Start(Object sender, EventArgs e) {
2. XmlDocument doc = new XmlDocument();
3. CacheData cd = new CacheData();
4. cd.c = Context.Cache;
5. cd.path = Server.MapPath("employees.xml");
6. doc.Load(cd.path);
7. cd.doc = doc;
8. CacheItemRemovedCallback onRemove = new
CacheItemRemovedCallback(Service1.RemovedCallback);
9. Context.Cache.Insert("Employees", cd,
new CacheDependency(cd.path),
Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
CacheItemPriority.Default, onRemove);
10. }
Scenarios Not all data is suitable for caching. Typically, it is recommended that you only
cache data that changes relatively infrequently. For example, the list of your
organization’s customers, organized by region, might be a relatively slow-
changing list, and therefore would make a good candidate for caching.
Web service methods, whose results depend on specific input parameters, and
where the possible range of values for the parameters is not restricted, are not
suitable for caching. For example, if you implemented a method to add two
numbers and return the result, it would not be a good idea to cache the result.
Module 8: Designing XML Web Services 25
Visual Basic .NET The Beginxxx method signature includes all the ByVal and ByRef parameters
implementation plus two additional parameters. The additional parameters are of type
AsyncCallback and Object. The method returns an object of type
IAsyncResult.
The Endxxx method signature includes all the ByRef parameters plus an
additional parameter of type IAsyncResult. The method returns the same type
that the synchronous version of the method returned.
Visual Basic .NET code <WebMethod()> _
example Function BeginGetAccounts(callback As AsyncCallback, _
asyncState As Object) As IAsyncResult
Dim bank As New WoodgroveOnlineBank()
asyncState = bank
Dim ar As IAsyncResult = bank.BeginGetAllAccounts( _
callback, asyncState)
Return ar
End Function 'BeginGetAccounts
Note This lab focuses on the concepts in this module and as a result may not
comply with Microsoft security recommendations
Lab Setup For each lab exercise in this course, you have the option of coding in either C#
or Microsoft Visual Basic® .NET. To avoid unnecessary instructions, the
following placeholders will be used throughout the lab exercises:
install_folder The install folder for the course content. Usually this will
be the folder C:\Program Files\Msdntrain\2524.
lab_root The folder install_folder\Labfiles\CS or
install_folder\Labfiles\VB, depending on the language you
are using for the lab exercises.
It is recommended that you select only one language for the lab exercises.
There are starter and solution files that are associated with this lab. The starter
files are in the folder lab_root\Lab08_1\Starter. The solution files for this lab
are in the folder lab_root\Lab08_1\Solution.
If you did not complete Lab 7, Securing XML Web Services, in Module 7,
“Securing XML Web Services,” in Course 2524, Developing XML Web
Services Using Microsoft ASP.NET, copy the lab_root\Lab07\Solution\Contoso
project to the C:\Inetpub\wwwroot\Contoso folder, overwriting your existing
Contoso project.
Module 8: Designing XML Web Services 29
Scenario In this lab, you will implement a method on the Contoso Micropayment Web
service that returns an XML document with information about the different
membership levels that the Contoso Micropayment service supports. The XML
document containing the information will be cached by using the .NET
Framework caching infrastructure. If the underlying XML document is
modified, the cache will be invalidated and the XML document must be
recached.
You will test the solution to this lab by using the Service Help page for the
Contoso Web service.
Estimated time to
complete this lab:
40 minutes
30 Module 8: Designing XML Web Services
Exercise 1
Extending the Contoso Micropayment Web Service
In this exercise, you will add a Web method named
GetMembershipInformation to the Contoso Micropayment Web service. This
method will retrieve a cached XML document and return its contents to the
client. You will also add code to Global.asax to initialize the cache and refresh
it when the underlying XML document is modified.
Important If you did not complete the modifications to the Contoso project
in Lab 7, refer to the Lab Setup section at the beginning of this lab for
additional instructions.
8. Add the CacheData object to the cache. The following code shows how to
do this.
C# onRemove = new CacheItemRemovedCallback(
Global.RemovedCallback);
Context.Cache.Insert("MembershipTypes", cd,
new CacheDependency(cd.path),
Cache.NoAbsoluteExpiration,
Cache.NoSlidingExpiration,
CacheItemPriority.Default,
onRemove);
5. In the method, use the HttpRuntime class to retrieve the cached data, and
return the cached XML document to the client. The following code shows
how to do this.
C# CacheData cd =
(CacheData)HttpRuntime.Cache["MembershipTypes"];
return cd.doc.DocumentElement;
Reliability
The common language runtime helps you address the preceding issues in a
number of ways.
Process isolation Most developers implement applications with little or no regard for the other
applications that run on the same computer. This can lead to unintended
interactions. One way to reduce the risk of unintended interactions is to isolate
all applications in separate processes. However, this solution makes more
demands on system resources than when applications share processes. As a
result, there is a tradeoff between reliability and performance.
With application domains in common language runtime, you are able to achieve
both reliability and performance in your Web service. Application domains
provide application isolation within the same process boundary. Because of this
feature, it is often a good idea to migrate any unmanaged code that your Web
service uses to the managed environment. Migrating unmanaged code reduces
the performance penalty incurred when your Web service calls a component
outside the application domain.
36 Module 8: Designing XML Web Services
Process recovery model All ASP.NET code runs in an external worker process named aspnet_wp.exe.
This process can automatically restart your application domain if it fails. Any
memory is reclaimed during the garbage collection for the common language
runtime, and if a deadlock is detected, the runtime performs deadlock recovery.
You can also configure the worker process to proactively reset itself based on a
timer or on-demand. Proactively resetting the process is a useful preventive
measure because it minimizes the chances of your application experiencing a
slowdown because of resource depletion, or experiencing problems with
counter roll-overs, and other similar issues.
Measurement Earlier, you learned about a few general considerations for measuring
performance and behavior of an application. This section examines the .NET
Framework support for instrumenting Web services.
Performance counters Windows performance counters allow your applications and components to
publish, capture, and analyze the performance data that applications, services,
and drivers provide. You can use this information to determine system
bottlenecks, and fine-tune system and application performance. For example,
you might use a performance counter to track the amount of time that is
required to process an order, or query a database. The decision about how to
instrument your Web service is a tradeoff between the performance impact that
writing to performance counters imposes and the utility gained by
instrumenting the Web service. If your Web service will be deployed by an
Internet Service Provider (ISP) or an Application Service Provider (ASP), it is
vital that you instrument the Web service.
You can use the PerformanceCounter class for both reading predefined or
custom counters and writing performance data to custom counters.
To read from a performance counter:
1. Create an instance of the PerformanceCounter class.
2. Set the CategoryName, CounterName, and, optionally, the InstanceName
or MachineName properties.
3. Call the NextValue method to get the reading.
The provision of data and events, and the ability to configure systems are
provided seamlessly to clients and applications through a well-defined schema.
In the .NET Framework, the System.Management namespace provides
common classes to traverse the WMI schema.
The following code shows how to define a WMI Instance class.
C# code example [InstrumentationClass(InstrumentationType.Abstract)]
public class AbstractClass : Instance
{
public string Property_Name;
}
[InstrumentationClass(InstrumentationType.Instance)]
public class InstanceClass : AbstractClass
{
public int Sample_Number;
}
...
InstanceClass instClass = new InstanceClass();
instClass.Property_Name = "Hello";
instClass.Sample_Number = 888;
instClass.Published = true;
38 Module 8: Designing XML Web Services
<InstrumentationClass(InstrumentationType.Instance)> _
Public Class InstanceClass
Inherits AbstractClass
Public Sample_Number As Integer
End Class 'InstanceClass
. . .
Dim instClass As New InstanceClass()
instClass.Property_Name = "Hello"
instClass.Sample_Number = 888
instClass.Published = True
Module 8: Designing XML Web Services 39
Versioning
Versioning request or If any parameter to a Web service method or the return value of a method
response payload changes its structure over time, then you can handle the versioning issues by
defining the parameter or return type to be of the type XmlElement or
XmlNode. You can then apply the XmlAnyElement or XmlAnyAttribute to
the parameter or the field. These attributes instruct the common language
runtime to capture all elements and attributes that are found in an XML
document. The following code shows how to do this.
C# code example public class Company : System.Web.Services.WebService
{
[WebMethod]
[return:XmlAnyElement]
public XmlNode GetOrganizationStructure()
{
. . .
}
}
<WebMethod()> _
Public Function GetOrganizationStructure() As _
<XmlAnyElement()> XmlNode
. . .
End Function 'GetOrganizationStructure
End Class 'Company
Module 8: Designing XML Web Services 41
The Match class The Match class represents the results of a regular expression match. The
following example uses the Match method of the Regex class to return an
object of type Match to find the first match in the input string. The example
uses the Success property of the Match class to find out whether a match was
found.
C# code example Regex r = new Regex("abc");
Match m = r.Match("123abc456");
if (m.Success)
{
Console.WriteLine("Found match at position " + m.Index);
}
Escaped characters Most of the important regular expression language operators are unescaped
single characters. The escape character “\” (a single backslash) notifies the
regular expression parser that the character following the backslash is not an
operator. The following table lists the character escapes that are recognized in
regular expressions.
Escaped character Meaning
Character classes Character classes are the set of characters that define which substring to match.
The following table summarizes character matching syntax.
Character class Meaning
For more information, see the topic “Regular Expression Language Elements”
in the .NET Framework SDK documentation.
The MatchCollection The MatchCollection class represents a sequence of successful nonoverlapping
Class matches when applying a regular expression to an input string. The
Regex.Matches property returns instances of MatchCollection.
The following example uses the Matches method of the Regex class to fill an
instance of the MatchCollection class with all the matches found in the input
string. The following example code copies the match collection to a string array
that holds all the matches and an integer array that indicates the position of each
match.
C# code example MatchCollection mc;
string[] results = new String[20];
int[] matchposition = new int[20];
The pattern attribute of the match element is a Perl 5.0 compatible regular
expression. The match elements can also have nested match elements to
perform pattern matching within a match.
Example Consider the following XML document:
<?xml version="1.0" encoding="UTF-8"?>
<family>
<parents>
<mother>Clair</mother>
<father>Peter</father>
</parents>
<children>
<child>John</child>
<child>Robert</child>
<child>Jim</child>
<child>Amy</child>
</children>
</family>
Module 8: Designing XML Web Services 47
To mimic a Web service that can provide a list of parents and a list of children,
you can have the following WSDL document:
<?xml version="1.0"?>
<definitions standard namespaces omitted for brevity
xmlns:urt="http://microsoft.com/wsdl/mime/textMatching/">
<types/>
<message name="GetFamilyInfoHttpGetIn"/>
<message name="GetFamilyInfoHttpGetOut"/>
<portType name="FamilyHttpGet">
<operation name="GetFamilyInfo">
<input message="s0:GetFamilyInfoHttpGetIn"/>
<output message="s0:GetFamilyInfoHttpGetOut"/>
</operation>
</portType>
<binding name="FamilyHttpGet" type="s0:FamilyHttpGet">
<http:binding verb="GET"/>
<operation name="GetFamilyInfo">
<http:operation location=""/>
<input>
<http:urlEncoded/>
</input>
<output>
<urt:text>
<urt:match name="listOfChildren"
pattern="(<children>(.*)?</children>)"
ignoreCase="1">
<urt:match name="children"
pattern="<child>(.*)?</child>"
repeats="*"/>
</urt:match>
</urt:text>
</output>
</operation>
</binding>
<service name="Family">
<port name="FamilyHttpGet" binding="s0:FamilyHttpGet">
<http:address
location="http://www.cpandl.com/Scrape/family.xml"/>
</port>
</service>
</definitions>
You can process this WSDL document by using Wsdl.exe to produce a proxy
class. You can use this proxy class like any other proxy to a Web service.
48 Module 8: Designing XML Web Services
Portals to Web services In lab 8.2 associated with this module, you will implement a Web service,
named Northwind Traders, which performs an electronic funds transfer. It does
this transfer by acting as a proxy for the consumer and handles the details of
obtaining routing information. The Web service also initiates the electronic
funds transfer and communicates with two other Web services. These services
act as the source and recipient of the funds being transferred. The only thing
that a client of the Northwind Traders Web service must do is select the source
and destination financial institution, and supply the amount for the transfer and
security credentials for the source financial institution. This is considerably
easier than having to request routing information from one financial institution
and delivering that information to another financial institution manually.
The previous scenario is an example of how a Web service that aggregates other
Web services can provide additional value to the consumer. Instead of the
consumer having to interact with multiple Web services, the aggregating Web
service can act as a portal to other Web services.
52 Module 8: Designing XML Web Services
Monitoring and metering ASPs want the capability to isolate and monitor individual transactions within
the application. They want the ability to configure which aspects of an
application will be monitored. The capability to closely monitor many system
metrics makes it easier for the ASP to correctly determine which clients are
using which services and the exact actions that are being performed. This is the
basis for application usage metering.
Another desirable attribute of an application from the ASP perspective is the
ability of applications to automatically generate alerts to notify key personnel.
You can implement much of the required eventing and monitoring
infrastructure by using the WMI support in the
System.Management.Instrumentation namespace and by using the
Performance Counter classes to write to the Windows eventlLogs.
Self-repair and remote It is recommended that applications also take some measures to perform self-
repair repair if problems are diagnosed. For example, if a Web service is a client of a
second Web service and it detects that the second Web service is unavailable, it
should attempt to locate a backup service provider.
If your application cannot perform self-diagnosis and repair, you should also
provide an administrative interface that will allow you to configure settings like
database connection strings in Web.config.
54 Module 8: Designing XML Web Services
Review
2. Name the two forms of caching that the .NET Framework provides and that
you can use in Web services.
Output and data caching
3. Name two technologies that you can use to instrument a Web service that
has been deployed in production.
WMI and Performance Counters
5. Which protocol should you use if you do not want your Web service to be
tied to the HTTP protocol?
SOAP
Note This lab focuses on the concepts in this module and, as a result, may not
comply with Microsoft security recommendations. For example, both the
Woodgrove and Contoso Web services use the sa login account to connect to
SQL Server and store the sa password in the Web.config file in clear text.
Lab Setup For each lab exercise in this course, you have the option of coding in either C#
or Visual Basic .NET. In order to avoid unnecessary instructions, the following
placeholders will be used throughout the lab exercises:
install_folder The install folder for the course content. Usually, this will
be the folder C:\Program Files\Msdntrain\2524.
lab_root The folder install_folder\Labfiles\CS or
install_folder\Labfiles\VB, depending on the language you
are using for the lab exercises.
It is recommended that you select only one language for the lab exercises.
There are starter and solution files that are associated with this lab. The starter
files are in the folder lab_root\Lab08_2\Starter. The solution files for this lab
are in the folder lab_root\Lab08_2\Solution.
If you did not complete Lab 8.1, Implementing Caching in an XML Web
Service, in Module 8, “Designing XML Web Services,” in Course 2524,
Developing XML Web Services Using Microsoft ASP.NET, copy the
lab_root\Lab08_1\Solution\Contoso project to the
C:\Inetpub\wwwroot\Contoso folder, overwriting your existing Contoso project.
58 Module 8: Designing XML Web Services
Scenario In this lab, you will implement an aggregating Web service named Northwind
Traders and a client to consume this service. The Northwind Traders Web
service will be a portal to facilitate electronic funds transfers between financial
institutions. It will locate Web services for financial institutions that can be
either a source or a destination of the funds transfers. It will allow a funds
transfer between any of the located financial institutions.
You will also implement a client that uses the Northwind Trader Web service.
Estimated time to
complete this lab:
60 minutes
Module 8: Designing XML Web Services 59
Exercise 1
Extending the Contoso Micropayment Web Service
In this exercise, you will add a CreditAccount method to the Contoso
Micropayment Web service. This method will invoke the Woodgrove Online
Bank TransferFunds method, which transfers funds from a Woodgrove
account to a Contoso account.
Important If you did not complete the modifications to the Contoso project
in Lab 8.1, refer to the Lab Setup section at the beginning of this lab for
additional instructions.
The endPoint string provides the URL that the CreditAccount method will
use to call the Woodgrove TransferFunds method. The token string
provides an encrypted string that the Woodgrove AuthorizeFundsTransfer
method returns. The TransferFunds method uses this token to verify that
the transfer has been authorized, and that the authorization has not expired.
4. Begin creating the CreditAccount method by adding the following method
signature to the MicroPaymentService class.
C# public void CreditAccount(EFTBindingInfo bindingInfo,
decimal amount)
ABA_RoutingNo “12345”
AccountName “Contoso Micropayments”
AccountNumber “12345678”
SubAccountName Name of the Contoso account holder
SubAccountNumber The Contoso account number
14. Build and run the Web service. The CreditAccount method will be
displayed on the Service Help page, but you will not be able to invoke the
method because the method uses data types that are incompatible with the
HTTP GET protocol.
15. Close Microsoft Internet Explorer.
62 Module 8: Designing XML Web Services
Exercise 2
Creating the Northwind Trader Web Service
In this exercise, you will implement the Northwind Traders EFT portal. The
Northwind Traders Web service will aggregate the Contoso and Woodgrove
Web services. The Northwind Traders Web service will allow clients to specify
a source and destination financial institution, and then initiate an electronic fund
transfer between the two financial institutions. The Northwind Web service
brokers the communication between the client and the two aggregated Web
services.
10. To allow a method in the Northwind Traders Web service to use SOAP
header authentication, add a SoapHeader-derived class to the Northwind
namespace, after the Traders class definition. The class should look as
follows.
C# public class AuthToken : SoapHeader
{
public string srcUserName;
public string srcPassword;
public string destUserName;
public string destPassword;
}
6. Set the Url property of the WoodgroveOnlineBank proxy to the uri data
member of the src parameter.
7. Create a ContosoMicropaymentService proxy class object.
8. Create a ContosoAuthInfo class object. Set its Username and Password
methods to the destUserName and destPassword data members of the
authInfo object.
9. Set the ContosoAuthInfoValue property of the
ContosoMicropaymentService proxy to the ContosoAuthInfo object.
10. Set the Url property of the ContosoMicropaymentService proxy to the uri
data member of the snk parameter.
11. Invoke the AuthorizeFundsTransfer method of the Woodgrove proxy.
a. Set the acctID parameter to the acctID data member of the src
parameter.
b. Set the amount parameter to this method’s amt parameter.
c. Save the returned Northwind.Source.EFTBindingInfo object.
Note When you declare the EFTBindingInfo instance, you must fully
qualify EFTBindingInfo with the Northwind.Source namespace because
the Northwind.Sink namespace also defines a structure of this same type.
Northwind.Source.EFTBindingInfo biFrom =
bank.AuthorizeFundsTransfer(src.acctID, amt);
Northwind.Sink.EFTBindingInfo biTo = new
Northwind.Sink.EFTBindingInfo();
biTo.endPoint = biFrom.endPoint;
biTo.token = biFrom.token;
micro.CreditAccount(biTo, amt);
return "Transaction succeeded";
micro.CreditAccount(biTo, amt)
Return "Transaction succeeded"
68 Module 8: Designing XML Web Services
16. Enclose the code that you added in steps 3 through 15 within a try/Try
block.
17. Add a catch/Catch block to catch any errors. In the event that an error is
thrown, return the string “Transaction failed”.
Exercise 3
Using the Northwind Trader Web Service
In this exercise, you will extend the Northwind client that is provided to you to
use the Northwind Trader Web service. The starter application project can be
found at lab_root\Lab08_2\Starter\NorthwindClient.
! Transfer funds
1. Locate the btnTransfer_Click method.
2. Create a BankInfo object for the source financial institution.
a. Set the BankInfo.acctID property to the value stored in the
txtAcctIDFrom textbox.
b. Set the BankInfo.uri property to the ListItem.Url property of the
ListItem selected in the lstFrom listbox.
3. Create a BankInfo object for the destination financial institution.
a. Set the BankInfo.acctID property to the value stored in the
txtAcctIDTo textbox.
b. Set the BankInfo.uri property to the ListItem.Url property of the
ListItem selected in the lstTo listbox.
4. Create a Northwind Traders Web service proxy class object.
5. Create an AuthToken authentication object to be used as the SoapHeader.
6. Populate the AuthToken authentication object with the values found in
txtUserFrom, txtUserTo, txtPasswordFrom, and txtPasswordTo boxes.
7. Set the Cursor property of the form to Cursors.WaitCursor to indicate
that the application is processing.
8. Set the statusBar.Text property to Processing…
9. Transfer the funds by calling the EFTTransfer method on the Northwind
Traders Web service proxy with the source and destination BankInfo
objects, and the amount specified by the Text property of the txtAmt
object.
10. Display the results of the EFTTransfer call in a message box.
11. Reset the statusBar.Text property to Ready.
Your code should look like the following.
12. Set the Cursor property of the form to Cursors.Default to indicate that the
application is done processing.
72 Module 8: Designing XML Web Services
Visual Basic .NET ' Retrieve the selected items in lstFrom and lstTo
Dim itemFrom As ListItem = CType(lstFrom.SelectedItem, _
ListItem)
Dim itemTo As ListItem = CType(lstTo.SelectedItem, _
ListItem)
Contents
Overview 1
Lesson: Introduction to GXA 3
Lesson: Routing and Referral 10
Lesson: Security and Licensing 19
Review 22
Course Evaluation 23
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.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 9: Global XML Web Services Architecture iii
Instructor Notes
Presentation: This module teaches students how to use the security services of the Microsoft®
30 Minutes Windows® operating system, Microsoft Internet Information Services (IIS), and
the Microsoft .NET Framework and common language runtime to secure XML
Lab: (Extensible Markup Language) Web services.
0 Minutes
After completing this module, students will be able to:
! Describe limitations inherent to the specifications with which today’s Web
services are built.
! Describe the design principles and specifications of Global XML Web
services Architecture (GXA).
! Describe Web service application scenarios that Web Services Routing
Protocol (WS-Routing) and Web Services Referral Protocol (WS-Referral)
make possible.
! Explain how to use Web Services Security Language (WS-Security) and
Web Services License Language (WS-License) to perform authentication
and authorization for Web services.
! Design Web services that anticipate and can leverage the features that GXA
will offer when released.
Required Materials To teach this module, you need the Microsoft PowerPoint® file 2524C_09.ppt.
Preparation Tasks To prepare for this module, read all of the materials for this module.
iv Module 9: Global XML Web Services Architecture
Module Strategy
Use the following strategy to present this module:
! Introduction to GXA
Ensure that students understand that GXA provides principles,
specifications, and guidelines for advancing the protocols of today's Web
services standards to address more complex and sophisticated tasks in
standard ways. Do not imply that it is impossible to implement sophisticated
Web services by using the current standards.
! Routing and Referral
Explain that as Simple Object Access Protocol (SOAP) has become more
widely used as a messaging infrastructure, WS-Referral and WS-Routing
have been developed to address some of the issues related to reliable
messaging and message routing. Emphasize that these specifications are
intended to be building blocks — they are not intended to be complete
messaging specifications.
! Security and Licensing
Describe the limitation in the current Web services security infrastructure.
Explain that XML Signature and XML Encryption make it possible to
ensure message integrity and message privacy, but that there is no industry-
standard process in place. Explain that WS-Security builds on these
standards to specify how to sign and encrypt SOAP messages that are being
communicated between a Web service and its clients.
Explain that WS-License is an extension to WS-Security that addresses how
to represent current license formats and include them in SOAP messages
that have been secured according to the WS-Security specification.
Module 9: Global XML Web Services Architecture 1
Overview
Tiers 1 and 2 are available today, but tier 3 is dependent on technology and
specifications that are still emerging.
Module 9: Global XML Web Services Architecture 5
Limitations Using Web services, organizations can extend the benefits of integrating
systems within organizations outward to partners and customers. However, the
lack of broadly adopted specifications for security, routing, and other necessary
capabilities limits integration to those scenarios where bilateral, out-of-band
agreements can be negotiated and maintained. To ensure secure, reliable cross-
organization interoperability, developers are forced to implement a series of
solutions that are specific to the situation. For example, you may need to
configure a custom authentication solution that adds a user name and password
to SOAP headers, which then uses a SOAP extension to encrypt and decrypt
this sensitive information. This solution requires that the encryption extension
assembly or, minimally, the encryption algorithm be distributed to all clients of
the Web service. Although this solution is adequate, clearly it is not optimally
secure and requires close cooperation between the Web service implementer
and client developers.
As the business requirements that drive Web services become more complex,
developers require additional capabilities that current Web services standards
do not address. These capabilities include the following:
! Security. Developers need a straight-forward, end-to-end security
architecture to implement across organizations and trust boundaries.
! Routing. Developers need a way of specifying messaging paths and the
ability to configure those message paths dynamically to ensure scalability
and fault-tolerance.
! Reliable Messaging. Developers need an end-to-end guarantee of message
delivery across a range of semantics such as, at-least-once, at-most-once,
and exactly once.
! Transactions. Developers need flexible process and compensation-based
transaction schemes to execute transactions across organizations.
If an organization does not use these capabilities, it can be exposed to risks and
the value of its Web services degrade. Currently, in the absence of these
capabilities in Web services, developers must create specific solutions for each
situation, which is time consuming and expensive. In addition, specific
solutions encroach upon a central value area of Web services — cross-
organizational interoperability.
6 Module 9: Global XML Web Services Architecture
Released specifications This section describes a set of the new Global XML Web services
specifications that were made available in October 2001. These specifications
represent a significant step toward a comprehensive Global XML Web services
Architecture.
! WS-Routing is a simple, stateless SOAP extension for sending SOAP
messages in an asynchronous manner over a variety of communication
transports such as Transmission Control Protocol (TCP), User Datagram
Protocol (UDP), and Hypertext Transfer Protocol (HTTP).
! WS-Referral is a simple SOAP extension that enables the routing between
SOAP nodes on a message path to be dynamically configured.
! WS-Security provides a security language for Web services. WS-Security
describes enhancements to SOAP messaging, providing three capabilities:
credential exchange, message integrity, and message confidentiality.
Message integrity is provided by taking advantage of XML Signature and
licenses to ensure that messages are transmitted without modifications.
Similarly, message confidentiality takes advantage of XML Encryption and
licenses to keep portions of SOAP messages confidential.
! WS-License describes how to use several common license formats,
including X.509 certificates and Kerberos tickets, as WS-Security
credentials. WS-License includes extensibility mechanisms that enable new
license formats to be easily incorporated into the specification.
Future protocols Interactions across organizations have many opportunities for failure ranging
from transmission errors to incompatible or unavailable business processes. The
following future protocols will allow the builders of Web services to manage
the scope and effect of failures.
! Reliable messaging
Web services must operate reliably over intranets and the public Internet. In
addition, they must operate reliably over transport protocols that are not
completely reliable. For example, HTTP, the most commonly used Web
service transport protocol, provides no mechanisms to ensure that a request
was received or that the client received a response. Although lower
network-level protocols can alert a client in case of common catastrophic
failures like resource not found, a SOAP-level reliable messaging protocol
can provide delivery guarantees. Using a protocol that provides delivery
guarantees isolates application processes from the detailed handling of
transmission failure and its recovery. This allows a developer to concentrate
on automating a process with a much-simplified error-handling model. In
the exchange of messages, individually or as part of a long-running process,
communicating parties will be able to obtain end-to-end delivery guarantees
so that messages will not be lost, duplicated, or delivered in the incorrect
order.
8 Module 9: Global XML Web Services Architecture
! Transactions
Transactions address the possibility of a business-level inability to complete
a process. Transactions allow multiple parties that are involved in a process
to arrive at a consistent final outcome or to discover that a consistent final
outcome is not possible. Although existing two-phase commit protocols are
appropriate in some circumstances, developers also need more loosely
coupled techniques, such as exceptions and compensation. Exceptions and
compensation enable a broader range of transactions to be automated across
trust boundaries. Developers will have powerful process-modeling
languages to express the patterns of messages that are exchanged between
Web services, the interactions of those messages, and the business processes
that they reflect, including both normal and exceptional conditions.
Module 9: Global XML Web Services Architecture 9
WS-Routing The purpose of WS-Routing is to define the mechanisms that are needed to
mechanisms describe messages that are being exchanged along the following two message
paths:
! A forward message path where messages travel from the initial sender
through zero or more intermediaries to the ultimate receiver.
! An optional reverse message path where messages travel in the direction
from the ultimate receiver through zero or more intermediaries to the initial
sender.
In addition, being able to identify a message and to correlate that message with
other messages is essential to WS-Routing. The correlation can, for example,
reside between multiple messages flowing in the same direction on either the
forward or the reverse message path. Alternatively, it can reside between
messages on different message paths. An example of a correlation is between a
WS-Routing fault message and the faulty message. WS-Routing defines a
correlation mechanism.
WS-Routing elements WS-Routing defines a single new SOAP header and associated processing
model. To illustrate this, consider a SOAP processor A that wishes to send a
SOAP message to an ultimate receiver D through B and then through C.
To express such routes, WS-Routing defines a new SOAP header named path,
and, within that header, defines:
! A <from> element for the message originator (A).
! A <to> element for the ultimate receiver (D).
! A <fwd> element to contain the forward message path.
! A <rev> element to contain the reverse message path.
Although occasionally grouped for convenience, you can evaluate each referral
statement independently of any other referral.
When interpreting a referral statement, the <for> element gives the list of
SOAP actors for which this referral applies. Consider the <if> clause as the set
of conditions to satisfy when applicable. If satisfied, then go (reroute) to one of
the SOAP routers listed in the <go> element.
Module 9: Global XML Web Services Architecture 15
Routing Scenario
STEP 2: From SN1 to B The following code example shows the SOAP message leaving intermediary
SN1 in a forward direction toward B with a reverse path. Notice in the bolded
code that SN1 has been removed (in the <via> element) from the <fwd>
element, and has been added to the reverse path that is given by the <rev>
element to specify the reverse path. The <to> and <from> elements are not
modified.
<S:Envelope !
xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header>
<p:path xmlns:p="http://schemas.xmlsoap.org/rp/">
<p:action>http://example.org/alert</p:action>
<p:to>soap://serverB.com/B</p:to>
<p:fwd>
</p:fwd>
<rev>
<p:via>soap://SN1.com</p:via>
<p:via>soap://serverA.com/A</p:via>
</rev>
<p:from>soap://serverA.com/A</p:from>
<p:id>uuid:12dfs83476-4asd-s234-s3df-d25656adssf4</p:id>
</p:path>
</S:Header>
<S:Body>…
</S:Body>
</S:Envelope>
STEP 3: From B to SN1 The following code example shows the SOAP message leaving B toward
intermediary SN1. Notice in the bolded code that the <fwd> element gives the
reverse path.
<S:Envelope !
xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header>
<p:path xmlns:p="http://schemas.xmlsoap.org/rp/">
<p:action>http://example.org/alert</p:action>
<p:fwd>
<p:via>soap://SN1.com</p:via>
<p:via>soap://serverA.com/A</p:from>
</p:fwd>
<p:from>soap://serverB.com/B</p:from>
<p:id>uuid:74583476-45gd-sg6g-sf54-dfgsgfgdssf4</p:id>
</p:path>
</S:Header>
<S:Body>
<m:alert xmlns:m="http://example.org/alert">
<m:msg>Pickup scheduled</m:msg>
</m:alert>
</S:Body>
</S:Envelope>
Module 9: Global XML Web Services Architecture 17
STEP 4: From SN1 to A The following code example shows the SOAP message leaving intermediary
SN1 towards A. Notice in the bolded code that the <fwd> element gives the
remainder of the reverse path.
<S:Envelope !
xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header>
<p:path xmlns:p="http://schemas.xmlsoap.org/rp/">
<p:action>http://example.org/alert</p:action>
<p:fwd>
<p:via>soap://serverA.com/A</p:from>
</p:fwd>
<p:from>soap://serverB.com/B</p:from>
<p:id>uuid:74583476-45gd-sg6g-sf54-dfgsgfgdssf4</p:id>
</p:path>
</S:Header>
<S:Body>
<m:alert xmlns:m="http://example.org/alert">
<m:msg>Pickup scheduled</m:msg>
</m:alert>
</S:Body>
</S:Envelope>
You are not required to specify a reverse path or every intermediary in the
reverse path if the underlying protocol is bidirectional. In this case, it is
assumed that the underlying protocol provides a bidirectional communication
channel.
18 Module 9: Global XML Web Services Architecture
Referral Scenario
Review
Course Evaluation