Vous êtes sur la page 1sur 206

MICROSOFT

LEARNING

PRODUCT

6461A
Visual Studio 2008: Windows
Communication Foundation

Be sure to access the extended learning content on your


Course Companion CD enclosed on the back cover of the book.

MCT USE ONLY. STUDENT USE PROHIBITED

OFFICIAL

Visual Studio 2008: Windows Communication Foundation

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, place or event 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 manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory,
regarding these manufacturers or the use of the products with any Microsoft technologies. The
inclusion of a manufacturer or product does not imply endorsement of Microsoft of the
manufacturer or product. Links may be provided to third party sites. Such sites are not under the
control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link
contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for
webcasting or any other form of transmission received from any linked site. Microsoft is providing
these links to you only as a convenience, and the inclusion of any link does not imply endorsement
of Microsoft of the site or the products contained therein.
2008 Microsoft Corporation. All rights reserved.
Microsoft, Active Directory, Internet Explorer, MSDN, PowerPoint, SQL Server, Visual Basic, Visual C#,
Visual Studio, Windows, Windows CardSpace, Windows Server, Windows Vista are either registered
trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.
All other trademarks are property of their respective owners.

Product Number: 6461A


Released: 04/2008

MCT USE ONLY. STUDENT USE PROHIBITED

ii

MICROSOFT LICENSE TERMS


OFFICIAL MICROSOFT LEARNING PRODUCTS - TRAINER
EDITION Pre-Release and Final Release Versions
These license terms are an agreement between Microsoft Corporation and you. Please read them. They
apply to the Licensed Content named above, which includes the media on which you received it, if any. The
terms also apply to any Microsoft

updates,

supplements,

Internet-based services, and

support services

for this Licensed Content, unless other terms accompany those items. If so, those terms apply.
By using the Licensed Content, you accept these terms. If you do not accept them, do not use
the Licensed Content.
If you comply with these license terms, you have the rights below.

1. DEFINITIONS.
a. Academic Materials means the printed or electronic documentation such as manuals,

workbooks, white papers, press releases, datasheets, and FAQs which may be included in the
Licensed Content.

b. Authorized Learning Center(s) means a Microsoft Certified Partner for Learning Solutions

location, an IT Academy location, or such other entity as Microsoft may designate from time to time.

c. Authorized Training Session(s) means those training sessions authorized by Microsoft and

conducted at or through Authorized Learning Centers by a Trainer providing training to Students


solely on Official Microsoft Learning Products (formerly known as Microsoft Official Curriculum or
MOC) and Microsoft Dynamics Learning Products (formerly know as Microsoft Business Solutions
Courseware). Each Authorized Training Session will provide training on the subject matter of one
(1) Course.

d. Course means one of the courses using Licensed Content offered by an Authorized Learning
Center during an Authorized Training Session, each of which provides training on a particular
Microsoft technology subject matter.

e. Device(s) means a single computer, device, workstation, terminal, or other digital electronic or
analog device.

f.

Licensed Content means the materials accompanying these license terms. The Licensed
Content may include, but is not limited to, the following elements: (i) Trainer Content, (ii) Student
Content, (iii) classroom setup guide, and (iv) Software. There are different and separate
components of the Licensed Content for each Course.

g.

Software means the Virtual Machines and Virtual Hard Disks, or other software applications that
may be included with the Licensed Content.

h. Student(s) means a student duly enrolled for an Authorized Training Session at your location.

i.

Student Content means the learning materials accompanying these license terms that are for
use by Students and Trainers during an Authorized Training Session. Student Content may include
labs, simulations, and courseware files for a Course.

j.

Trainer(s) means a) a person who is duly certified by Microsoft as a Microsoft Certified Trainer
and b) such other individual as authorized in writing by Microsoft and has been engaged by an
Authorized Learning Center to teach or instruct an Authorized Training Session to Students on its
behalf.

k. Trainer Content means the materials accompanying these license terms that are for use by

Trainers and Students, as applicable, solely during an Authorized Training Session. Trainer Content
may include Virtual Machines, Virtual Hard Disks, Microsoft PowerPoint files, instructor notes, and
demonstration guides and script files for a Course.

l.

Virtual Hard Disks means Microsoft Software that is comprised of virtualized hard disks (such as
a base virtual hard disk or differencing disks) for a Virtual Machine that can be loaded onto a single
computer or other device in order to allow end-users to run multiple operating systems concurrently.
For the purposes of these license terms, Virtual Hard Disks will be considered Trainer Content.

m. Virtual Machine means a virtualized computing experience, created and accessed using

Microsoft Virtual PC or Microsoft Virtual Server software that consists of a virtualized hardware
environment, one or more Virtual Hard Disks, and a configuration file setting the parameters of the
virtualized hardware environment (e.g., RAM). For the purposes of these license terms, Virtual Hard
Disks will be considered Trainer Content.

n.

you means the Authorized Learning Center or Trainer, as applicable, that has agreed to these
license terms.

2. OVERVIEW.
Licensed Content. The Licensed Content includes Software, Academic Materials (online and
electronic), Trainer Content, Student Content, classroom setup guide, and associated media.
License Model. The Licensed Content is licensed on a per copy per Authorized Learning Center
location or per Trainer basis.

3. INSTALLATION AND USE RIGHTS.


a. Authorized Learning Centers and Trainers: For each Authorized Training Session, you
may:
i.

either install individual copies of the relevant Licensed Content on classroom Devices only for
use by Students enrolled in and the Trainer delivering the Authorized Training Session, provided
that the number of copies in use does not exceed the number of Students enrolled in and the
Trainer delivering the Authorized Training Session, OR

ii. install one copy of the relevant Licensed Content on a network server only for access by
classroom Devices and only for use by Students enrolled in and the Trainer delivering the
Authorized Training Session, provided that the number of Devices accessing the Licensed
Content on such server does not exceed the number of Students enrolled in and the Trainer
delivering the Authorized Training Session.
iii. and allow the Students enrolled in and the Trainer delivering the Authorized Training Session to
use the Licensed Content that you install in accordance with (ii) or (ii) above during such
Authorized Training Session in accordance with these license terms.

i.

Separation of Components. The components of the Licensed Content are licensed as a single
unit. You may not separate the components and install them on different Devices.

ii. Third Party Programs. The Licensed Content may contain third party programs. These license
terms will apply to the use of those third party programs, unless other terms accompany those
programs.

b. Trainers:
i.

Trainers may Use the Licensed Content that you install or that is installed by an Authorized
Learning Center on a classroom Device to deliver an Authorized Training Session.

ii. Trainers may also Use a copy of the Licensed Content as follows:

A. Licensed Device. The licensed Device is the Device on which you Use the Licensed Content.
You may install and Use one copy of the Licensed Content on the licensed Device solely for
your own personal training Use and for preparation of an Authorized Training Session.

B. Portable Device. You may install another copy on a portable device solely for your own
personal training Use and for preparation of an Authorized Training Session.

4. PRE-RELEASE VERSIONS. If this is a pre-release (beta) version, in addition to the other provisions
in this agreement, these terms also apply:

a. Pre-Release Licensed Content. This Licensed Content is a pre-release version. It may not

contain the same information and/or work the way a final version of the Licensed Content will. We
may change it for the final, commercial version. We also may not release a commercial version.
You will clearly and conspicuously inform any Students who participate in each Authorized Training
Session of the foregoing; and, that you or Microsoft are under no obligation to provide them with
any further content, including but not limited to the final released version of the Licensed Content
for the Course.

b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, you give to

Microsoft, without charge, the right to use, share and commercialize your feedback in any way and
for any purpose. You also give to third parties, without charge, any patent rights needed for their
products, technologies and services to use or interface with any specific parts of a Microsoft
software, Licensed Content, or service that includes the feedback. You will not give feedback that is
subject to a license that requires Microsoft to license its software or documentation to third parties
because we include your feedback in them. These rights survive this agreement.

c. Confidential Information. The Licensed Content, including any viewer, user interface, features

and documentation that may be included with the Licensed Content, is confidential and proprietary
to Microsoft and its suppliers.
i.

Use. For five years after installation of the Licensed Content or its commercial release,
whichever is first, you may not disclose confidential information to third parties. You may
disclose confidential information only to your employees and consultants who need to know
the information. You must have written agreements with them that protect the confidential
information at least as much as this agreement.

ii.

Survival. Your duty to protect confidential information survives this agreement.

iii. Exclusions. You may disclose confidential information in response to a judicial or


governmental order. You must first give written notice to Microsoft to allow it to seek a

protective order or otherwise protect the information. Confidential information does not
include information that

becomes publicly known through no wrongful act;

you received from a third party who did not breach confidentiality obligations to
Microsoft or its suppliers; or

you developed independently.

d.

Term. The term of this agreement for pre-release versions is (i) the date which Microsoft informs
you is the end date for using the beta version, or (ii) the commercial release of the final release
version of the Licensed Content, whichever is first (beta term).

e.

Use. You will cease using all copies of the beta version upon expiration or termination of the beta
term, and will destroy all copies of same in the possession or under your control and/or in the
possession or under the control of any Trainers who have received copies of the pre-released
version.

f.

Copies. Microsoft will inform Authorized Learning Centers if they may make copies of the beta
version (in either print and/or CD version) and distribute such copies to Students and/or Trainers. If
Microsoft allows such distribution, you will follow any additional terms that Microsoft provides to you
for such copies and distribution.

5. ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS.


a. Authorized Learning Centers and Trainers:
i.

Software.

ii. Virtual Hard Disks. The Licensed Content may contain versions of Microsoft XP, Microsoft
Windows Vista, Windows Server 2003, Windows Server 2008, and Windows 2000 Advanced
Server and/or other Microsoft products which are provided in Virtual Hard Disks.
A. If the Virtual Hard Disks and the labs are launched through the Microsoft
Learning Lab Launcher, then these terms apply:
Time-Sensitive Software. If the Software is not reset, it will stop running based upon the
time indicated on the install of the Virtual Machines (between 30 and 500 days after you
install it). You will not receive notice before it stops running. You may not be able to
access data used or information saved with the Virtual Machines when it stops running and
may be forced to reset these Virtual Machines to their original state. You must remove the
Software from the Devices at the end of each Authorized Training Session and reinstall and
launch it prior to the beginning of the next Authorized Training Session.
B. If the Virtual Hard Disks require a product key to launch, then these terms
apply:
Microsoft will deactivate the operating system associated with each Virtual Hard Disk.
Before installing any Virtual Hard Disks on classroom Devices for use during an Authorized
Training Session, you will obtain from Microsoft a product key for the operating system
software for the Virtual Hard Disks and will activate such Software with Microsoft using such
product key.
C. These terms apply to all Virtual Machines and Virtual Hard Disks:

You may only use the Virtual Machines and Virtual Hard Disks if you comply with
the terms and conditions of this agreement and the following security
requirements:
o

You may not install Virtual Machines and Virtual Hard Disks on portable Devices or
Devices that are accessible to other networks.

You must remove Virtual Machines and Virtual Hard Disks from all classroom Devices at
the end of each Authorized Training Session, except those held at Microsoft Certified
Partners for Learning Solutions locations.

You must remove the differencing drive portions of the Virtual Hard Disks from all
classroom Devices at the end of each Authorized Training Session at Microsoft Certified
Partners for Learning Solutions locations.

You will ensure that the Virtual Machines and Virtual Hard Disks are not copied or
downloaded from Devices on which you installed them.

You will strictly comply with all Microsoft instructions relating to installation, use,
activation and deactivation, and security of Virtual Machines and Virtual Hard Disks.

You may not modify the Virtual Machines and Virtual Hard Disks or any contents
thereof.

You may not reproduce or redistribute the Virtual Machines or Virtual Hard Disks.

ii. Classroom Setup Guide. You will assure any Licensed Content installed for use during an
Authorized Training Session will be done in accordance with the classroom set-up guide for the
Course.
iii. Media Elements and Templates. You may allow Trainers and Students to use images, clip
art, animations, sounds, music, shapes, video clips and templates provided with the Licensed
Content solely in an Authorized Training Session. If Trainers have their own copy of the
Licensed Content, they may use Media Elements for their personal training use.
iv. iv Evaluation Software. Any Software that is included in the Student Content designated as
Evaluation Software may be used by Students solely for their personal training outside of the
Authorized Training Session.

b. Trainers Only:
i.

Use of PowerPoint Slide Deck Templates. The Trainer Content may include Microsoft
PowerPoint slide decks. Trainers may use, copy and modify the PowerPoint slide decks only for
providing an Authorized Training Session. If you elect to exercise the foregoing, you will agree
or ensure Trainer agrees: (a) that modification of the slide decks will not constitute creation of
obscene or scandalous works, as defined by federal law at the time the work is created; and
(b) to comply with all other terms and conditions of this agreement.

ii. Use of Instructional Components in Trainer Content. For each Authorized Training
Session, Trainers may customize and reproduce, in accordance with the MCT Agreement, those
portions of the Licensed Content that are logically associated with instruction of the Authorized
Training Session. If you elect to exercise the foregoing rights, you agree or ensure the Trainer
agrees: (a) that any of these customizations or reproductions will only be used for providing an
Authorized Training Session and (b) to comply with all other terms and conditions of this
agreement.

iii. Academic Materials. If the Licensed Content contains Academic Materials, you may copy and
use the Academic Materials. You may not make any modifications to the Academic Materials
and you may not print any book (either electronic or print version) in its entirety. If you
reproduce any Academic Materials, you agree that:

The use of the Academic Materials will be only for your personal reference or training use

You will not republish or post the Academic Materials on any network computer or
broadcast in any media;

You will include the Academic Materials original copyright notice, or a copyright notice to
Microsofts benefit in the format provided below:
Form of Notice:
2008 Reprinted for personal reference use only with permission by Microsoft
Corporation. All rights reserved.
Microsoft, Windows, and Windows Server are either registered trademarks or
trademarks of Microsoft Corporation in the US and/or other countries. Other
product and company names mentioned herein may be the trademarks of their
respective owners.

6. INTERNET-BASED SERVICES. Microsoft may provide Internet-based services with the Licensed

Content. It may change or cancel them at any time. You may not use these services in any way that
could harm them or impair anyone elses use of them. You may not use the services to try to gain
unauthorized access to any service, data, account or network by any means.

7. SCOPE OF LICENSE. The Licensed Content is licensed, not sold. This agreement only gives you some

rights to use the Licensed Content. Microsoft reserves all other rights. Unless applicable law gives you
more rights despite this limitation, you may use the Licensed Content only as expressly permitted in this
agreement. In doing so, you must comply with any technical limitations in the Licensed Content that
only allow you to use it in certain ways. You may not

install more copies of the Licensed Content on classroom Devices than the number of Students and
the Trainer in the Authorized Training Session;

allow more classroom Devices to access the server than the number of Students enrolled in and the
Trainer delivering the Authorized Training Session if the Licensed Content is installed on a network
server;

copy or reproduce the Licensed Content to any server or location for further reproduction or
distribution;

disclose the results of any benchmark tests of the Licensed Content to any third party without
Microsofts prior written approval;

work around any technical limitations in the Licensed Content;

reverse engineer, decompile or disassemble the Licensed Content, except and only to the extent
that applicable law expressly permits, despite this limitation;

make more copies of the Licensed Content than specified in this agreement or allowed by applicable
law, despite this limitation;

publish the Licensed Content for others to copy;

transfer the Licensed Content, in whole or in part, to a third party;

access or use any Licensed Content for which you (i) are not providing a Course and/or (ii) have not
been authorized by Microsoft to access and use;

rent, lease or lend the Licensed Content; or

use the Licensed Content for commercial hosting services or general business purposes.

Rights to access the server software that may be included with the Licensed Content, including the
Virtual Hard Disks does not give you any right to implement Microsoft patents or other Microsoft
intellectual property in software or devices that may access the server.

8. EXPORT RESTRICTIONS. The Licensed Content is subject to United States export laws and

regulations. You must comply with all domestic and international export laws and regulations that apply
to the Licensed Content. These laws include restrictions on destinations, end users and end use. For
additional information, see www.microsoft.com/exporting.

9. NOT FOR RESALE SOFTWARE/LICENSED CONTENT. You may not sell software or Licensed
Content marked as NFR or Not for Resale.

10. ACADEMIC EDITION. You must be a Qualified Educational User to use Licensed Content marked as
Academic Edition or AE. If you do not know whether you are a Qualified Educational User, visit
www.microsoft.com/education or contact the Microsoft affiliate serving your country.

11. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you
fail to comply with the terms and conditions of these license terms. In the event your status as an
Authorized Learning Center or Trainer a) expires, b) is voluntarily terminated by you, and/or c) is
terminated by Microsoft, this agreement shall automatically terminate. Upon any termination of this
agreement, you must destroy all copies of the Licensed Content and all of its component parts.

12. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates, Internet-

based services and support services that you use, are the entire agreement for the Licensed
Content and support services.

13. APPLICABLE LAW.


a. United States. If you acquired the Licensed Content in the United States, Washington state law
governs the interpretation of this agreement and applies to claims for breach of it, regardless of
conflict of laws principles. The laws of the state where you live govern all other claims, including
claims under state consumer protection laws, unfair competition laws, and in tort.

b. Outside the United States. If you acquired the Licensed Content in any other country, the laws
of that country apply.

14. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the

laws of your country. You may also have rights with respect to the party from whom you acquired the
Licensed Content. This agreement does not change your rights under the laws of your country if the
laws of your country do not permit it to do so.

15. DISCLAIMER OF WARRANTY. The Licensed Content is licensed as-is. You bear the risk of
using it. Microsoft gives no express warranties, guarantees or conditions. You may have
additional consumer rights under your local laws which this agreement cannot change. To
the extent permitted under your local laws, Microsoft excludes the implied warranties of
merchantability, fitness for a particular purpose and non-infringement.

16. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM
MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT
RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL,
INDIRECT OR INCIDENTAL DAMAGES.
This limitation applies to

anything related to the Licensed Content, software, services, content (including code) on third party
Internet sites, or third party programs; and

claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence,
or other tort to the extent permitted by applicable law.

It also applies even if Microsoft knew or should have known about the possibility of the damages. The
above limitation or exclusion may not apply to you because your country may not allow the exclusion or
limitation of incidental, consequential or other damages.
Please note: As this Licensed Content is distributed in Quebec, Canada, some of the clauses in
this agreement are provided below in French.
Remarque : Ce le contenu sous licence tant distribu au Qubec, Canada, certaines des clauses
dans ce contrat sont fournies ci-dessous en franais.
EXONRATION DE GARANTIE. Le contenu sous licence vis par une licence est offert tel quel . Toute
utilisation de ce contenu sous licence est votre seule risque et pril. Microsoft naccorde aucune autre
garantie expresse. Vous pouvez bnficier de droits additionnels en vertu du droit local sur la protection dues
consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties
implicites de qualit marchande, dadquation un usage particulier et dabsence de contrefaon sont
exclues.
LIMITATION DES DOMMAGES-INTRTS ET EXCLUSION DE RESPONSABILIT POUR LES
DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de
dommages directs uniquement hauteur de 5,00 $ US. Vous ne pouvez prtendre aucune indemnisation
pour les autres dommages, y compris les dommages spciaux, indirects ou accessoires et pertes de
bnfices.
Cette limitation concerne:

tout ce qui est reli au le contenu sous licence , aux services ou au contenu (y compris le code)
figurant sur des sites Internet tiers ou dans des programmes tiers ; et

les rclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilit stricte,


de ngligence ou dune autre faute dans la limite autorise par la loi en vigueur.

Elle sapplique galement, mme si Microsoft connaissait ou devrait connatre lventualit dun tel
dommage. Si votre pays nautorise pas lexclusion ou la limitation de responsabilit pour les dommages
indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou lexclusion ci-dessus ne
sappliquera pas votre gard.
EFFET JURIDIQUE. Le prsent contrat dcrit certains droits juridiques. Vous pourriez avoir dautres droits
prvus par les lois de votre pays. Le prsent contrat ne modifie pas les droits que vous confrent les lois de
votre pays si celles-ci ne le permettent pas.

iii

Contents
Module 1: Getting Started with Windows Communication Foundation
Lesson 1: Designing an Application to be Part of a Service Oriented Architecture
(SOA)
1-3
Lesson 2: Overview of WCF Architecture

1-9

Lesson 3: Using a Language-Level Interface As a Service Contract

1-16

Lesson 4: Implementing a Simple WCF Service in Visual Studio 2008

1-22

Lesson 5: Consuming a simple WCF service in Visual Studio 2008

1-27

Lab: Creating a Simple Service

1-31

Module 2: Configuring and Hosting WCF Services


Lesson 1: Programmatically Configuring a Managed Application to Host a WCF
Service
2-3
Lesson 2: Programmatically Configuring a Managed Application to Call a WCF
Service
2-12
Lesson 3: Defining Client and Service Settings by Using File-Based
Configuration

2-17

Lesson 4: Selecting a Hosting Option for a WCF Service

2-21

Lesson 5: Deploying a WCF Service

2-30

Lab: Configure and Host a WCF Service

2-36

Module 3: Endpoints and Behaviors


Lesson 1: Exposing WCF Services over Different Endpoints

3-3

Lesson 2: Adding Behaviors to Services and Endpoints

3-14

Lesson 3: Interoperating with Non-WCF Web Services

3-20

Lab: Changing Service Endpoints and Behaviors

3-27

MCT USE ONLY. STUDENT USE PROHIBITED

Visual Studio 2008: Windows Communication Foundation

Visual Studio 2008: Windows Communication Foundation

Module 4: Debugging and Diagnostics


Lesson 1: Logging Messages

4-3

Lesson 2: Activity Tracing

4-12

Lab: Message Logging and Activity Tracing

4-17

Module 5: Designing and Defining Contracts


Lesson 1: Designing a Coherent and Cohesive WCF Service Interface

5-3

Lesson 2: Defining a Service Contract

5-10

Lesson 3: Defining Operations on a Service

5-16

Lesson 4: Defining a Data Contract

5-23

Lab: Contracts for Services and Data

5-30

Module 6: Handling Errors


Lesson 1: Relating .NET Exceptions to Service-level Faults

6-3

Lesson 2: Using Faults in a Service

6-8

Lesson 3: Handling Faults and Exceptions on Clients

6-17

Lab: Error Handling

6-24

Module 7: Improving WCF Service Quality


Lesson 1: Managing WCF Service Instances

7-3

Lesson 2: Managing Concurrency Issues

7-11

Lesson 3: Improving WCF Service Quality

7-17

Lesson 4: Improving Data Transfer Throughput

7-23

Lab: Improving WCF Service Quality

7-31

Module 8: Implementing WCF Security


Lesson 1: Overview of Security in WCF

8-3

Lesson 2: Applying Overall Security Requirements to a Binding

8-14

Lesson 3: Specifying Required Client and Service Credentials

8-25

Lesson 4: Working with Security Information

8-34

Lab: Protecting a Service

8-41

MCT USE ONLY. STUDENT USE PROHIBITED

iv

Module 9: Implementing Transactions


Lesson 1: Overview of Transactions in a Service-Oriented Application

9-3

Lesson 2: Creating Transactional Service Operations

9-10

Lesson 3: Enabling the Flow of Transactions from Client to Service

9-16

Lab: Implementing Transactions for a Service

9-22

Course Evaluation

9-34

Lab Answer Keys


Lab Answer Key 1: Getting Started with Windows Communication
Foundation

L1-1 -L1-22

Lab Answer Key 2: Configuring and Hosting WCF Services

L2-23 - L2-44

Lab Answer Key 3: Endpoints and Behaviors

L3-45 - L3-64

Lab Answer Key 4: Debugging and Diagnostics

L4-65 - L4-74

Lab Answer Key 5: Designing and Defining Contracts

L5-75 - L5-104

Lab Answer Key 6: Handling Errors

L6-105- L6-120

Lab Answer Key 7: Improving WCF Service Quality

L7-121 - L7-150

Lab Answer Key 8: Implementing WCF Security

L8-151 - L8-166

Lab Answer Key 9: Implementing Transactions

L9-167 - L9-192

MCT USE ONLY. STUDENT USE PROHIBITED

Visual Studio 2008: Windows Communication Foundation

L1-1

Module 1: Getting Started with Windows


Communication Foundation

Lab: Creating a Simple Service


Scenario
You are a developer on the Contoso Clinic Management product team. You are
starting development and you have been assigned to the appointments service in
this initial phase.

Logon Information:

Virtual Machine: 6461A-LON-DEV-01

User Name: Student

Password: Pa$$w0rd

Estimated time: 40 minutes

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating a Simple Service

Module 1: Getting Started with Windows Communication Foundation

Exercise 1: Creating a Simple WCF Service


In this exercise, you will develop the WCF service by using the WCF Service
Library template in Microsoft Visual Studio 2008. You will then define a service
contract, implement the service contract, and configure the service's endpoints.
Finally, you will host the service in Internet Information Service (IIS).
The main tasks for this exercise are as follows:
1.

Start the 6461-LON-DEV-01 virtual machine and log on as Student.

2.

Add a new WCF Service Library project to the existing ConnectedWCF


solution.

3.

Add the existing AppointmentHelperClass to the solution.

4.

Define the service contract.

5.

Implement the service contract.

6.

Add a WCF Service Application project to the ConnectedWCF solution.

7.

Configure the endpoints for the service.

8.

Test the AppointmentService.

f Task 1: Start the 6461-LON-DEV-01 virtual machine and log on as


Student.
1.

Open the Virtual Server Remote Control Client and double-click 6461-LONDEV-01.

2.

Log on to 6461-LON-DEV-01 as Student using the password Pa$$w0rd.

f Task 2: Add a new WCF Service Library project to the existing


ConnectedWCF solution.
1.

On the Start menu, point to All Programs, point to Microsoft Visual Studio
2008, and then click Microsoft Visual Studio 2008.

2.

In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.

MCT USE ONLY. STUDENT USE PROHIBITED

L1-2

3.

L1-3

In the Open Project dialog box, browse to either of the following:

If you are using Visual Basic, browse to the


E:\Labfiles\Starter\VB\ConnectedWCF folder, and then double-click the
ConnectedWCF.sln file.

If you are using Visual C#, browse to the


E:\Labfiles\Starter\CS\ConnectedWCF folder, and then double-click the
ConnectedWCF.sln file.

4.

On the File menu, point to Add, and then click New Project.

5.

In the Add New Project dialog box, define a project with the following
properties, and then click OK:

Project types: If you are using Visual Basic, expand Visual Basic, and then
click WCF. If you are using Visual C#, expand Visual C#, and then click
WCF.

Templates: Click the WCF Service Library project template.

Name: In the Name box, type AppointmentService

Location: If you are using Visual Basic, in the Location box, type
E:\Labfiles\Starter\VB\ConnectedWCF If you are using Visual C#, in
the Location box, type E:\Labfiles\Starter\CS\ConnectedWCF

6.

In Solution Explorer, right-click the AppointmentService project, and then


click Properties.

7.

In the Properties window, on the Application tab, in the Root namespace box
(for Visual Basic) or Default namespace box for Visual C#), type
com.contoso.AppointmentService

8.

On the File menu, click Save All.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating a Simple Service

Module 1: Getting Started with Windows Communication Foundation

f Task 3: Add the existing AppointmentHelperClass to the solution.


1.

In Solution Explorer, right-click the AppointmentService project, click Add,


and then click Existing Item.

2.

In the Add Existing Item - AppointmentService dialog box, browse to the


following file:

3.

If you are using Visual Basic, browse to the E:\Labfiles\Starter\VB\


folder, and then double-click the AppointmentHelperClass.vb file.

If you are using Visual C#, browse to the E:\Labfiles\Starter\CS\ folder,


and then double-click the AppointmentHelperClass.cs file.

In Solution Explorer, right-click AppointmentHelperClass, and then click


View Code.

f Task 4: Define the service contract.


1.

In Solution Explorer, right-click IService1, click Rename, type


AppointmentServiceContract.vb (for Visual Basic) or
AppointmentServiceContract.cs (for Visual C#), and then press ENTER.

2.

If you are using Visual Basic, in the Microsoft Visual Studio dialog box, click
Yes.

3.

In Solution Explorer, right-click AppointmentServiceContract, and then click


View Code.

4.

If you are using Visual C#, change the namespace to


com.contoso.AppointmentService.
[Visual C#]
...
namespace com.contoso.AppointmentService
{
...
}

MCT USE ONLY. STUDENT USE PROHIBITED

L1-4

5.

L1-5

If you are using Visual C#, change the interface name to


AppointmentServiceContract.
[Visual C#]
...
public interface AppointmentServiceContract
{
}
...

6.

7.

In the Code Editor window for the AppointmentServiceContract class file,


remove the following:

All comments

The CompositeType class definition

The GetData and GetDataUsingDataContract methods in the


AppointmentServiceContract interface definition

Modify the ServiceContract attribute on the AppointmentServiceContract


definition to include the namespace
http://contoso.com/services/AppointmentService.
[Visual Basic]
...
<ServiceContract(Namespace:= _
"http://contoso.com/services/AppointmentService")> _
...

[Visual C#]
...
[ServiceContract(Namespace =
"http://contoso.com/services/AppointmentService")]
...

8.

Within the AppointmentServiceContract definition, define a method named


CreateAppointment that returns a string and that accepts a string parameter
named patientId, a string parameter named doctorId, and a DateTime
parameter named start.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating a Simple Service

Module 1: Getting Started with Windows Communication Foundation

9.

Add the OperationContract attribute to the CreateAppointment method.


[Visual Basic
...
<OperationContract()> _
Function CreateAppointment(ByVal patientId As String, _
ByVal doctorId As String, ByVal start As DateTime) As String
...

[Visual C#]
...
[OperationContract]
string CreateAppointment(string patientId, string doctorId,
DateTime start);
...

10. Define a second method named CancelAppointment that returns a bool value
and that accepts a string parameter named appointmentId.
11. Add the OperationContract attribute to the CancelAppointment method.
[Visual Basic
...
<OperationContract()> _
Function CancelAppointment(ByVal appointmentId As String) _
As Boolean
...

[Visual C#]
...
[OperationContract]
bool CancelAppointment(string appointmentId);
...

12. Define a third method named ListAvailableAppointmentTimes that returns a


generic List of type DataTime and accepts a string parameter named doctorId
and a DataTime parameter named day.

MCT USE ONLY. STUDENT USE PROHIBITED

L1-6

L1-7

13. Add the OperationContract attribute to the ListAvailableAppointmentTimes


method.
[Visual Basic
...
<OperationContract()> _
Function ListAvailableAppointmentTimes(ByVal doctorId As String, _
ByVal day As DateTime) As List(Of DateTime)
...

[Visual C#]
...
[OperationContract]
List<DateTime> ListAvailableAppointmentTimes(string doctorId,
DateTime day);
...

Your code for the AppointmentServiceContract class should resemble the


following.
[Visual Basic]
<ServiceContract(Namespace:= _
"http://contoso.com/services/AppointmentService")> _
Public Interface AppointmentServiceContract
<OperationContract()> _
Function CreateAppointment(ByVal patientId As String, _
ByVal doctorId As String, ByVal start As DateTime) As String
<OperationContract()> _
Function CancelAppointment(ByVal appointmentId As String) _
As Boolean
<OperationContract()> _
Function ListAvailableAppointmentTimes(ByVal doctorId As String,
_
ByVal day As DateTime) As List(Of DateTime)
End Interface

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating a Simple Service

Module 1: Getting Started with Windows Communication Foundation

[Visual C#]
...
namespace com.contoso.AppointmentService
{
[ServiceContract(Namespace =
"http://contoso.com/services/AppointmentService")]
public interface AppointmentServiceContract
{
[OperationContract]
string CreateAppointment(string patientId, string doctorId,
DateTime start);
[OperationContract]
bool CancelAppointment(string appointmentId);
[OperationContract]
List<DateTime> ListAvailableAppointmentTimes(string doctorId,
DateTime day);
}
}

f Task 5: Implement the service contract.


1.

In Solution Explorer, right-click Service1, click Rename, type


AppointmentServiceImplementation.vb (for Visual Basic) or
AppointmentServiceImplementation.cs (for Visual C#), and then press
ENTER.

2.

If you are using Visual Basic, in the Microsoft Visual Studio dialog box, click
Yes.

3.

In Solution Explorer, right-click AppointmentServiceImplementation, and


then click View Code.

4.

If you are using Visual C#, change the namespace to


com.contoso.AppointmentService.

If you are using Visual C#, rename the Service1 class definition to
AppointmentServiceImplementation.

6.

Remove the following from the AppointmentServiceImplementation class:

All comments

The GetData and GetDataUsingDataContract methods

MCT USE ONLY. STUDENT USE PROHIBITED

L1-8

L1-9

7.

Implement the AppointmentServiceContract interface. If you are using Visual


Basic, press ENTER after you type the interface name to generate the method
stubs. If you are using Visual C#, right-click the text
AppointmentServiceContract in the class definition, point to Implement
Interface, and then click Implement Interface.

8.

If you are using Visual C#, remove the following code from the
CreateAppointment, CancelAppointment and
ListAvailableAppointmentTimes methods.
[Visual C#]
...
throw new NotImplementedException();
...

9.

In the CreateAppointment method, add code to do the following:

Create an Appointment object named newAppointment, and then pass


the variables patientId, doctorId, and start as parameters to the
constructor.

Return the result of the static GenerateNewAppointment method in the


AppointmentHelperClass class. Pass the newAppointment object as a
parameter.

[Visual Basic]
...
Public Function CreateAppointment(ByVal patientId As String, _
ByVal doctorId As String, ByVal start As Date) _
As String Implements
AppointmentServiceContract.CreateAppointment
Dim newAppointment As New Appointment(patientId, doctorId, _
start)
Return AppointmentHelperClass. _
GenerateNewAppointment(newAppointment)
End Function
...

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating a Simple Service

Module 1: Getting Started with Windows Communication Foundation

[Visual C#]
...
public string CreateAppointment(string patientId, string doctorId,
DateTime start)
{
Appointment newAppointment = new Appointment(patientId,
doctorId,
start);
return AppointmentHelperClass.GenerateNewAppointment(
newAppointment);
}
...

10. In the CancelAppointment method, add code to return the result of the static
CancelExistingAppointment method in the AppointmentHelperClass class.
Pass the appointmentId variable as a parameter.
[Visual Basic]
...
Public Function CancelAppointment(ByVal appointmentId As String) _
As Boolean Implements
AppointmentServiceContract.CancelAppointment
Return AppointmentHelperClass.CancelExistingAppointment( _
appointmentId)
End Function
...

[Visual C#]
...
public bool CancelAppointment(string appointmentId)
{
return AppointmentHelperClass.CancelExistingAppointment(
appointmentId);
}
...

MCT USE ONLY. STUDENT USE PROHIBITED

L1-10

L1-11

11. In the ListAvailableAppointmentTimes method, add code to return the result


of the static GetAvailableAppointments method in the
AppointmentHelperClass class. Pass the doctorId and day variables as
parameters.
[Visual Basic]
...
Public Function ListAvailableAppointmentTimes(ByVal doctorId _
As String, ByVal day As Date) As System.Collections. _
Generic.List(Of Date) Implements _
AppointmentServiceContract.ListAvailableAppointmentTimes
Return AppointmentHelperClass.GetAvailableAppointments(doctorId,
_
day)
End Function
...

[Visual C#]
...
public List<DateTime> ListAvailableAppointmentTimes(string
doctorId,
DateTime day)
{
return AppointmentHelperClass.GetAvailableAppointments(doctorId,
day);
}
...

12. In Solution Explorer, right-click the AppointmentService project, and then


click Build.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating a Simple Service

Module 1: Getting Started with Windows Communication Foundation

Your code for the AppointmentServiceImplementation class should resemble


the following.
[Visual Basic]
...
Public Class AppointmentServiceImplementation
Implements AppointmentServiceContract
Public Function CreateAppointment(ByVal patientId As String, _
ByVal doctorId As String, ByVal start As Date) _
As String Implements _
AppointmentServiceContract.CreateAppointment
Dim newAppointment As New Appointment(patientId, doctorId, _
start)
Return AppointmentHelperClass. _
GenerateNewAppointment(newAppointment)
End Function
Public Function CancelAppointment(ByVal appointmentId As String)
_
As Boolean Implements _
AppointmentServiceContract.CancelAppointment
Return AppointmentHelperClass.CancelExistingAppointment( _
appointmentId)
End Function
Public Function ListAvailableAppointmentTimes(ByVal doctorId _
As String, ByVal day As Date) As System.Collections. _
Generic.List(Of Date) Implements _
AppointmentServiceContract.ListAvailableAppointmentTimes
Return AppointmentHelperClass.GetAvailableAppointments( _
doctorId, day)
End Function
End Class
...

MCT USE ONLY. STUDENT USE PROHIBITED

L1-12

[Visual C#]
...
namespace com.contoso.AppointmentService
{
public class AppointmentServiceImplementation :
AppointmentServiceContract
{
#region AppointmentServiceContract Members
public string CreateAppointment(string patientId, string
doctorId,
DateTime start)
{
Appointment newAppointment = new Appointment(patientId,
doctorId,
start);
return AppointmentHelperClass.GenerateNewAppointment(
newAppointment);
}
public bool CancelAppointment(string appointmentId)
{
return AppointmentHelperClass.CancelExistingAppointment(
appointmentId);
}
public List<DateTime> ListAvailableAppointmentTimes(
string doctorId, DateTime day)
{
return
AppointmentHelperClass.GetAvailableAppointments(doctorId,
day);
}
#endregion
}
...

L1-13

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating a Simple Service

Module 1: Getting Started with Windows Communication Foundation

f Task 6: Add a WCF Service Application project to the ConnectedWCF


solution.
1.

On the File menu, point to Add, and then click New Project.

2.

In the Add New Project dialog box, define a project with the following
properties, and then click OK:

Project types: If you are using Visual Basic, expand Visual Basic, and then
click Web. If you are using Visual C#, expand Visual C#, and then click
Web.

Templates: Click the WCF Service Application project template.

Name: In the Name box, type AppointmentServiceIISHost

Location: If you are using Visual Basic, in the Location box, type
E:\Labfiles\Starter\VB\ConnectedWCF If you are using Visual C#, in
the Location box, type E:\Labfiles\Starter\CS\ConnectedWCF

3.

In Solution Explorer, right-click the AppointmentServiceIISHost project, and


then click Properties.

4.

In the Properties window, on the Web tab, in the Servers section, click
Specific port, and then in the corresponding box, type 8001

5.

On the File menu, click Save All.

6.

If you are using Visual Basic, in Solution Explorer, click Show All Files.

7.

Remove the following files and folders from the AppointmentServiceIISHost


project:

The IService1 class file

The Service1.svc.vb (for Visual Basic) or Service.svc.cs (for Visual C#)

The App_Data folder

8.

In Solution Explorer, right-click the AppointmentServiceIISHost project, and


then click Add Reference.

9.

In the Add Reference dialog box, on the Projects tab, double-click


AppointmentService.

10. In Solution Explorer, within the AppointmentServiceIISHost project, rightclick the Service1.svc file, click Rename, type AppointmentService.svc and
then press ENTER.

MCT USE ONLY. STUDENT USE PROHIBITED

L1-14

L1-15

11. In Solution Explorer, right-click AppointmentService.svc, and then click View


Markup.
12. In the Code Editor window, make the following changes to the ServiceHost
element in the AppointmentService.svc file:

Change the Service attribute value to


com.contoso.AppointmentService.AppointmentServiceImplementation.

Remove the CodeBehind attribute and value.

[Visual Basic]
<%@ ServiceHost Language="vb" Debug="true"
Service="com.contoso.AppointmentService.AppointmentServiceImplement
ation" %>

[Visual C#]
<%@ ServiceHost Language="c#" Debug="true"
Service="com.contoso.AppointmentService.AppointmentServiceImplement
ation" %>

13. On the File menu, click Save All.


14. In Solution Explorer, right-click the AppointmentServiceIISHost project, and
then click Build.

f Task 7: Configure the endpoints for the AppointmentServiceIISHost.


1.

In Solution Explorer, within the AppointmentServiceIISHost project, rightclick Web.config, and then click Edit WCF Configuration.

2.

In the WCF Service Configuration Editor window, in the Configuration pane,


expand Advanced, expand ServiceBehaviors, and then click
AppointmentServiceIISHost.Service1Behavior.

3.

In the right pane, in the General section, in the Name box, type
AppointmentServiceIISHost.ServiceBehavior

4.

In the left pane under Services, click AppointmentServiceIISHost.Service1.

5.

In the right pane, in the Name box, type


com.contoso.AppointmentService.AppointmentServiceImplementation and
then press ENTER.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating a Simple Service

Module 1: Getting Started with Windows Communication Foundation

6.

In the left pane under Services, expand


com.contoso.AppointmentService.AppointmentServiceImplementation,
expand Endpoints, and then click the first {EmptyName] node.

In the right-pane, in the Contract box, type


com.contoso.AppointmentService.AppointmentServiceContract

8.

In the Microsoft Service Configuration Editor window, on the File menu, click
Save.

9.

Close the Microsoft Service Configuration Editor window.

f Task 8: Test the AppointmentService.


1.

In Solution Explorer, right-click the AppointmentServiceIISHost project,


point to Debug, and then click Start new instance.

2.

In the Debugging Not Enabled dialog box, click OK.

3.

In the Script Debugging Disabled dialog box, click Yes.

4.

In the Information Bar dialog box, click Close.

5.

In Internet Explorer, on the Directory Listing page, click


AppointmentService.svc.

6.

If you have successfully configured and hosted the AppointmentService,


Internet Explorer will display the AppointmentServiceImplementation
service default page.

7.

Close Internet Explorer.

Results: After this exercise, you should have developed a WCF service in Visual
Studio 2008.

MCT USE ONLY. STUDENT USE PROHIBITED

L1-16

L1-17

Exercise 2: Calling the Simple WCF Service


In this exercise, you will add code to the existing ClinicAdminClient Windows
Forms application to enable users to find all the available appointment timeslots,
create a new appointment, and delete an existing appointment.
The main tasks for this exercise are as follows:
1.

Add a reference to the AppointmentService.

2.

Add code to the ClinicAdminClient class.

3.

Build and run the solution.

f Task 1: Add a reference to the AppointmentService.


1.

In Solution Explorer, right-click the ClinicAdminClient project, and then click


Add Service Reference.

2.

In the Add Service Reference dialog box, define a service reference with the
following information, and then click OK.
a.

Address: In the Address box, type


http://localhost:8001/AppointmentService.svc and then click Go.

b.

Namespace: In the Namespace box, type AppointmentServiceReference

f Task 2: Add code to the ClinicAdminClient class.


1.

In Solution Explorer, right-click ClinicAdminForm, and then click View Code.

2.

Locate the TODO 1 comment, and bring the


ClinicAdminClient.AppointmentServiceReference into scope.
[Visual Basic]
...
'TODO 1.
Imports ClinicAdminClient.AppointmentServiceReference
...

[Visual C#]
...
//TODO 1.
using ClinicAdminClient.AppointmentServiceReference;
...

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating a Simple Service

Module 1: Getting Started with Windows Communication Foundation

3.

Locate the TODO 2 comment, and then add code to return a new
AppointmentServiceContractClient object.
[Visual Basic]
...
Private Function GetAppointmentServiceProxy() As _
AppointmentServiceContract
' TODO 2.
Return New AppointmentServiceContractClient()
End Function
...

[Visual C#]
...
private AppointmentServiceContract GetAppointmentServiceProxy()
{
// TODO 2.
return new AppointmentServiceContractClient();
}
...

4.

Locate the TODO 3 comment, and then add code to do the following:

Create a new AppointmentServiceContract object called proxy, and then


initialize it to the return value of the GetAppointmentServiceProxy
method.

Set the slots object to the return value of the


ListAvailableAppointmentTimes method in the proxy class. Pass the
Text property of the doctorId field and the Value property of the
dateRequested field as parameters.

[Visual Basic]
...
' TODO 3.
Dim proxy As AppointmentServiceContract = _
GetAppointmentServiceProxy()
slots = proxy.ListAvailableAppointmentTimes(doctorId.Text, _
dateRequested.Value)
...

MCT USE ONLY. STUDENT USE PROHIBITED

L1-18

L1-19

[Visual C#]
...
// TODO 3.
AppointmentServiceContract proxy = GetAppointmentServiceProxy();
slots = proxy.ListAvailableAppointmentTimes(doctorId.Text,
dateRequested.Value);
...

5.

Locate the TODO 4 comment, and then add code to do the following:

Create a new AppointmentServiceContract object named proxy, and


then initialize it to the return value of the GetAppointmentServiceProxy
method.

Set the appointmentId variable to the return value of the


CreateAppointment method in the proxy class. Pass the Text property of
the patientId field, the Text property of the doctorId field, and the slot
variable as parameters.

[Visual Basic]
...
' TODO 4.
Dim proxy As AppointmentServiceContract _
= GetAppointmentServiceProxy()
appointmentId = _
proxy.CreateAppointment(patientId.Text, doctorId.Text, slot)
...

[Visual C#]
...
// TODO 4.
AppointmentServiceContract proxy = GetAppointmentServiceProxy();
appointmentId = proxy.CreateAppointment(patientId.Text,
doctorId.Text, slot);
...

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating a Simple Service

Module 1: Getting Started with Windows Communication Foundation

6.

Locate the TODO 5 comment, and then add code to do the following:

Create a new AppointmentServiceContract object named proxy, and


then initialize it to the return value of the GetAppointmentServiceProxy
method.

Set the cancelled variable to the return value of the CancelAppointment


method in the proxy class. Pass the Text property of the appointmentId
field as a parameter.

[Visual Basic]
...
' TODO 5.
Dim proxy As AppointmentServiceContract _
= GetAppointmentServiceProxy()
cancelled = proxy.CancelAppointment(appointmentId.Text)
...

[Visual C#]
...
// TODO 5.
AppointmentServiceContract proxy = GetAppointmentServiceProxy();
cancelled = proxy.CancelAppointment(appointmentId.Text);
...

MCT USE ONLY. STUDENT USE PROHIBITED

L1-20

L1-21

f Task 3: Build and run the solution.


1.

On the Build menu, click Build Solution.

2.

On the Debug menu, click Start Debugging.

3.

On the Clinic Administration Client form, on the Create Appointment tab,


click Find Slots.

4.

Create an appointment with the following information, and then click Create:

Doctor: In Doctor list, click ENT_Davies.

Slots: In the Slots list, click any of the available time slots.

Patient: In the Patient box, type your name.

5.

In the Appointment Created dialog box, make a note of the Appointment


identifier, and then click OK.

6.

On the Cancel Appointment tab, in the Appt ID box, type your Appointment
identifier, and then click Delete.

7.

In the Appointment Cancellation dialog box, click OK.

8.

In Visual Studio 2008, on the Debug menu, click Stop Debugging.

9.

Close Visual Studio 2008.

Results: After this exercise, you should have enhanced the existing
ClinicAdminClient application to invoke the methods in the AppointmentService.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating a Simple Service

L2-23

Module 2: Configuring and Hosting WCF


Services

Lab: Configure and Host a WCF


Service
Scenario
You are a developer on the Contoso Clinic Management product team. Your team
has developed part of the appointment service and your task now is to look at the
different ways of storing the WCF configurations settings and hosting the
appointments service.

Logon Information:

Virtual Machine: 6461A-LON-DEV-02

User Name: Student

Password: Pa$$w0rd

Estimated time: 80 minutes

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Configure and Host a WCF Service

Module 2: Configuring and Hosting WCF Services

Exercise 1: Creating a Programmatically Configured


Managed Application to Host a Service
In this exercise, you will develop an EXE application to host the appointment
service.
The main tasks for this exercise are as follows:
1.

Start the 6461-LON-DEV-02 virtual machine and log on as Student.

2.

Open the existing ConnectedWCF solution.

3.

Add a new Windows Console application to the ConnectedWCF solution.

4.

Add code to host the AppointmentService.

5.

Change the endpoint address in the ClinicAdminClient.

6.

Set the ConnectedWCF solution startup projects.

7.

Build and run the solution.

f Task 1: Start the 6461-LON-DEV-02 virtual machine and log on as


Student
1.

Open the Virtual Server Remote Control Client, and then double-click 6461LON-DEV-02.

2.

Log on to 6461-LON-DEV-02 as Student using the password Pa$$w0rd.

f Task 2: Open the existing ConnectedWCF solution


1.

On the Start menu, point to All Programs, point to Microsoft Visual Studio
2008, right-click Microsoft Visual Studio 2008, and then click Run as
administrator

2.

In the User Account Control dialog box, click Continue.

3.

In Microsoft Visual Studio 2008 development system, on the File menu,


point to Open, and then click Project/Solution.

MCT USE ONLY. STUDENT USE PROHIBITED

L2-24

4.

L2-25

In the Open Project dialog box, go to either of the following:

If you are using Microsoft Visual Basic development system, go to the


E:\Labfiles\Starter\VB\Ex1\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

If you are using Microsoft Visual C# development tool, go to the


E:\Labfiles\Starter\CS\Ex1\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

f Task 3: Add a new Windows Console application to the


ConnectedWCF solution
1.

On the File menu, point to Add, and then click New Project.

2.

In the Add New Project dialog box, define a project with the following
properties, and then click OK.

Project types: If you are using Visual Basic, expand Visual Basic, and then
click Windows. If you are using Visual C#, expand Visual C#, and then
click Windows.

Templates: Click the ConsoleApplication project template.

Name: In the Name box type AppointmentServiceSelfHost.

Location: If you are using Visual Basic, in the Location box, type
E:\Labfiles\Starter\VB\Ex1\ConnectedWCF
If you are using Visual C#, in the Location box, type
E:\Labfiles\Starter\CS\Ex1\ConnectedWCF

f Task 4: Add code to host the AppointmentService


1.

In Solution Explorer, right-click the AppointmentServiceSelfHost project, and


then click Add Reference.

2.

In the Add Reference dialog box, on the .NET tab, in the Component Name
column, double-click the System.ServiceModel assembly.

3.

In Solution Explorer, right-click the AppointmentServiceSelfHost project, and


then click Add Reference.

4.

In the Add Reference dialog box, on the Projects tab, in the Project Name
column, double-click the AppointmentService assembly.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Configure and Host a WCF Service

Module 2: Configuring and Hosting WCF Services

5.

In the Code Editor window for the Module1 class (for Visual Basic) or
Program class (for Visual C#), bring the System.ServiceModel namespace
into scope.
[Visual Basic]
...
Imports System.ServiceModel
...

[Visual C#]
...
using System.ServiceModel;
...

6.

In the Main method, create a new Uri object named baseAddress. Pass the
string http://localhost:8002/Contoso as a parameter.
[Visual Basic]
...
Dim baseAddress As New Uri("http://localhost:8002/Contoso")
...

[Visual C#]
...
Uri baseAddress = new Uri("http://localhost:8002/Contoso");
...

7.

Create a new Type object named instanceType. Initialize the instanceType


object to
com.contoso.AppointmentService.AppointmentServiceImplementation.
[Visual Basic]
...
Dim instanceType As Type = _
GetType(com.contoso.AppointmentService. _
AppointmentServiceImplementation)
...

MCT USE ONLY. STUDENT USE PROHIBITED

L2-26

L2-27

[Visual C#]
...
Type instanceType =
typeof(com.contoso.AppointmentService.
AppointmentServiceImplementation);
...

8.

Create a new ServiceHost object named host. Pass the instanceType and
baseAddress objects to the ServiceHost constructor.
[Visual Basic]
...
Dim host As New ServiceHost(instanceType, baseAddress)
...

[Visual C#]
...
ServiceHost host = new ServiceHost(instanceType, baseAddress);
...

9.

Add a Using block (for Visual Basic) or using block (for Visual C#), and then
pass the host object as a parameter.
[Visual Basic]
...
Using host
End Using
...

[Visual C#]
...
using (host)
{
}
...

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Configure and Host a WCF Service

Module 2: Configuring and Hosting WCF Services

10. In the Using block (for Visual Basic) or using block (for Visual C#), add code
to do the following:
a.

Create a new instance of the Type class named contractType. Initialize the
contractType object to
com.contoso.AppointmentService.AppointmentServiceImplementation.

b.

Create a new string variable named relativeAddress, and then initialize it


to the text AppointmentService.

c.

Add a WSHttpBinding endpoint to the host object. To do this, invoke the


AddServiceEndpoint method on the host object. Pass the contractType
variable, a new WsHttpBinding object, and the relativeAddress variable
as parameters.

d. Invoke the Open method on the host object.


e.

Write the following message to the console:


Appointment service running. Press <ENTER> to quit.

f.

Invoke the ReadLine method on the Console class to stop the console
from closing.

g.

Invoke the Close method on the host object.


[Visual Basic]
...
Using host
Dim contractType As Type = _
GetType(com.contoso.AppointmentService. _
AppointmentServiceContract)
Dim relativeAddress As String = "AppointmentService"
host.AddServiceEndpoint(contractType, New WSHttpBinding(), _
relativeAddress)
host.Open()
Console.WriteLine("Appointment service " & _
"running. Press <ENTER> to quit.")
Console.ReadLine()
host.Close()
End Using
...

MCT USE ONLY. STUDENT USE PROHIBITED

L2-28

L2-29

[Visual C#]
...
using (host)
{
Type contractType =
typeof(com.contoso.AppointmentService.
AppointmentServiceContract);
string relativeAddress = "AppointmentService";
host.AddServiceEndpoint(contractType,
new WSHttpBinding(), relativeAddress);
host.Open();
Console.WriteLine("Appointment service " +
"running. Press <ENTER> to quit.");
Console.ReadLine();
host.Close();
}
...

f Task 5: Change the endpoint address in the ClinicAdminClient


1.

In Solution Explorer, in the ClinicAdminClient project, right-click the


app.config (for Visual Basic) or App.config (for Visual C#) file, and then click
Edit WCF Configuration.

In the Microsoft Service Configuration Editor, in the left pane, expand the
Endpoints folder under the Client folder, and then click
WSHttpBinding_AppointmentServiceContract.

In the right pane, change the Address property to


http://localhost:8002/Contoso/AppointmentService.

4.

On the File menu, click Save, and then close the Microsoft Service
Configuration Editor.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Configure and Host a WCF Service

Module 2: Configuring and Hosting WCF Services

f Task 6: Set the ConnectedWCF solution startup projects


1.

In Solution Explorer, right-click the ConnectedWCF solution, and then click


Set Startup Projects.

2.

In the Solution 'ConnectedWCF' Property Pages dialog box, click Multiple


startup projects.

3.

In the Multiple startup projects list, set the Action for the
AppointmentServiceSelfHost and ClinicAdminClient projects to Start. Set
the Action for the remaining projects to None.

4.

In the Solution 'ConnectedWCF' Property Pages dialog box, click OK.

f Task 7: Build and run the solution


1.

On the Build menu, click Build Solution.

2.

On the Debug menu, click Start Debugging.

3.

Wait for the Console window to display the following message:


Appointment service running. Press <ENTER> to quit.
In the Clinic Administration Client form, on the Create Appointment tab,
click Find Slots. You should see the list of available appointments.

4.

In Visual Studio 2008, on the Debug menu, click Stop Debugging.

Results: After this exercise, you should have developed an EXE host for the
appointment service.

MCT USE ONLY. STUDENT USE PROHIBITED

L2-30

L2-31

Exercise 2: Calling a Service Hosted in a Managed


Application by Using Programmatic Configuration
In this exercise, you will programmatically define the WCF configuration for the
ClinicAdminClient project.
The main tasks for this exercise are as follows:
1.

Remove the existing endpoint configuration from the ClinicAdminClient


configuration file.

2.

Programmatically add code to define the endpoint configuration.

3.

Build and run the solution.

f Task 1: Remove the existing endpoint configuration from the


ClinicAdminClient configuration file
1.

In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.

2.

In the Open Project dialog box, go to either of the following:

If you are using Visual Basic, go to the


E:\Labfiles\Starter\VB\Ex2\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

If you are using Visual C#, go to the


E:\Labfiles\Starter\CS\Ex2\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

3.

In Solution Explorer, in the ClinicAdminClient project, double-click the


app.config file (for Visual Basic) or the App.config file (for Visual C#).

4.

In the Code Editor window for the configuration file, remove the
<system.serviceModel> </system.serviceModel> element and all its subelements.

5.

On the File menu, click Save All.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Configure and Host a WCF Service

Module 2: Configuring and Hosting WCF Services

f Task 2: Programmatically add code to define the endpoint


configuration
1.

In Solution Explorer, right-click the ClinicAdminForm class, and then click


View Code.

2.

If you are using Visual Basic, bring the System.ServiceModel namespace into
scope.
[Visual Basic]
...
Imports System.ServiceModel
...

3.

Locate the GetAppointmentServiceProxy method, and then remove the


existing method body code.

4.

In the GetAppointmentServiceProxy method, add code to do the following:


a.

Create a new instance of the EndpointAddress class named address. Pass


the text http://localhost:8002/Contoso/AppointmentService to the
constructor.

b.

Create a new instance of the WSHttpBinding class named binding.

c.

Create a new variable of type AppointmentServiceContract named proxy.

d. Instantiate the proxy object to the return value of the CreateChannel


method of the form of the ChannelFactory class that is specific to the
AppointmentServiceContract type. Pass the binding and address objects
as parameters in the method call.
e.

Return the proxy object to the method caller.

[Visual Basic]
...
Private Function GetAppointmentServiceProxy() As _
AppointmentServiceContract
Dim address As New EndpointAddress("http://localhost:8002/" & _
"Contoso/AppointmentService")
Dim binding As New WSHttpBinding()
Dim proxy As AppointmentServiceContract = _
ChannelFactory(Of AppointmentServiceContract). _
CreateChannel(binding, address)
Return proxy
End Function...

MCT USE ONLY. STUDENT USE PROHIBITED

L2-32

L2-33

[Visual C#]
...
private AppointmentServiceContract GetAppointmentServiceProxy()
{
EndpointAddress address =
new EndpointAddress("http://localhost:8002/" +
"Contoso/AppointmentService");
WSHttpBinding binding = new WSHttpBinding();
AppointmentServiceContract proxy =
ChannelFactory<AppointmentServiceContract>.
CreateChannel(binding, address);
return proxy;
}
...

f Task 3: Build and run the solution


1.

On the Build menu, click Build Solution.

2.

On the Debug menu, click Start Debugging.

3.

Wait for the Console window to display the following message:


Appointment service running. Press <ENTER> to quit.
In the Clinic Administration Client form, on the Create Appointment tab,
click Find Slots. You should see the list of available appointments.

4.

In Visual Studio 2008, on the Debug menu, click Stop Debugging.

Results: After this exercise, you should have programmatically defined the WCF
configuration for the AppontmentServiceSelfHost and ClinicAdminClient
projects.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Configure and Host a WCF Service

Module 2: Configuring and Hosting WCF Services

Exercise 3: Defining Service Settings by Using External


Configuration
In this exercise, you will remove the programmatic WCF configuration from the
AppointmentServiceSelfHost and ClinicAdminClient projects and then provide
the configuration in external configuration files.
The main tasks for this exercise are as follows:
1.

Add an external configuration file to the AppointmentServiceSelfHost project.

2.

Remove the programmatic endpoint configuration from the


AppointmentServiceSelfHost project.

3.

Remove the programmatic endpoint configuration from the


ClinicAdminClient project.

4.

Build and run the solution.

f Task 1: Add an external configuration file to the


AppointmentServiceSelfHost project
1.

In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.

2.

In the Open Project dialog box, go to either of the following:

If you are using Visual Basic, go to the


E:\Labfiles\Starter\VB\Ex3\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

If you are using Visual C#, go to the


E:\Labfiles\Starter\CS\Ex3\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

3.

In Solution Explorer, right-click the AppointmentServiceSelfHost project,


point to Add, and then click New Item.

4.

In the Add New Item - AppointmentServiceSelfHost dialog box, do the


following, and then click Add:

If you are using Visual Basic, in the Categories pane, click General, and
then in the Templates pane, click Application Configuration File.

If you are using Visual C#, in the Templates pane, click Application
Configuration File.

MCT USE ONLY. STUDENT USE PROHIBITED

L2-34

L2-35

5.

In Solution Explorer, in the AppointmentServiceSelfHost project, right-click


the app.config file (for Visual Basic) or the App.config file (for Visual C#), and
then click Edit WCF Configuration.

6.

In Microsoft Service Configuration Editor, in the left pane, right-click the


Services node, and then click New Service.

7.

In the right pane, in the Name box, type


com.contoso.AppointmentService.AppointmentServiceImplementation and
then press ENTER.

8.

In the left pane, expand the


com.contoso.AppointmentService.AppointmentServiceImplementation
folder under the Services folder, right-click the Endpoints folder, and then
click New Service Endpoint.

9.

In the right pane, define a new endpoint with the following information:

Name: APService_WsHTTP

Address: http://localhost:8002/Contoso/AppointmentService

Binding: wsHttpBinding

Contract:
com.contoso.AppointmentService.AppointmentServiceContract

10. On the File menu, click Save, and then close the Microsoft Service
Configuration Editor.
11. In the Microsoft Visual Studio dialog box, click Yes to All.

f Task 2: Remove the programmatic endpoint configuration from the


AppointmentServiceSelfHost project
1.

In Solution Explorer, in the AppointmentServiceSelfHost project, right-click


the Module1 class (for Visual Basic) or Program class (for Visual C#), and
then click View Code.

2.

In the Main method, make the following changes to the existing code:
a.

Remove the code that defines the baseAddress object.

b.

Remove the baseAddress parameter from the ServiceHost constructor.

c.

Remove the code that defines the contractType object and


relativeAddress string.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Configure and Host a WCF Service

Module 2: Configuring and Hosting WCF Services

d. Remove the line of code that adds a new service endpoint to the host
object.
Your code should resemble the following.
[Visual Basic]
...
Sub Main()
Dim instanceType As Type = _
GetType(com.contoso.AppointmentService. _
AppointmentServiceImplementation)
Dim host As New ServiceHost(instanceType)
Using host
host.Open()
Console.WriteLine("Appointment service " _
& "running. Press <ENTER> to quit.")
Console.ReadLine()
host.Close()
End Using
End Sub
...

[Visual C#]
...
static void Main(string[] args)
{
Type instanceType =
typeof(com.contoso.AppointmentService.
AppointmentServiceImplementation);
ServiceHost host = new ServiceHost(instanceType);
using (host)
{
host.Open();
Console.WriteLine("Appointment service " +
"running. Press <ENTER> to quit.");
Console.ReadLine();
host.Close();
}
}
...

MCT USE ONLY. STUDENT USE PROHIBITED

L2-36

L2-37

f Task 3: Remove the programmatic endpoint configuration from the


ClinicAdminClient project
1.

In Solution Explorer, in the ClinicAdminClient project, right-click the


app.config file (for Visual Basic) or App.config file (for Visual C#), and then
click Edit WCF Configuration.

2.

In the Microsoft Service Configuration Editor, in the left pane, expand Client,
right-click Endpoints, and then click New Client Endpoint.

3.

In the right pane, define a new client endpoint with the following information:

Name: APService_WsHTTP

Address: http://localhost:8002/Contoso/AppointmentService

Binding: wsHttpBinding

Contract: AppointmentServiceReference.AppointmentServiceContract

4.

On the File menu, click Save, and then close the Microsoft Service
Configuration Editor.

5.

In Solution Explorer, in the ClinicAdminClient project, right-click the


ClinicAdminForm class, and then click View Code.

6.

Locate the GetAppointmentServiceProxy method, and then do the following:


a.

Remove the existing method body code.

b.

Add code to return a new AppointmentServiceContractClient object.


[Visual Basic]
...
Private Function GetAppointmentServiceProxy() As _
AppointmentServiceContract
Return New AppointmentServiceContractClient()
End Function
...

[Visual C#]
...
private AppointmentServiceContract GetAppointmentServiceProxy()
{
return new AppointmentServiceContractClient();
}
...

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Configure and Host a WCF Service

Module 2: Configuring and Hosting WCF Services

f Task 4: Build and run the solution


1.

On the Build menu, click Build Solution.

2.

On the Debug menu, click Start Debugging.

3.

Wait for the Console window to display the following message:


Appointment service running. Press <ENTER> to quit.
In the Clinic Administration Client form, on the Create Appointment tab,
click Find Slots. You should see the list of available appointments.

4.

In Visual Studio 2008, on the Debug menu, click Stop Debugging.

Results: After this exercise, you should have defined the WCF configuration for the
AppontmentServiceSelfHost and ClinicAdminClient projects in external
configuration files.

MCT USE ONLY. STUDENT USE PROHIBITED

L2-38

L2-39

Exercise 4: Employing Different Hosting Options for a


Service
In this exercise, you will host the appointment service with WAS. To use WAS, you
will add additional endpoints to both the AppointmentServiceIISHost and the
ClinicAdminClient projects.
The main tasks for this exercise are as follows:
1.

Add a new Application directory to IIS.

2.

Add the net.tcp binding to the WAS configuration.

3.

Enable TCP support for the AppointmentServiceIISHost application.

4.

Configure a TCP endpoint for the AppointmentServiceIISHost application.

5.

Configure a TCP binding for the ClinicAdminClient application.

6.

Set the ConnectedWCF solution startup projects.

7.

Build and run the solution.

f Task 1: Add a new Application directory to IIS


1.

On the Start menu, click Control Panel.

2.

In the Control Panel window, click System Maintenance.

3.

In the Control Panel\System and Maintenance window, click Administrative


Tools.

4.

In the Administrative Tools window, click Internet Information Services (IIS)


Manager.

5.

In the User Account Control dialog box, click Continue.

6.

In the Internet Information Services (IIS) Manager window, in the left pane,
expand LON-DEV (LON-DEV\Student), and then expand Web Sites.

7.

Right-click Default Web Site, and then click Add Application.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Configure and Host a WCF Service

Module 2: Configuring and Hosting WCF Services

8.

9.

In the Add Application dialog box, add a new application with the following
details, and then click OK.

Alias: AppointmentServiceIISHost

Physical path: If you are using Visual Basic, go to


E:\Labfiles\Starter\VB\Ex4\ConnectedWCF\AppointmentServiceIISH
ost. If you are using Visual C#, go to
E:\Labfiles\Starter\CS\Ex4\ConnectedWCF\AppointmentServiceIISH
ost.

Close the Internet Information Services (IIS) Manager window.

f Task 2: Add the net.tcp binding to the WAS configuration


1.

In Windows Explorer, go to E:\Labfiles\Starter\, right-click the


AddTcpBindingToWas.cmd file, and then click Edit.

2.

Examine the command, and then close Notepad.

3.

Right-click the AddTcpBindingToWas.cmd file, and then click Run as


administrator.

4.

In the User Account Control dialog box, click Continue.

5.

In the Command Prompt window, ensure the command executed successfully,


and then press ENTER.

f Task 3: Enable TCP support for the AppointmentServiceIISHost


application
1.

In Windows Explorer, in the E:\Labfile\Starter\ folder, right-click the


AppointmentServiceIISHostTcpSupport.cmd file, and then click Edit.

2.

Examine the command, and then close Notepad.

3.

Right-click the AppointmentServiceIISHostTcpSupport.cmd file, and then


click Run as administrator.

4.

In the User Account Control dialog box, click Continue.

5.

In the Command Prompt window, ensure the command executed successfully,


and then press ENTER.

6.

Close Windows Explorer.

MCT USE ONLY. STUDENT USE PROHIBITED

L2-40

L2-41

f Task 4: Configure a TCP endpoint for the AppointmentServiceIISHost


application
1.

In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.

2.

In the Open Project dialog box, go to either of the following:

If you are using Visual Basic, go to the


E:\Labfiles\Starter\VB\Ex4\ConnectedWCF folder, and then doubleclick the ConnectedWCF.sln file.

If you are using Visual C#, go to the


E:\Labfiles\Starter\CS\Ex4\ConnectedWCF folder, and then doubleclick the ConnectedWCF.sln file.

3.

In Solution Explorer, in the AppointmentServiceIISHost project, right-click


the Web.config file, and then click Edit WCF Configuration.

4.

In the left pane, under Services, expand


com.contoso.AppointmentService.AppointmentServiceImplementation,
right-click Endpoints, and then click New Service Endpoint.

5.

In the right-pane, define a service endpoint with the following details:

6.

Name: APService_TCP

Address:
net.tcp://localhost:9090/AppointmentServiceIISHost/AppointmentSer
viceIISHost.svc

Binding: netTcpBinding

Contract:
com.contoso.AppointmentService.AppointmentServiceContract

On the File menu, click Save, and then close the WCF Configuration Editor.

f Task 5: Configure a TCP binding for the ClinicAdminClient application


1.

In Solution Explorer, in the ClinicAdminClient project, right-click the


app.config file (for Visual Basic) or App.config file (for Visual C#), and then
click Edit WCF Configuration.

2.

In the Microsoft Service Configuration Editor, in the left pane, under the
Client folder, right-click Endpoints, and then click New Client Endpoint.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Configure and Host a WCF Service

Module 2: Configuring and Hosting WCF Services

3.

In the right pane, define a new client endpoint with the following information:

Name: APService_TCP

Address:
net.tcp://localhost:9090/AppointmentServiceIISHost/AppointmentSer
viceIISHost.svc

Binding: netTcpBinding

Contract: AppointmentServiceReference.AppointmentServiceContract

4.

On the File menu, click Save, and then close the Microsoft Service
Configuration Editor.

5.

In Solution Explorer, right-click the ClinicAdminForm, and then click View


Code.

6.

In the Code Editor window, for the ClinicAdminForm class, locate the
GetAppointmentServiceProxy method, and then pass the string
APService_TCP to the AppointmentServiceContractClient constructor.
[Visual Basic]
...
Private Function GetAppointmentServiceProxy() As _
AppointmentServiceContract
Return New AppointmentServiceContractClient("APService_TCP")
End Function
...

[Visual C#]
...
private AppointmentServiceContract GetAppointmentServiceProxy()
{
return new AppointmentServiceContractClient("APService_TCP");
}
...

MCT USE ONLY. STUDENT USE PROHIBITED

L2-42

L2-43

f Task 6: Set the ConnectedWCF solution startup projects


1.

In the Solution Explorer window, right-click Solution 'ConnectedWCF', and


then click Set Startup Projects.

2.

In the Solution 'ConnectedWCF' Property Pages dialog box, click Single


startup project.

3.

In the Solution 'ConnectedWCF' Property Pages dialog box, click OK.

f Task 7: Build and run the solution


1.

On the Build menu, click Build Solution.

2.

On the Debug menu, click Start Debugging.

3.

In the Clinic Administration Client form, on the Create Appointment tab,


click Find Slots. You should see the list of available appointments.

4.

In Visual Studio 2008, on the Debug menu, click Stop Debugging.

Results: After this exercise, you should have hosted the appointment service in IIS
using WAS.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Configure and Host a WCF Service

L3-45

Module 3: Endpoints and Behaviors

Lab: Changing Service Endpoints


and Behaviors
Scenario
You are a developer on the Contoso, Ltd Clinic Management product team. Your
manager has asked you to look at exposing the Appointment service to both
Internet and intranet clients and to lock down security a little by removing the
metadata endpoint. You must also experiment with exposing a metadata endpoint,
and configuring the Patient Letter service to interoperate with an existing ASP.NET
legacy Web service.

Logon Information:

Virtual Machine: 6461-LON-DEV-03

User Name: Student

Password: Pa$$w0rd

Estimated time: 60 minutes

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Changing Service Endpoints and Behaviors

Module 3: Endpoints and Behaviors

Exercise 1: Exposing Services by Using Different Bindings


In this exercise, you will configure both a wsHttpBinding and a netTcpBinding
endpoint for the Appointment service. You will then manually generate a service
proxy class by using the Svcutil.exe tool. You will then add the necessary WCF
configuration to the ClinicAdminClient and FPAdminClient client applications.
The main tasks for this exercise are as follows:
1.

Start the 6461-LON-DEV-03 virtual machine and log on as Student.

2.

Open the existing ConnectedWCF solution.

3.

Add a netTcpBinding and a wsHttpBiniding endpoint to the Appointment


service.

4.

Generate a service proxy by using Svcutil.exe.

5.

Add the proxy to the FPAdminClient project and configure a wsHttpBinding


binding.

6.

Add the proxy to the ClinicAdminClient project and configure a


netTcpBinding binding.

7.

Set the ConnectedWCF solution startup projects.

8.

Build and run the solution.

f Task 1: Start the 6461-LON-DEV-03 virtual machine and log on as


Student
1.

Open the Virtual Server Remote Control Client and double-click 6461-LONDEV-03.

2.

Log on to 6461-LON-DEV-03 as Student using the password Pa$$w0rd.

f Task 2: Open the existing ConnectedWCF solution


1.

On the Start menu, click All Programs, click Microsoft Visual Studio 2008,
right-click Microsoft Visual Studio 2008, and then click Run as
administrator.

2.

In the User Account Control dialog box, click Continue.

3.

In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.

MCT USE ONLY. STUDENT USE PROHIBITED

L3-46

4.

L3-47

In the Open Project dialog box, go to either of the following:

If you are using Microsoft Visual Basic development system, go to the


E:\Labfiles\Starter\VB\Ex1\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

If you are using Microsoft Visual C# development tool, go to the


E:\Labfiles\Starter\CS\Ex1\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

f Task 3: Add a netTcpBinding and a wsHttpBiniding endpoint to the


Appointment service
1.

In the Solution Explorer window, in the AppointmentServiceSelfHost project,


right-click the App.config file, and then click Edit WCF Configuration.

2.

In the Microsoft Service Configuration Editor window, in the Configuration


pane, expand
com.contoso.AppointmentService.AppointmentServiceImplementation,
right-click Endpoints, and then click New Service Endpoint.

3.

In the Service Endpoint pane, define a service endpoint with the following
information:

Name: APService_TCP

Address: IntranetAppointmentService

Binding: netTcpBinding

Contract:
com.contoso.AppointmentService.AppointmentServiceContract

4.

In the Configuration pane, right-click Endpoints, and then click New Service
Endpoint.

5.

In the Service Endpoint pane, define a second service endpoint with the
following information:

Name: APService_wsHTTP

Address: InternetAppointmentService

Binding: wsHttpBinding

Contract:
com.contoso.AppointmentService.AppointmentServiceContract

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Changing Service Endpoints and Behaviors

Module 3: Endpoints and Behaviors

6.

In the Configuration pane, click Host.

7.

In the BaseAddresses section, click New.

8.

In the Base Address Editor dialog box, in the Base address box, type
http://localhost:8002/Contoso and then click OK.

9.

In the BaseAddresses section, click New.

10. In the Base Address Editor dialog box, in the Base address box, type
net.tcp://localhost/Contoso and then click OK.
11. In the Microsoft Service Configuration Editor window, on the File menu, click
Save.
12. Close the Microsoft Service Configuration Editor window.
13. In the Solution Explorer window, right-click the AppointmentServiceSelfHost
project, and then click Build.

f Task 4: Generate a service proxy by using Svcutil.exe


1.

In Windows Explorer, go to the E:\Labfiles\Starter\Proxy folder.

2.

If you are using Visual Basic, right-click GenerateVbProxy.cmd, and then click
Edit.
If you are using Visual C#, right-click GenerateCsProxy.cmd, and then click
Edit.

3.

Examine the command, and then close Notepad.

4.

If you are using Visual Basic, right-click GenerateVbProxy.cmd, and then click
Run as administrator.
If you are using Visual C#, right-click GenerateCsProxy.cmd, and then click
Run as administrator.

5.

In the User Account Control dialog box, click Continue.

6.

In the Command Prompt window, ensure that the command executed


successfully, and then press ENTER.

MCT USE ONLY. STUDENT USE PROHIBITED

L3-48

L3-49

f Task 5: Add the proxy to the FPAdminClient project and configure a


wsHttpBinding binding
1.

Switch to Visual Studio 2008.

2.

In the Solution Explorer window, right-click the FPAdminClient project, point


to Add, and then click Existing Item.

3.

In the Add Existing Item - FPAdminClient dialog box, go to the following file,
and then click Add:

4.

If you are using Visual Basic, go to E:\Labfiles\Starter\Proxy\


contoso.com.services.AppointmentService.vb.

If you are using Visual C#, go to E:\Labfiles\Starter\Proxy\


contoso.com.services.AppointmentService.cs.

In the Solution Explorer window, in the FPAdminClient project, right-click the


following file, and then click Edit WCF Configuration:

If you are using Visual Basic, right-click the app.config file.

If you are using Visual C#, right-click the App.config file.

5.

In the Microsoft Service Configuration Editor window, in the Configuration


pane, expand Client, right-click Endpoints, and then click New Client
Endpoint.

6.

In the Client Endpoint pane, define a new client endpoint with the following
information:

Name: APService_wsHTTP

Address: http://localhost:8002/Contoso/InternetAppointmentService

Binding: wsHttpBinding

Contract: AppointmentServiceContract

7.

In the Microsoft Service Configuration Editor window, on the File menu, click
Save.

8.

Close the Microsoft Service Configuration Editor window.

9.

In the Solution Explorer window, right-click the FPAdminClient project, and


then click Build.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Changing Service Endpoints and Behaviors

Module 3: Endpoints and Behaviors

f Task 6: Add the proxy to the ClinicAdminClient project and configure


a netTcpBinding binding
1.

In the Solution Explorer window, right-click the ClinicAdminClient project,


point to Add, and then click Existing Item.

2.

In the Add Existing Item - ClinicAdminClient dialog box, go to the following


file, and then click Add:

3.

If you are using Visual Basic, go to E:\Labfiles\Starter\Proxy\


contoso.com.services.AppointmentService.vb.

If you are using Visual C#, go to E:\Labfiles\Starter\Proxy\


contoso.com.services.AppointmentService.cs.

In the Solution Explorer window, in the ClinicAdminClient project, right-click


the following file, and then click Edit WCF Configuration:

If you are using Visual Basic, right-click the app.config file.

If you are using Visual C#, right-click the App.config file.

4.

In the Microsoft Service Configuration Editor window, in the Configuration


pane, expand Client, right-click Endpoints, and then click New Client
Endpoint.

5.

In the Client Endpoint pane, define a new client endpoint with the following
information:

Name: APService_TCP

Address: net.tcp://localhost/Contoso/IntranetAppointmentService

Binding: netTcpBinding

Contract: AppointmentServiceContract

6.

In the Microsoft Service Configuration Editor window, on the File menu, click
Save.

7.

Close the Microsoft Service Configuration Editor window.

8.

In the Solution Explorer window, right-click the ClinicAdminClient project,


and then click Build.

MCT USE ONLY. STUDENT USE PROHIBITED

L3-50

L3-51

f Task 7: Set the ConnectedWCF solution startup projects


1.

In the Solution Explorer window, right-click the ConnectedWCF solution, and


then click Set Startup Projects.

2.

In the Solution 'ConnectedWCF' Property Pages dialog box, click Multiple


startup projects.

3.

In the Multiple startup projects list, set the Action for the
AppointmentServiceSelfHost, ClinicAdminClient, and FPAdminClient
projects to Start. Set the Action for the remaining projects to None.

4.

In the Solution 'ConnectedWCF' Property Pages dialog box, click OK.

f Task 8: Build and run the solution


1.

On the Build menu, click Build Solution.

2.

On the Debug menu, click Start Debugging.

3.

In the Windows Security Alert dialog box, click Unblock.

4.

Wait for the Console window to display the message Appointment service
running.

5,

In the FP Admin Client form, on the Create Appointment tab, click Find
Slots.
Ensure that the Slots box is populated with a list of available appointment
times.

6,

In the Clinic Administration Client form, on the Create Appointment tab,


click Find Slots.
Ensure that the Slots box is populated with a list of available appointment
times.

7.

In Visual Studio 2008, on the Debug menu, click Stop Debugging.

Results: After this exercise, you should have exposed the Appointment service over
a netTcpBinding and wsHttpBinding endpoint.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Changing Service Endpoints and Behaviors

Module 3: Endpoints and Behaviors

Exercise 2: Adding Metadata Exchange to a Service


Scenario
In this exercise, you will add IMetadataExchange endpoints to the Appointment
service to expose metadata over both TCP and HTTP. You will then use the Add
Service Reference tool in Visual Studio 2008 to generate a proxy object from the
metadata.
The main tasks for this exercise are as follows:
1.

Add a mexHttpBinding endpoint and a mexTcpBinding endpoint to the


Appointment service.

2.

Set the ConnectedWCF solution startup projects.

3.

Add a service reference to the FPAdminClient project.

4.

Add a service reference to the ClinicAdminClient project.

5.

Set the ConnectedWCF solution startup projects.

6.

Build and run the solution.

f Task 1: Add a mexHttpBinding endpoint and a mexTcpBinding


endpoint to the Appointment service
1.

In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.

2.

In the Open Project dialog box, go to either of the following:

If you are using Visual Basic, go to the


E:\Labfiles\Starter\VB\Ex2\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

If you are using Visual C#, go to the


E:\Labfiles\Starter\CS\Ex2\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

3.

In the Solution Explorer window, in the AppointmentServiceSelfHost project,


right-click the App.config file, and then click Edit WCF Configuration.

4.

In the Microsoft Service Configuration Editor window, in the Configuration


pane, expand Advanced, right-click Service Behaviors, and then click New
Service Behavior Configuration.

MCT USE ONLY. STUDENT USE PROHIBITED

L3-52

5.

In the Behavior: NewBehavior pane, in the Name box, type


AppointmentServiceBehavior

6.

In the Behavior element extension position section, click Add.

7.

In the Adding Behavior Element Extension Sections dialog box, click


serviceMetadata, and then click Add.

8.

In the Configuration pane, under AppointmentServiceBehavior, click


serviceMetadata.

9.

In the serviceMetadata pane, set the HttpGetEnabled property to True.

L3-53

10. In the Configuration pane, under Services, click


com.contoso.AppointmentService.AppointmentServiceImplementation.
11. In the Service:
com.contoso.AppointmentService.AppointmentServiceImplementation
pane, set the BehaviorConfiguration property to
AppointmentServiceBehavior.
12. In the Configuration pane, expand
com.contoso.AppointmentService.AppointmentServiceImplementation,
right-click Endpoints, and then click New Service Endpoint.
13. In the Service Endpoint pane, define a service endpoint with the following
information:

Name: APService_mexHttp

Binding: mexHttpBinding

Contract: IMetadataExchange

14. In the Configuration pane, right-click Endpoints, and then click New Service
Endpoint.
15. In the Service Endpoint pane, define a service endpoint with the following
information:

Name: APService_mexTcp

Binding: mexTcpBinding

Contract: IMetadataExchange

16. In the Microsoft Service Configuration Editor window, on the File menu, click
Save.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Changing Service Endpoints and Behaviors

Module 3: Endpoints and Behaviors

17. Close the Microsoft Service Configuration Editor window.


18. In the Solution Explorer window, right-click the AppointmentServiceSelfHost
project, and then click Build.

f Task 2: Set the ConnectedWCF solution startup projects


1.

In the Solution Explorer window, right-click the ConnectedWCF solution, and


then click Set Startup Projects.

2.

In the Solution 'ConnectedWCF' Property Pages dialog box, click Single


startup project.

3.

In the Single startup project list, click AppointmentServiceSelfHost.

4.

In the Solution 'ConnectedWCF' Property Pages dialog box, click OK.

5.

On the Debug menu, click Start Without Debugging.

6.

In the Windows Security Alert dialog box, click Unblock.


Leave the AppointmentServiceSelfHost console running.

f Task 3: Add a service reference to the FPAdminClient project


1.

In the Solution Explorer window, in the FPAdminClient project, right-click the


following class, and then click Delete:

If you are using Visual Basic, right-click the


contoso.com.services.AppointmentService.vb class.

If you are using Visual C#, right-click the


contoso.com.services.AppointmentService.cs class.

2.

In the Microsoft Visual Studio dialog box, click OK.

3.

In the Solution Explorer window, in the FPAdminClient project, double-click


the following file:

If you are using Visual Basic, double-click the app.config file.

If you are using Visual C#, double-click the App.config file.

4.

In the Code Editor window, remove the system.serviceModel element.

5.

On the File menu, click Close.

MCT USE ONLY. STUDENT USE PROHIBITED

L3-54

L3-55

6.

In the Microsoft Visual Studio dialog box, click Yes.

7.

In the Solution Explorer window, right-click the FPAdminClient project, and


then click Add Service Reference.

8.

In the Add Service Reference dialog box, define a service reference with the
following information, and then click OK.

9.

Address: In the Address box, type http://localhost:8002/Contoso and


then click Go.

Namespace: In the Namespace box, type AppointmentServiceReference

In the Solution Explorer window, in the FPAdminClient project, right-click the


FPAdminForm class, and then click View Code.

10. In the Code Editor window for the FPAdminForm class, add code to bring the
FPAdminClient.AppointmentServiceReference namespace into scope.
[Visual Basic]
...
Imports FPAdminClient.AppointmentServiceReference
...

[Visual C#]
...
using FPAdminClient.AppointmentServiceReference;
...

11. Locate the GetAppointmentServiceProxy method, and then pass the string
APService_wsHTTP in the AppointmentServiceContractClient constructor.
[Visual Basic]
...
Private Function GetAppointmentServiceProxy() As _
AppointmentServiceContract
Return New AppointmentServiceContractClient("APService_wsHTTP")
End Function
...

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Changing Service Endpoints and Behaviors

Module 3: Endpoints and Behaviors

[Visual C#]
...
private AppointmentServiceContract GetAppointmentServiceProxy()
{
return new AppointmentServiceContractClient("APService_wsHTTP");
}
...

12. In the Solution Explorer window, right-click the FPAdminClient project, and
then click Build.

f Task 4: Add a service reference to the ClinicAdminClient project


1.

In the Solution Explorer window, in the ClinicAdminClient project, right-click


the following class, and then click Delete:

If you are using Visual Basic, right-click the


contoso.com.services.AppointmentService.vb class.

If you are using Visual C#, right-click the


contoso.com.services.AppointmentService.cs class.

2.

In the Microsoft Visual Studio dialog box, click OK.

3.

In the Solution Explorer window, in the ClinicAdminClient project, doubleclick the following file:

If you are using Visual Basic, double-click the app.config file.

If you are using Visual C#, double-click the App.config file.

4.

In the Code Editor window, remove the system.serviceModel element.

5.

On the File menu, click Close.

6.

In the Microsoft Visual Studio dialog box, click Yes.

7.

In the Solution Explorer window, right-click the ClinicAdminClient project,


and then click Add Service Reference.

MCT USE ONLY. STUDENT USE PROHIBITED

L3-56

8.

9.

L3-57

In the Add Service Reference dialog box, define a service reference with the
following information, and then click OK.

Address: In the Address box, type net.tcp://localhost/Contoso and then


click Go.

Namespace: In the Namespace box, type AppointmentServiceReference

In the Solution Explorer window, in the ClinicAdminClient project, right-click


the ClinicAdminForm class, and then click View Code.

10. In the Code Editor window for the ClinicAdminForm class, add code to bring
the ClinicAdminClient.AppointmentServiceReference namespace into scope.
[Visual Basic]
...
Imports ClinicAdminClient.AppointmentServiceReference
...

[Visual C#]
...
using ClinicAdminClient.AppointmentServiceReference;
...

11. Locate the GetAppointmentServiceProxy method, and then pass the string
APService_TCP in the AppointmentServiceContractClient constructor.
[Visual Basic]
...
Private Function GetAppointmentServiceProxy() As _
AppointmentServiceContract
Return New AppointmentServiceContractClient("APService_TCP")
End Function
...

[Visual C#]
...
private AppointmentServiceContract GetAppointmentServiceProxy()
{
return new AppointmentServiceContractClient("APService_TCP");
}
...

12. In the Solution Explorer window, right-click the ClinicAdminClient project,


and then click Build.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Changing Service Endpoints and Behaviors

Module 3: Endpoints and Behaviors

f Task 5: Set the ConnectedWCF solution startup projects


1.

In the Solution Explorer window, right-click the ConnectedWCF solution, and


then click Set Startup Projects.

2.

In the Solution 'ConnectedWCF' Property Pages dialog box, click Multiple


startup projects.

3.

In the Multiple startup projects list, set the Action for the
AppointmentServiceSelfHost, ClinicAdminClient, and FPAdminClient
projects to Start. Set the Action for the remaining projects to None.

4.

In the Solution 'ConnectedWCF' Property Pages dialog box, click OK.

f Task 6: Build and run the solution


1.

Switch to the AppointmentServiceSelfHost console, and close the console


window.

2.

On the Build menu, click Build Solution.

3.

On the Debug menu, click Start Debugging.

4.

In the Windows Security Alert dialog box, click Unblock.

5.

Wait for the Console window to display the message Appointment service
running.

6,

In the FP Admin Client form, on the Create Appointment tab, click Find
Slots.
Ensure that the Slots box is populated with a list of available appointment
times.

7,

In the Clinic Administration Client form, on the Create Appointment tab,


click Find Slots.
Ensure that the Slots box is populated with a list of available appointment
times.

8.

In Visual Studio 2008, on the Debug menu, click Stop Debugging.

Results: After this exercise, you should have exposed an IMetadataExchange


endpoint for netTcpBinding and wsHttpBinding, and then used the Add Service
Reference function in Visual Studio to generate a proxy object.

MCT USE ONLY. STUDENT USE PROHIBITED

L3-58

L3-59

Exercise 3: Creating WCF Clients and Services That


Interoperate with Non-WCF Web Services
Scenario
In this exercise, you will add the necessary code and WCF configuration to the
existing Patient Letter WCF service to interoperate with a legacy Web service.
The main tasks for this exercise are as follows:
1.

Host a legacy Web service in Internet Information Services (IIS).

2.

Create a proxy for the PatientLetterService project.

3.

Add the proxy to the PatientLetterService project.

4.

Configure a basicHttpBinding for the PatientLetterService project.

5.

Add code to call the methods in the PatientLetterService project.

6.

Build and run the solution.

f Task 1: Host a legacy Web service in IIS


1.

On the Start menu, click Control Panel.

2.

In the Control Panel window, click System and Maintenance.

3.

In the Control Panel\System and Maintenance window, click Administrative


Tools.

4.

In the Administrative Tools window, double-click Internet Information


Services (IIS) Manager.

5.

In the User Account Control dialog box, click Continue.

6.

In the Internet Information Services (IIS) Manager window, in the left pane,
expand LON-DEV (LON-DEV\Student), and then expand Web Sites.

7.

Right-click Default Web Site, and then click Add Application.

8.

In the Add Application dialog box, add a new application with the following
details, and then click OK.

9.

Alias: PatientInformationService

Physical path:
E:\Labfiles\Starter\LegacyWebServices\PatientInformationService

Close the Internet Information Services (IIS) Manager window.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Changing Service Endpoints and Behaviors

Module 3: Endpoints and Behaviors

10. On the Start menu, click Internet Explorer.


11. In the Address bar, type
http://localhost/PatientInformationService/Service.asmx and then press
ENTER.
If you have hosted the Web service correctly, you will see the default
PatientInformationService page.
12. In the Information Bar dialog box, click Close.
13. On the PatientInformationService page, click Service Description.
Windows Internet Explorer will now display the Web Services Description
Language (WSDL) document for the Web service.
14. In the Information Bar dialog box, click Close.
15. Close Internet Explorer.

f Task 2: Create a proxy for the PatientLetterService project


1.

In Windows Explorer, go to the E:\Labfiles\Starter\LegacyWebServices folder.

2.

Right-click the following file, and then click Edit:

If you are using Visual Basic, right-click the GenerateLegacyVbProxy.cmd


file.

If you are using Visual C#, right-click the GenerateLegacyCsProxy.cmd


file.

3.

Examine the command, and then close Notepad.

4.

Right-click the following file, and then click Run as administrator:

If you are using Visual Basic, right-click GenerateLegacyVbProxy.cmd.

If you are using Visual C#, right-click GenerateLegacyCsProxy.cmd.

5.

In the User Account Control dialog box, click Continue.

6.

In the Command Prompt window, ensure that the command executed


successfully, and then press ENTER.

MCT USE ONLY. STUDENT USE PROHIBITED

L3-60

L3-61

f Task 3: Add the proxy to the PatientLetterService project


1.

In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.

2.

In the Open Project dialog box, go to either of the following:

If you are using Visual Basic, go to the


E:\Labfiles\Starter\VB\Ex3\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

If you are using Visual C#, go to the


E:\Labfiles\Starter\CS\Ex3\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

3.

In the Solution Explorer window, right-click the PatientLetterService project,


point to Add, and then click Existing Item.

4.

In the Add Existing Item - PatientLetterService dialog box, go to the


following file, and then click Add.

If you are using Visual Basic, go to


E:\Labfiles\Starter\LegacyWebServices\LegacyPatientInformationService
Proxy.vb.

If you are using Visual C#, go to


E:\Labfiles\Starter\LegacyWebServices\LegacyPatientInformationService
Proxy.cs.

f Task 4: Configure a basicHttpBinding for the PatientLetterService


project
1.

In the Solution Explorer window, in the AppointmentServiceSelfHost project,


right-click the App.config file, and then click Edit WCF Configuration.

2.

In the Microsoft Service Configuration Editor window, in the Configuration


pane, expand Client, right-click Endpoints, and then click New Client
Endpoint.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Changing Service Endpoints and Behaviors

Module 3: Endpoints and Behaviors

3.

In the Client Endpoint pane, define a client endpoint with the following
information:

Name: PatientInformationServiceSoap

Address: http://localhost/PatientInformationService/Service.asmx

Binding: basicHttpBinding

Contract: PatientInformationServiceSoap

4.

In the Microsoft Service Configuration Editor window, on the File menu, click
Save.

5.

Close the Microsoft Service Configuration Editor window.

f Task 5: Add code to call the methods in the PatientLetterService


project
1.

In the Solution Explorer window, in the PatientLetterService project, right-click


the PatientLetterServiceImplementation class, and then click View Code.

2.

In the Code Editor window, locate the TODO 1 comment, and add code to
bring the contoso.com.ClinicManagementSystem._2004._07 namespace into
scope.
[Visual Basic]
...
'TODO 1
Imports contoso.com.ClinicManagementSystem._2004._07
...

[Visual C#]
...
//TODO 1
using contoso.com.ClinicManagementSystem._2004._07;
...

MCT USE ONLY. STUDENT USE PROHIBITED

L3-62

3.

L3-63

In the PopulateTemplate method, locate the TODO 2 comment, and add


code to do the following:

Create a new instance of the PatientInformationServiceSoapClient class


called patientInformationService. Pass the string
PatientInformationServiceSoap to the constructor.

Create a new instance of the PatientDetails class called details, and then
initialize it to the return value of the GetPatientDetails method in the
patientInformationService object. Pass the patientId variable as a
parameter in the method call.

[Visual Basic]
...
'TODO 2
Dim patientInformationService As New _
PatientInformationServiceSoapClient( _
"PatientInformationServiceSoap")
Dim patientDetails As PatientDetails = _
patientInformationService.GetPatientDetails(patientId)
...

[Visual C#]
...
//TODO 2
PatientInformationServiceSoapClient patientInformationService
= new PatientInformationServiceSoapClient(
"PatientInformationServiceSoap");
PatientDetails patientDetails =
patientInformationService.GetPatientDetails(patientId);
...

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Changing Service Endpoints and Behaviors

Module 3: Endpoints and Behaviors

f Task 6: Build and run the solution


1.

On the Build menu, click Build Solution.

2.

On the Debug menu, click Start Debugging.

3.

In the Windows Security Alert dialog box, click Unblock.

4.

Wait for the Console window to display the message Appointment service
and patient letter service running. Press <ENTER> to quit.

5,

In the Clinic Administration Client form, on the Create Appointment tab,


click Find Slots.

6.

In the Patient box, type NH991199Z and then click Create.

7.

In the Appointment Created dialog box, click OK.

8.

Switch to the AppointmentServiceSelfHost console window, and verify that the


Entered SendLetter and Exited SendLetter messages are displayed.

9.

Open Windows Explorer, and go to the E:\Labfiles\Starter\Letters folder.

10 In the Letters folder, double-click the NH991199Z.txt file.


The file contains a basic letter that provides details of the appointment.

Results: After this exercise, you should have added the necessary code and WCF
configuration to the Patient Letter WCF service to interoperate with a legacy .asmx
Web service.

MCT USE ONLY. STUDENT USE PROHIBITED

L3-64

L4-65

Module 4: Debugging and Diagnostics

Lab: Message Logging and Activity


Tracing
Scenario
You are a developer on the Contoso Clinic Management product team. You have
been involved in the development of the appointment service and your manager
has now asked you to add additional configuration to the service to log messages
sent to and from the clients and to monitor the activities the clients and service
performs.

Logon Information:

Virtual Machine: 6461A-LON-DEV-04

User Name: Student

Password: Pa$$w0rd

Estimated time: 40 minutes

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Message Logging and Activity Tracing

Module 4: Debugging and Diagnostics

Exercise 1: Generating Logging Information for a Service


In this exercise, you will configure the AppointmentService, the
PatientManagementService, and the ClinicAdminClient to log messages. You will
then analyze these messages by using the Microsoft Service Trace Viewer tool.
The main tasks for this exercise are as follows:
1.

Start the 6461-LON-DEV-04 virtual machine and log on as Student.

2.

Open the existing WCFConnected solution.

3.

Enable message logging for the AppointmentService and the


PatientManagementService.

4.

Enable message logging for the ClinicAdminClient.

5.

Build and run the solution.

6.

View the message logs.

f Task 1: Start the 6461-LON-DEV-04 virtual machine and log on as


Student
1.

Open the Virtual Server Remote Control Client and double-click 6461-LONDEV-04.

2.

Log on to 6461-LON-DEV-04 as Student using the password Pa$$w0rd.

f Task 2: Open the existing WCFConnected solution


1.

On the Start menu, point to All Programs, point to Microsoft Visual Studio
2008, right-click Microsoft Visual Studio 2008, and then click Run as
administrator.

2.

In the User Account Control dialog box, click Continue.

3.

In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.

MCT USE ONLY. STUDENT USE PROHIBITED

L4-66

4.

L4-67

In the Open Project dialog box, go either of the following:

If you are using Microsoft Visual Basic development system, go to the


E:\Labfiles\Starter\VB\Ex1\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

If you are using Microsoft Visual C# development tool, go to the


E:\Labfiles\Starter\CS\Ex1\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

f Task 3: Enable message logging for the AppointmentService and the


PatientManagementService
1.

In Solution Explorer, within the ServiceSelfHost project, right-click the


app.config file (for Visual Basic) or the App.config file (for Visual C#), and
then click Edit WCF Configuration.

2.

In the Microsoft Service Configuration Editor window, in the Configuration


pane, click Diagnostics.

3.

In the Diagnostics pane, do the following:

Click Enable Log Auto Flush.

Click Enable MessageLogging.

Click ServiceModelMessageLoggingListener.

4.

In the Listener Settings dialog box, in the Log file box, type
E:\Labfiles\Starter\Logs\service_messages.svclog and then click OK.

5.

In the Configuration pane, expand Diagnostics, and then click Message


Logging.

6.

In the Message Logging pane, do the following:

Set LogEntireMessage to True.

Set LogMessagesAtServiceLevel to True.

7.

In the Configuration pane, expand Sources, and then click


System.ServiceModel.MessageLogging.

8.

In the Trace Source: System.ServiceModel.MessageLogging pane, in the


Trace level list, click Information.

9.

In the Microsoft Service Configuration Editor window, on the File menu, click
Save.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Message Logging and Activity Tracing

Module 4: Debugging and Diagnostics

10. Close the Microsoft Service Configuration Editor window.

f Task 4: Enable message logging for the ClinicAdminClient


1.

In Solution Explorer, within the ClinicAdminClient project, right-click the


app.config file (for Visual Basic) or the App.config file (for Visual C#), and
then click Edit WCF Configuration.

2.

In the Microsoft Service Configuration Editor window, in the Configuration


pane, click Diagnostics.

3.

In the Diagnostics pane, do the following:

Click Enable Log Auto Flush.

Click Enable MessageLogging.

Click ServiceModelMessageLoggingListener.

4.

In the Listener Settings dialog box, in the Log file box, type
E:\Labfiles\Starter\Logs\client_messages.svclog and then click OK.

5.

In the Configuration pane, expand Diagnostics, and then click Message


Logging.

6.

In the Message Logging pane, do the following:

Set LogEntireMessage to True.

Set LogMessagesAtServiceLevel to True.

7.

In the Configuration pane, expand Sources, and then click


System.ServiceModel.MessageLogging.

8.

In the Trace Source: System.ServiceModel.MessageLogging pane, in the


Trace level list, click Information.

9.

In the Microsoft Service Configuration Editor window, on the File menu, click
Save.

10. Close the Microsoft Service Configuration Editor window.

f Task 5: Build and run the solution


1.

On the Build menu, click Build Solution.

2.

On the Debug menu, click Start Debugging.

3.

If the Windows Security Alert dialog box appears, click Unblock.

MCT USE ONLY. STUDENT USE PROHIBITED

L4-68

L4-69

4.

Wait for the Console window to display the message Service running.

5,

In the Clinic Administration Client form, on the Create Appointment tab,


click Find Slots.
Ensure the Slots box is populated with a list of available appointment times.

6.

In Visual Studio 2008, on the Debug menu, click Stop Debugging.

f Task 6: View the message logs


1.

On the Start menu, point to All Programs, point to Microsoft Windows SDK
v6.0A, point to Tools, and then click Service Trace Viewer.

2.

In the Microsoft Service Trace Viewer, on the File menu, click Open.

3.

In the Open dialog box, go to E:\Labfiles\Starter\Logs, select both the


client_messages.svclog and service_messages.svclog files, and then click
Open.

4.

In the Activity pane, click the 000000000000 entry.

5.

In the Description column, click the first message, and then click the Message
tab.
The first message is a client request message at the service level, which
contains the parameters for the ListAvailableAppointmentTimes method call.
The second message is the equivalent transport level message on the client
which is addressed to the
http://localhost:8002/Contoso/AppointmentService endpoint.

6.

In the Description column, click the fifth message.


The fifth message is the service's response to the
ListAvailableAppointmentTimes method call and includes the available
appointment times as the return value.
The sixth message is the equivalent response message at the transport level.

On the File menu, click Close All.

Results: After this exercise, you should have enabled message logging for the
AppointmentService, PatientManagementService, and the ClinicAdminClient
application.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Message Logging and Activity Tracing

Module 4: Debugging and Diagnostics

Exercise 2: Enabling End-to-End Tracing for a Service


In this exercise, you will configure the AppointmentService, the
PatientManagementService, and the ClinicAdminClient to log information on
the various activities that they perform when the ConnectedWCF solution runs.
You will then analyze the trace logs by using the Microsoft Service Trace Viewer
tool.
The main tasks for this exercise are as follows:
1.

Open the existing WCFConnected solution.

2.

Enable tracing for the AppointmentService and the


PatientManagementService.

3.

Enable tracing for the ClinicAdminClient.

4.

Build and run the solution.

5.

View the trace logs.

f Task 1: Open the existing WCFConnected solution


1.

In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.

2.

In the Open Project dialog box, go to either of the following:

If you are using Visual Basic, go to the


E:\Labfiles\Starter\VB\Ex2\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

If you are using Visual C#, go to the


E:\Labfiles\Starter\CS\Ex2\ConnectedWCF folder, and then double-click
the ConnectedWCF.sln file.

f Task 2: Enable tracing for the AppointmentService and the


PatientManagementService
1.

In Solution Explorer, within the ServiceSelfHost project, right-click the


app.config file (for Visual Basic) or the App.config file (for Visual C#), and
then click Edit WCF Configuration.

2.

In the Microsoft Service Configuration Editor window, in the Configuration


pane, click Diagnostics.

MCT USE ONLY. STUDENT USE PROHIBITED

L4-70

3.

L4-71

In the Diagnostics pane, do the following:

Click Enable Log Auto Flush.

Click Enable Tracing.

Click ServiceModelTraceListener.

4.

In the Listener Settings dialog box, in the Log file box, type
E:\Labfiles\Starter\Logs\service_tracelog.svclog and then click OK.

5.

In the Configuration pane, expand Diagnostics, expand Sources, and then


click System.ServiceModel.

6.

In the Trace Source: System.ServiceModel pane, in the Trace level list, click
Information.

7.

In the Microsoft Service Configuration Editor window, on the File menu, click
Save.

8.

Close the Microsoft Service Configuration Editor window.

f Task 3: Enable tracing for the ClinicAdminClient


1.

In Solution Explorer, within the CinicAdminClient project, right-click the


app.config file (for Visual Basic) or the App.config file (for Visual C#), and
then click Edit WCF Configuration.

2.

In the Microsoft Service Configuration Editor window, in the Configuration


pane, click Diagnostics.

3.

In the Diagnostics pane, do the following:

Click Enable Log Auto Flush.

Click Enable Tracing.

Click ServiceModelTraceListener.

4.

In the Listener Settings dialog box, in the Log file box, type
E:\Labfiles\Starter\Logs\client_tracelog.svclog and then click OK.

5.

In the Configuration pane, expand Diagnostics, expand Sources, and then


click System.ServiceModel.

6.

In the Trace Source: System.ServiceModel pane, in the Trace level list, click
Information.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Message Logging and Activity Tracing

Module 4: Debugging and Diagnostics

7.

In the Microsoft Service Configuration Editor window, on the File menu, click
Save.

8.

Close the Microsoft Service Configuration Editor window.

f Task 4: Build and run the solution


1.

On the Build menu, click Build Solution.

2.

On the Debug menu, click Start Debugging.

3.

If the Windows Security Alert dialog box appears, click Unblock.

4.

Wait for the Console window to display the message Service running.

5,

In the Clinic Administration Client form, on the Create Appointment tab,


click Find Slots.
Ensure the Slots box is populated with a list of available appointment times.

6.

In the Patient box, type NH991199Z and then click Create. Make a note of
the appointment ID.

7.

In the Appointment Created dialog box, click OK.

8.

On the Cancel Appointment tab, in the Patient No box, type NH991199Z


and then click Get Details.

9.

The Appt ID box, type your appointment ID, and then click Delete.

10. In the Appointment Cancellation box, click OK.


11. In Microsoft Visual Studio 2008 development system, on the Debug menu,
click Stop Debugging.

f Task 5: View the trace logs


1.

Switch to the Microsoft Service Trace Viewer.

2.

In the Microsoft Service Trace Viewer, on the File menu, click Open.

3.

In the Open dialog box, go to E:\Labfiles\Starter\Logs, select both the


client_tracelog.svclog and service_tracelog.svclog files, and then click Open.
The activity pane contains a chronological list of activities associated with
creating the AppointmentService, the PatientManagementService, and the
ClinicAdminClient, and the calling of the methods.

MCT USE ONLY. STUDENT USE PROHIBITED

L4-72

4.

L4-73

In the Activity pane, click the Construct ServiceHost


'com.contoso.AppointmentService.AppointmentServiceImplementation'
activity.
This activity represents the service host building an instance of the
AppointmentService. The right pane contains the details of the activity, such
as the activity name, trace level, process name, and thread ID.
The next activity represents the similar process of building an instance of the
PatientManagementService.

5.

In the Activity pane, click the Construct ChannelFactory. Contract types:


'ClinicAdminClient.AppointmentServiceReference.AppointmentServiceCon
tract' activity.
This activity represents the building of the channel stack for the
ClinicAdminClient.

6.

In the Activity pane, click the Execute


'com.contoso.AppointmentService.AppointmentServiceContract.ListAvaila
bleAppointmentTimes' activity.
This activity represents the process of invoking the
ListAvailableAppointmentTimes method.

7.

In the Activity pane, examine some of the other activities.

8.

In the Activity pane, click the 000000000000 activity.

9.

In the left pane, click the Graph tab.


The graph view enables you to view the correlation between the different
activities.
The ServiceSelfHost column contains the activities associated with building
the AppointmentService, the PatientManagementService instances, and
starting listening for requests over the configured endpoints.
The ClinicAdminClient column contains activities associated with the
following processes:
a.

Building the channel stack for the client to communicate with the
AppointmentService

b.

Opening the client for the AppointmentServiceContract

c.

Calling the ListAvailableAppointmentTimes method in the


AppointmentService

d. Opening the client for the AppointmentServiceContract

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Message Logging and Activity Tracing

Module 4: Debugging and Diagnostics

e.

Calling the CreateAppointment method in the AppointmentService

f.

Building the channel stack for the client to communicate with the
PatientManagementService

g.

Opening the client for the PatientManagementServiceContract

h.

Calling the GetPatientDetails method in the PatientManagementService

i.

Opening the client for the AppointmentServiceContract

j.

Calling the CancelAppointment method in the AppointmentService

10. On the File menu, click Close All.

Results: After this exercise, you should have enabled tracing for the
AppointmentService, PatientManagementService, and the ClinicAdminClient
application.

MCT USE ONLY. STUDENT USE PROHIBITED

L4-74

Module 5: Designing and Defining Contracts

Lab: Contracts for Services and


Data
Logon Information:

Virtual Machine: 6461A-LON-DEV-05

User Name: Student

Password: Pa$$w0rd

Estimated time: 60 minutes

L5-75

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 5: Designing and Defining Contracts

Exercise 1: Defining and implementing a one-way


operation contract
Scenario
Initial user feedback for a preliminary version of the Contoso Clinic Management
System has highlighted that it takes longer than the user would like to create an
appointment. An analysis of the appointment creation process has identified that a
significant percentage of the time is spent waiting for the system to generate the
patient letter. This needs to be speeded up to reach the desired level of system
performance.
In this exercise, you will add code to make the letter sending operation one-way
and so decouple it from the client thread of execution. This will improve the
perceived response time of the system.
The main tasks for this exercise are as follows:
1.

Start the 6461-LON-DEV-05 virtual machine and log on as Student.

2.

Add a call from the clinic admin client to the patient letter service.

3.

Add a delay and diagnostic output to the patient letter service.

4.

Verify the letter creation and notification.

5.

Change the patient letter contract to be one-way.

6.

Verify the decoupling of client and service.

f Task 1: Start the 6461-LON-DEV-06 virtual machine and log on as


Student
1.

Open the Virtual Server Remote Control Client and double-click 6461-LONDEV-05.

2.

Log on to 6461-LON-DEV-05 as Student using the password Pa$$w0rd.

MCT USE ONLY. STUDENT USE PROHIBITED

L5-76

L5-77

f Task 2: Add a call from the clinic admin client to the patient letter
service
1.

On the Start menu, point to All Programs, click Microsoft Visual Studio
2008, right-click Microsoft Visual Studio 2008, and then click Run as
administrator

2.

In the User Account Control dialog box, click Continue.

3.

On the File menu, point to Open, and then click Project/Solution.

If you are using Microsoft Visual Basic development system in the Open
Project dialog box, go to the folder
E:\Labfiles\Starter\VB\OneWay\ConnectedWCF and then double-click
ConnectedWCF.sln.

If you are using Microsoft Visual C# development tool, in the Open


Project dialog box, go to the folder
E:\Labfiles\Starter\CS\OneWay\ConnectedWCF and then double-click
ConnectedWCF.sln.

4.

In Solution Explorer, expand the ClinicAdminClient project, right-click the


ClinicAdminForm file, and then click View Code.

5.

Locate the TODO 1 comment in the MakeAppointment method and add the
following code to create a PatientLetterServiceContractClient proxy with the
client endpoint name PLService_TCP.
[Visual C#]
// TODO 1
PatientLetterServiceContract letterProxy =
new
PatientLetterServiceContractClient("PLService_TCP");
letterProxy.SendLetter(LetterType.ConsultationBooked,
patientId,
doctorId,
slot);

[Visual Basic]
' TODO 1
Dim letterProxy As PatientLetterServiceContract = _
New PatientLetterServiceContractClient("PLService_TCP")
letterProxy.SendLetter(LetterType.ConsultationBooked, patientId, _
doctorId, slot)

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 5: Designing and Defining Contracts

f Task 3: Add a delay and diagnostic output to the patient letter service
1.

In Solution Explorer, expand the PatientLetterService project, right-click the


PatientLetterServiceImplementation file, and then click View Code.

2.

Locate the TODO 2 comment in the SendLetter method and replace the three
lines of code in the try block with the following statements.
[Visual C#]
// TODO 2
Console.WriteLine("{0}: Entered SendLetter",
DateTime.Now.ToLongTimeString());
string template = GetLetterTemplate(type);
string letterToSend = PopulateTemplate(template,
patientId,
doctorId,
date);
SendTheLetter(letterToSend, patientId);
Thread.Sleep(5000);
Console.WriteLine("{0}: Exited SendLetter",
DateTime.Now.ToLongTimeString());

[Visual Basic]
' TODO 2
Console.WriteLine("{0}: Entered SendLetter", _
DateTime.Now.ToLongTimeString())
Dim template As String = GetLetterTemplate(type)
Dim letterToSend As String = PopulateTemplate(template, patientId,
_
doctorId,
[date])
SendTheLetter(letterToSend, patientId)
Thread.Sleep(5000)
Console.WriteLine("{0}: Exited SendLetter", _
DateTime.Now.ToLongTimeString()

MCT USE ONLY. STUDENT USE PROHIBITED

L5-78

L5-79

f Task 4: Verify the letter creation and notification


1.

On the Debug menu, click Start Debugging.

2.

In the Windows Security Alert dialog box, click Unblock.

3.

Position the Contoso services console window and the Clinic Administration
Client window so that you can see both windows.

4.

In the Clinic Administration Client form, click the Create Appointment tab.
Enter the following data, and then click Create:

Doctor: Gastro_Jones

Date:

Today's date

Slot:

Click Find Slots (this selects the first slot shown)

Patient: NH991199Z

5.

Verify that both of the messages from the SendLetter method appear before
you see the Clinic Admin: Appointment Created window.

6.

In the Clinic Admin: Appointment Created window, make a note of the


appointment time, and then click OK.

7.

On the Debug menu, click Stop Debugging.

8.

On the Start menu, point to All Programs, point to Accessories, and then
click Windows Explorer.

9.

In Windows Explorer, move to the folder E:\Labfiles\letters, right-click the


file NH991199Z.txt, and then click Open to open the file in Notepad.

10. Verify that the appointment time in the letter is the one you selected.
11. Close Notepad.

f Task 5: Change the patient letter contract to be one-way


1.

Switch to Microsoft Visual Studio 2008 development system.

2.

In Solution Explorer, expand the PatientLetterService project, right-click the


PatientLetterServiceContract file, and then click View Code.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 5: Designing and Defining Contracts

3.

Locate the TODO 3 comment and change the OperationContract attribute of


the SendLetter operation to identify it as a one-way operation.
[Visual C#]
// TODO 3
[OperationContract(IsOneWay=true)]
void SendLetter(LetterType type, string patientId, string doctorId,
DateTime date);

[Visual Basic]
' TODO 3
<OperationContract(IsOneWay:=True)> _
Sub SendLetter(ByVal type As LetterType, ByVal patientId As String,
_
ByVal doctorId As String, ByVal [date] As
DateTime)

4.

In Solution Explorer, right-click the ConnectedWCF solution, and then click


Rebuild Solution.

5.

Switch to Windows Explorer, and then go to the following folder:

If you are using Visual Basic, go to the folder


E:\Labfiles\Starter\VB\OneWay\ConnectedWCF\ContosoServicesSelf
HostExtConfig\bin\Debug.

If you are using Visual C#, go to the folder


E:\Labfiles\Starter\CS\OneWay\ConnectedWCF\ContosoServicesSelf
HostExtConfig\bin\Debug.

6.

Right-click the file ContosoServicesSelfHostExtConfig.exe, and then click


Run as administrator.

7.

In the User Account Control dialog box, click Allow.

8.

In the Windows Security Alert dialog box, click Unblock.

9.

Switch to Visual Studio 2008.

10. In Solution Explorer, expand the ClinicAdminClient project, expand the


Service References folder, right-click PatientLetterServiceReference, and then
click Update Service Reference.
11. Switch to the ContosoServicesSelfHostExtConfig console window and press
ENTER to close the service host.

MCT USE ONLY. STUDENT USE PROHIBITED

L5-80

L5-81

f Task 6: Verify the decoupling of client and service


1.

Switch to Visual Studio 2008.

2.

On the Debug menu, click Start Debugging.

3.

Position the Contoso services console window and the Clinic Administration
Client window so that you can see both windows.

4.

In the Clinic Administration Client form, click the Create Appointment tab.
Enter the following data, and then click Create:

Doctor: Gastro_Jones

Date:

Today's date

Slot:

Click Find Slots (this selects the first slot shown)

Patient: NH991199Z

5.

Verify that the Clinic Admin Appointment Created window appears before
you see the both of the messages from the SendLetter method. This
demonstrates that the execution of the operation in the service is now
decoupled from the client.

6.

In the Clinic Admin Appointment Created window, make a note of the


appointment time, and then click OK.

7.

On the Debug menu, click Stop Debugging.

8.

Switch to Windows Explorer.

9.

In Windows Explorer, go to the folder E:\Labfiles\letters, right-click the file


NH991199Z.txt, and then click Open to open the file in Notepad.

10. Verify that the appointment time in the letter is the one you selected.
11. Close Notepad.

Results: After completing this exercise, you have seen how to turn a
request/response service operation into a one-way operation.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 5: Designing and Defining Contracts

Exercise 2: Passing complex data with a data contract


Scenario
As part of the Clinic Administration Client application, you need to list today's
appointments including information about the patient, doctor, and time. To do
this, you need to retrieve a set of data for today's appointments. To keep the
appointment service decoupled from its underlying technology, you have decided
to pass this data as a collection of complex types that maps to the Web Service
Description Language (WDSL) service definition.
In this exercise, you will define a data contract for a .NET Framework class that
represents an appointment. You will then pass a collection of these classes back
from the appointment service to the client.
The main tasks for this exercise are as follows:
1.

Add a data contract to the Appointment class.

2.

Use the Appointment class as a return value in the appointment service


contract.

3.

Call the appointment service to list Appointments.

4.

Run the client to verify the appointment listing.

f Task 1: Add a data contract to the Appointment class


1.

Switch to Microsoft Visual Studio 2008.

2.

On the File menu, point to Open, and then click Project/Solution.

3.

If you are using Visual Basic, in the Open Project dialog box, go to the
folder E:\Labfiles\Starter\VB\ComplexData\ConnectedWCF, and then
double-click ConnectedWCF.sln.

If you are using Visual C#, in the Open Project dialog box, go to the
folder E:\Labfiles\Starter\CS\ComplexData\ConnectedWCF, and then
double-click ConnectedWCF.sln.

In Solution Explorer, expand the AppointmentService project, right-click the


Appointment file, and then click View Code.

MCT USE ONLY. STUDENT USE PROHIBITED

L5-82

4.

L5-83

Locate the TODO 4 comment, and then add the following DataContract
attribute to the Appointment class.
[Visual C#]
// TODO 4
[DataContract(Namespace =
"http://contoso.com/ClinicManagementSystem/2007/10")]
public class Appointment

[Visual Basic]
'TODO 4
<DataContract([Namespace]:="http://contoso.com/ClinicManagementSyst
em/2007/10")> _
Public Class Appointment

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 5: Designing and Defining Contracts

5.

Add a DataMember attribute to the Id, DoctorId, PatientId, and Time


properties of the Appointment class, as shown in the following code.
[Visual C#]
[DataMember]
public string Id
{
get
{
return id;
}
set
{
id = value;
}
}
[DataMember]
public string PatientId
{
get
{
return patientId;
}
set
{
patientId = value;
}
}
[DataMember]
public string DoctorId
{
get
{
return doctorId;
}
set
{
doctorId = value;
}
}

MCT USE ONLY. STUDENT USE PROHIBITED

L5-84

(Code continued)
[DataMember]
public DateTime Time
{
get
{
return time;
}
set
{
time = value;
}
}

[Visual Basic]
<DataMember()> _
Public Property Id() As String
Get
Return m_id
End Get
Set(ByVal value As String)
m_id = value
End Set
End Property
<DataMember()> _
Public Property PatientId() As String
Get
Return m_patientId
End Get
Set(ByVal value As String)
m_patientId = value
End Set
End Property
<DataMember()> _
Public Property DoctorId() As String
Get
Return m_doctorId
End Get
Set(ByVal value As String)
m_doctorId = value
End Set
End Property

L5-85

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 5: Designing and Defining Contracts

(Code continued)
<DataMember()> _
Public Property Time() As DateTime
Get
Return m_time
End Get
Set(ByVal value As DateTime)
m_time = value
End Set
End Property

f Task 2: Use the Appointment class as a return value in the


appointment service contract
1.

In Solution Explorer, expand the AppointmentService project, right-click the


AppointmentServiceContract file, and then click View Code.

2.

Locate the TODO 5 comment, and then add the following operation to the
AppointmentServiceContract interface.
[Visual C#]
// TODO 5
[OperationContract]
List<Appointment> ListTodaysAppointments();

[Visual Basic]
'TODO 5
<OperationContract()> _
Function ListTodaysAppointments() As List(Of Appointment)

3.

In Solution Explorer, right-click the AppointmentServiceImplementation file,


and then click View Code.

MCT USE ONLY. STUDENT USE PROHIBITED

L5-86

4.

L5-87

Locate the TODO 6 comment at the end of the


AppointmentServiceImplementation class. and then add the following
method.
[Visual C#]
// TODO 6
public List<Appointment> ListTodaysAppointments()
{
return new AppointmentHelper().ListTodaysAppointments();
}

[Visual Basic]
'TODO 6
Public Function ListTodaysAppointments() As List(Of Appointment)
Implements AppointmentServiceContract.ListTodaysAppointments
Dim helper As New AppointmentHelperClass()
Return helper.ListTodaysAppointments()
End Function

5.

In Solution Explorer, right-click the ConnectedWCF solution, and then click


Rebuild Solution.

f Task 3: Call the appointment service to list Appointments


1.

Switch to Windows Explorer, and then go to the following folder:

If you are using Visual Basic, go to the folder


E:\Labfiles\Starter\VB\ComplexData\ConnectedWCF\ContosoServic
esSelfHostExtConfig\bin\Debug.

If you are using Visual C#, go to the folder


E:\Labfiles\Starter\CS\ComplexData\ConnectedWCF\ContosoService
sSelfHostExtConfig\bin\Debug.

2.

Right-click the file ContosoServicesSelfHostExtConfig.exe, and then click


Run as administrator.

3.

In the User Account Control dialog box, click Allow.

4.

In the Windows Security Alert dialog box, click Unblock.

5.

Switch to Visual Studio 2008.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 5: Designing and Defining Contracts

6.

In Solution Explorer, expand the ClinicAdminClient project, expand the


Service References folder, right-click AppointmentServiceReference, and
then click Update Service Reference.

7.

Switch to the ContosoServicesSelfHostExtConfig console window and press


ENTER to close the service host.

8.

Switch to Visual Studio 2008.

9.

In Solution Explorer, right-click the ClinicAdminForm file, and then click


View Code.

10. Locate the TODO 7 comment in the RefreshAppointmentList_Click method,


and then add the following code.
[Visual C#]
// TODO 7
AppointmentServiceContract proxy = GetAppointmentServiceProxy();
appointmentsToday.DataSource = proxy.ListTodaysAppointments();

[Visual Basic]
'TODO 7
Dim proxy As AppointmentServiceContract =
GetAppointmentServiceProxy()
appointmentsToday.DataSource = proxy.ListTodaysAppointments()

f Task 4: Run the client to verify the appointment listing


1.

On the Debug menu, click Start Debugging.

2.

In the Windows Security Alert dialog box, click Unblock.

3.

In the Clinic Administration Client form, click the Create Appointment tab.
Enter the following data and click Create:

Doctor: Gastro_Jones

Date:

Today's date

Slot:

Click Find Slots (this selects the first slot shown)

Patient: NH991199Z

MCT USE ONLY. STUDENT USE PROHIBITED

L5-88

L5-89

4.

In the Clinic Admin Appointment Created window, click OK.

5.

Click the Today's Appointments tab, and then click Refresh.

6.

Verify that you see at least one appointment listed with an ID, doctor ID,
patient ID, and time. If you created appointments in the previous exercise, you
should see multiple appointments.

7.

On the Debug menu, click Stop Debugging.

Results: After completing this exercise, you have defined a data contract and used
this to pass complex type data between a Windows Communication Foundation
(WCF) service and a client.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 5: Designing and Defining Contracts

Exercise 3: Defining and implementing a callback contract


Scenario
One of the requirements of the Contoso Clinic Management System is that the
clinic administrators are informed when a consultant is ready to see their next
patient. To achieve this, you have decided to implement a callback contract
between the two client applications, the clinic admin client and the consultant
client. The clinic admin client application will receive a callback message when the
consultant client application tells the system that the consultant is ready for the
next patient.
In this exercise, you will add code to enable the clinic admin client application to
register for callbacks with the clinic management service. You will then add code to
the consultant client application to notify the clinic management service that it is
ready for the next patient and add code the clinic management service to
propagate any notifications to any registered clinic management clients.
The main tasks for this exercise are as follows:
1.

Define a callback contract.

2.

Add the callback contract to a service contract.

3.

Enable clients to register for callbacks with the service.

4.

Implement the callback contract in the clinic admin client and register with the
service.

5.

Implement the triggering method.

6.

Call the triggering method from the consultant client.

7.

Verify that callbacks are delivered to the clinic admin client.

f Task 1: Define a callback contract


1.

Switch to Microsoft Visual Studio 2008.

2.

On the File menu, point to Open, and then click Project/Solution.

If you are using Visual Basic, in the Open Project dialog box, go to the
folder E:\Labfiles\Starter\VB\Callback\ConnectedWCF, and then
double-click ConnectedWCF.sln.

If you are using Visual C#, in the Open Project dialog box, go to the
folder E:\Labfiles\Starter\CS\Callback\ConnectedWCF, and then
double-click ConnectedWCF.sln.

MCT USE ONLY. STUDENT USE PROHIBITED

L5-90

3.

In Solution Explorer, expand the ClinicManagementService project, rightclick the ClinicManagementServiceCallbackContract file, and then click
View Code.

4.

Locate the TODO 8 comment and add the following service contract.

L5-91

[Visual C#]
// TODO 8
[ServiceContract(Namespace =
"http://contoso.com/ClinicManagementSystem/2007/10")]
public interface ClinicManagementServiceCallbackContract
{
[OperationContract(IsOneWay=true)]
void NextPatientDueInToSeeConsultant(string doctorId);
}

[Visual Basic]
' TODO 8
<ServiceContract([Namespace]:="http://contoso.com/ClinicManagementS
ystem/2007/10")> _
Public Interface ClinicManagementServiceCallbackContract
<OperationContract(IsOneWay:=True)> _
Sub NextPatientDueInToSeeConsultant(ByVal doctorId As String)
End Interface

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 5: Designing and Defining Contracts

f Task 2: Add the callback contract to a service contract


1.

In Solution Explorer, right-click the


ClinicManagementServiceEventsContract file, and then click View Code.

2.

Locate the TODO 9 comment and define a service contract as follows.


[Visual C#]
// TODO 9
[ServiceContract(Namespace =
"http://contoso.com/ClinicManagementSystem/2007/10",
CallbackContract =
typeof(com.contoso.ClinicManagementService.ClinicManagementServiceC
allbackContract))]
public interface ClinicManagementServiceEventsContract
{
[OperationContract(IsOneWay = true)]
void RegisterForEvents();
}

[Visual Basic]
'TODO 9
<ServiceContract([Namespace]:="http://contoso.com/ClinicManagementS
ystem/2007/10",
CallbackContract:=GetType(com.contoso.ClinicManagementService.Clini
cManagementServiceCallbackContract))> _
Public Interface ClinicManagementServiceEventsContract
<OperationContract(IsOneWay:=True)> _
Sub RegisterForEvents()
End Interface

MCT USE ONLY. STUDENT USE PROHIBITED

L5-92

L5-93

f Task 3: Enable clients to register for callbacks with the service


1.

In Solution Explorer, right-click the


ClinicManagementServiceImplementation file, and then click View Code.

2.

Locate the TODO 10 comment, and then add the following code.
[Visual C#]
// TODO 10
private List<ClinicManagementServiceCallbackContract> eventClients
= null;
public ClinicManagementServiceImplementation()
{
eventClients = new
List<ClinicManagementServiceCallbackContract>();
}

[Visual Basic]
'TODO 10
Private eventClients As List( _
Of ClinicManagementServiceCallbackContract) =
Nothing
Public Sub New()
eventClients = New List( _
Of
ClinicManagementServiceCallbackContract)()
End Sub

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 5: Designing and Defining Contracts

3.

Locate the TODO 11 comment and change the definition of the


ClinicManagementServiceImplementation class, as follows.
[Visual C#]
// TODO 11
public class ClinicManagementServiceImplementation :
ClinicManagementServiceContract,
ClinicManagementServiceEventsContract

[Visual Basic]
'TODO 11
<ServiceBehavior(InstanceContextMode:=InstanceContextMode.[Single])
> _
Public Class ClinicManagementServiceImplementation
Implements ClinicManagementServiceContract
Implements ClinicManagementServiceEventsContract

4.

If you are using Visual Basic, press ENTER after you type the interface name to
generate the method stubs. If you are using Visual C#, right-click
ClinicManagementServiceEventsContract, point to Implement Interface,
and then click Implement Interface.

5.

If you are using Visual C#, locate the RegisterForEvents method and make the
following changes to the generated code:

Delete the following statements:

[Visual C#]
throw new NotImplementedException();

Add the following code to the RegisterForEvents method.

#region AppointmentServiceClinicEventsContract Members


public void RegisterForEvents()
{
ClinicManagementServiceCallbackContract client =
OperationContext.Current.GetCallbackChannel<ClinicManagementService
CallbackContract>();
eventClients.Add(client);
}
#endregion

MCT USE ONLY. STUDENT USE PROHIBITED

L5-94

L5-95

[Visual Basic]
Public Sub RegisterForEvents() _
Implements
ClinicManagementServiceEventsContract.RegisterForEvents
Dim client As ClinicManagementServiceCallbackContract _
= OperationContext.Current.GetCallbackChannel(
_
Of
ClinicManagementServiceCallbackContract)()
eventClients.Add(client)
End Sub

6.

In Solution Explorer, right-click the Connected WCF solution, and then click
Rebuild Solution.

f Task 4: Implement the callback contract in the clinic admin client and
register with the service
1.

Switch to Windows Explorer, and then go to the following folder:

If you are using Visual Basic, go to the folder


E:\Labfiles\Starter\VB\Callback\ConnectedWCF\ContosoServicesSelf
HostExtConfig\bin\Debug.

If you are using Visual C#, go to the folder


E:\Labfiles\Starter\CS\Callback\ConnectedWCF\ContosoServicesSelf
HostExtConfig\bin\Debug.

2.

Right-click the file ContosoServicesSelfHostExtConfig.exe, and then click


Run as administrator.

3.

In the User Account Control dialog box, click Allow.

4.

In the Windows Security Alert dialog box, click Unblock.

5.

Switch to Visual Studio 2008.

6.

In Solution Explorer, expand the ClinicAdminClient project, right-click the


Service References folder, and then click Add Service Reference.

7.

In the Add Service Reference dialog box, in the Address text box, enter
net.tcp://localhost:9003/Contoso/mex, and then click Go.

8.

In the Namespace box, enter ClinicManagementServiceReference, and the


click OK.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 5: Designing and Defining Contracts

9.

Switch to the ContosoServicesSelfHostExtConfig console window and press


ENTER to close the service host.

10. Switch to Visual Studio 2008.


11. In Solution Explorer, right-click the ClinicAdminForm file, and then click
View Code.
12. Locate the TODO 12 comment above the ClinicAdminClient namespace, and
add the following statement.
[Visual C#]
// TODO 12
using ClinicAdminClient.ClinicManagementServiceReference;

[Visual Basic]
'TODO 12
Imports ClinicAdminClient.ClinicManagementServiceReference

13. Locate the TODO 13 comment and change the definition of the
ClinicAdminForm class, as follows.
[Visual C#]
// TODO 13
public partial class ClinicAdminForm : Form,
ClinicManagementServiceEventsContractCallback

[Visual Basic]
'TODO 13
Partial Public Class ClinicAdminForm
Inherits Form
Implements ClinicManagementServiceEventsContractCallback

14. If you are using Visual Basic, press ENTER after you type the interface name to
generate the method stubs. If you are using Visual C#, right-click
ClinicManagementServiceEventsContractCallback, point to Implement
Interface, and then click Implement Interface.
15. If you are using Visual C#, locate the NextPatientDueInToSeeConsultant
method at the end of the ClinicAdminForm class, and make the following
changes to the generated code:

MCT USE ONLY. STUDENT USE PROHIBITED

L5-96

L5-97

Delete the following statements.

[Visual C#]
throw new NotImplementedException();

Add the following code to the method.

[Visual C#]
string message = String.Format("Please send in the next patient for
{0}", doctorId);
MessageBox.Show(message,
"Clinic Admin: Next Patient",
MessageBoxButtons.OK);

[Visual Basic]
Dim message As String = [String].Format( _
"Please send in the next patient for {0}",
doctorId)
MessageBox.Show(message, "Clinic Admin: Next Patient", _
MessageBoxButtons.OK)

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 5: Designing and Defining Contracts

16. Locate the TODO 14 comment in the ClinicAdminForm constructor, and


then add the following code.
[Visual C#]
// TODO 14
InstanceContext context = new InstanceContext(this);
NetTcpBinding binding = new NetTcpBinding();
EndpointAddress address = new
EndpointAddress("net.tcp://localhost:9003/Contoso/ClinicManagementS
erviceEvents");
ClinicManagementServiceEventsContract clinicManagementServiceEvents
=
DuplexChannelFactory<ClinicManagementServiceEventsContract>.CreateC
hannel(
context,
binding,
address);
bool registered = false;
for (int retryCount = 0; !registered && retryCount < 3;
retryCount++ )
{
try
{
clinicManagementServiceEvents.RegisterForEvents();
registered = true;
}
catch (Exception ex)
{
Thread.Sleep(2000);
}
}

MCT USE ONLY. STUDENT USE PROHIBITED

L5-98

L5-99

[Visual Basic]
'TODO 14
Dim context As New InstanceContext(Me)
Dim binding As New NetTcpBinding()
Dim address As New
EndpointAddress("net.tcp://localhost:9003/Contoso/ClinicManagementS
erviceEvents")
Dim clinicManagementServiceEvents As _
ClinicManagementServiceEventsContract = DuplexChannelFactory(
_
Of ClinicManagementServiceEventsContract).CreateChannel( _
context, binding,
address)
Dim registered As Boolean = False
Dim retryCount As Integer = 0
While Not registered AndAlso retryCount < 3
Try
clinicManagementServiceEvents.RegisterForEvents()
registered = True
Catch ex As Exception
Thread.Sleep(2000)
End Try
retryCount += 1
End While

f Task 5: Implement the triggering method


1.

In Solution Explorer, in the ClinicManagementService project, right-click the


ClinicManagementServiceImplementation file, and then click View Code.

2:

Locate the TODO 15 comment in the SendInNextPatient method, and then


add the following code.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 5: Designing and Defining Contracts

[Visual C#]
// TODO 15
List<ClinicManagementServiceCallbackContract> problemClients =
new
List<ClinicManagementServiceCallbackContract>();
foreach (ClinicManagementServiceCallbackContract client in
eventClients)
{
try
{
client.NextPatientDueInToSeeConsultant(doctorId);
}
catch (CommunicationException cex)
{
problemClients.Add(client);
}
}
// Assume that the client is no longer there and remove it
foreach (ClinicManagementServiceCallbackContract client in
problemClients)
{
eventClients.Remove(client);
}

[Visual Basic]
'TODO 15
Dim problemClients As New List( _
Of ClinicManagementServiceCallbackContract)()
For Each client As ClinicManagementServiceCallbackContract _
In eventClients
Try
client.NextPatientDueInToSeeConsultant(doctorId)
Catch cex As CommunicationException
problemClients.Add(client)
End Try
Next
' Assume that the client is no longer there and remove it
For Each client As ClinicManagementServiceCallbackContract _
In problemClients
eventClients.Remove(client)
Next

MCT USE ONLY. STUDENT USE PROHIBITED

L5-100

L5-101

f Task 6: Call the triggering method from the consultant client


1.

Switch to Windows Explorer, and then go to the following folder:

If you are using Visual Basic, go to the folder


E:\Labfiles\Starter\VB\Callback\ConnectedWCF\ContosoServicesSelf
HostExtConfig\bin\Debug.

If you are using Visual C#, go to the folder


E:\Labfiles\Starter\CS\Callback\ConnectedWCF\ContosoServicesSelf
HostExtConfig\bin\Debug.

2.

Right-click the file ContosoServicesSelfHostExtConfig.exe, and then click


Run as administrator.

3.

In the User Account Control dialog box, click Allow.

4.

Switch to Visual Studio 2008.

5.

In Solution Explorer, expand the ConsultantClient project, expand the


Service References folder, right-click the ClinicManagementServiceReference
node, and then click Update Service Reference.

6.

Switch to the ContosoServicesSelfHostExtConfig console window and press


ENTER to close the service host.

7.

Switch to Visual Studio 2008.

8.

In Solution Explorer, right-click the ConsultantForm file, and then click View
Code.

9.

Locate the TODO 16 comment above the ConsultantClient namespace and


add the following statement.
[Visual C#]
// TODO 16
using ConsultantClient.ClinicManagementServiceReference;

[Visual Basic]
'TODO 16
Imports ConsultantClient.ClinicManagementServiceReference

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 5: Designing and Defining Contracts

10. Locate the TODO 17 comment in the nextPatient_Click method and add the
following code.
[Visual C#]
// TODO 17
ClinicManagementServiceContract clinicManagementService =
new
ClinicManagementServiceContractClient();
clinicManagementService.SendInNextPatient(doctorId.Text);

[Visual Basic]
'TODO 17
Dim clinicManagementService As ClinicManagementServiceContract = _
New
ClinicManagementServiceContractClient()
clinicManagementService.SendInNextPatient(doctorId.Text)

f Task 7: Verify that callbacks are delivered to the clinic admin client
1.

On the Debug menu, click Start Without Debugging.

2.

In Solution Explorer, right-click ClinicAdminClient, point to Debug, and then


click Start new instance.

3.

Repeat step 2 to start a second instance of the ClinicAdminClient application.

4.

In Solution Explorer, right-click ConsultantClient, point to Debug, and then


click Start new instance.

5.

In Consultant Client window, click the Appointment Admin tab, select


Gastro_Jones in the My ID list box, and then click Next Patient.
Verify that two message boxes appear, one for each clinic administration client,
that inform you that doctor Gastro_Jones is ready for the next patient. Click
OK to close each message box. This demonstrates that the call to the operation
is now decoupled from the client.

MCT USE ONLY. STUDENT USE PROHIBITED

L5-102

L5-103

6.

Close one of the Clinic Administration Client windows.

7.

In the Consultant Client window, click the Appointment Admin tab, select
ENT_Davies in the My ID list box, and then click Next Patient.
Verify that only one message box appears that informs you that doctor
ENT_Davies is ready for the next patient. Click OK to close the message box.

8.

On the Debug menu, click Stop Debugging.

Results: After completing this exercise, you have defined a callback contract and
used this to communicate an event between two different service clients.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Contracts for Services and Data

Module 6: Handling Errors

Lab: Handling Errors


Exercise 1: Title
Logon Information:

Virtual Machine: 6461A-LON-DEV-06

User Name: Student

Password: Pa$$w0rd

Estimated time: 40 minutes

L6-105

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Handling Errors

Module 6: Handling Errors

Exercise 1: Handle Unexpected Errors in a WCF Service


Scenario
As the project moves into the prototyping stage, you need to define and implement
a consistent error handling policy for your services and the applications that use
them. It is difficult to predict all errors that might occur in your services, so the first
thing to do is to handle any errors that the service might generate.
In this exercise, you will add code to catch errors in the client application and
change the service behavior to pass more information about the errors to the client.
The main tasks for this exercise are as follows:
1.

Start the 6461-LON-DEV-06 virtual machine and log on as Student.

2.

Confirm that the clinic admin client runs without errors.

3.

Force an unexpected error in the service and examine the effects.

4.

Add an outer try block to the client and report the exception to the user.

5.

Pass exception detail from service to client.

f Task 1: Start the 6461-LON-DEV-06 virtual machine and log on as


Student
1.

Open the Virtual Server Remote Control Client and double-click 6461-LONDEV-06.

2.

Log on to 6461-LON-DEV-06 as Student using the password Pa$$w0rd.

f Task 2: Confirm that the clinic admin client runs without errors
1.

On the taskbar, click Start, point to All Programs, point to Microsoft Visual
Studio 2008, right-click Microsoft Visual Studio 2008, and then click Run as
administrator.

2.

In the User Account Control dialog box, click Continue.

MCT USE ONLY. STUDENT USE PROHIBITED

L6-106

3.

L6-107

On the File menu, point to Open, and then click Project/Solution.

If you are using Microsoft Visual Basic development system, in the


Open Project dialog box, go to the folder
E:\Labfiles\Starter\VB\UnexpectedErrors\ConnectedWCF, and then
double-click ConnectedWCF.sln.

If you are using Microsoft Visual C# development tool, in the Open


Project dialog box, go to the folder
E:\Labfiles\Starter\CS\UnexpectedErrors\ConnectedWCF, and then
double-click ConnectedWCF.sln.

4.

On the Debug menu, click Start Debugging.

5.

In the Windows Security Alert dialog box, click Unblock.

6.

In the Clinic Administration Client form, click the Create Appointment tab.
Enter the following data, and then click Create:

Doctor: Gastro_Jones

Date: Todays date

Slot: Click Find Slots (this selects the first slot shown)

Patient: NH991199Z

7.

In the Clinic Admin Appointment Created window, click OK.

8.

Click the Todays Appointments tab, and then click Refresh.


On this tab, you should see the appointment you have just added. You will use
this listing function as the basis of the rest of the exercises.

9.

On the Debug menu, click Stop Debugging.

f Task 3: Force an unexpected error in the service and examine the


effects
1.

In Solution Explorer, expand the AppointmentService project, right-click the


AppointmentHelper file, and then click View Code.

2.

Locate the TODO 1 comment in the GetConnection method and change the
connection string passed into the SqlConnection constructor as follows:

Data Source: .\\Dummy

Connection Timeout: 5

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Handling Errors

Module 6: Handling Errors

[Visual Basic]
' TODO 1
Return New SqlConnection("Data Source=.\Dummy;" & _
"Initial Catalog=Appointments;"& _
"Integrated Security=SSPI;" & _
"Connection Timeout=5")

[Visual C#]
// TODO 1
return new SqlConnection("Data Source=.\\Dummy;" +
"Initial Catalog=Appointments;" +
"Integrated Security=SSPI;" +
"Connection Timeout=5");

3.

On the Debug menu, click Start Debugging.

4.

In the Clinic Administration Client form, click the Todays Appointments tab,
and then click Refresh.
After 5 seconds, you will see the Visual Studio Exception dialog box appear in
the service-side code (AppointmentHelper) with the title "SQLException was
unhandled by user code". This is the original exception inside the service
caused by setting the invalid SQL data source value in the connection string.

5.

On the Debug menu, click Continue.


You will now see the Visual Studio Exception dialog box appear in the clientside code (ClinicAdminForm) with the title "FaultException was unhandled".

Note: If you leave it too long between the service-side exception appearing and
continuing to debug, you might see a dialog box titles "TimeoutException was
unhandled". In this case, restart the debugging session and perform the preceding
above more rapidly.

6.

On the Debug menu, click Stop Debugging.

MCT USE ONLY. STUDENT USE PROHIBITED

L6-108

L6-109

f Task 4: Add an outer try block to the client and report the exception
to the user
1.

In Solution Explorer, expand the ClinicAdminClient project, right-click the


ClinicAdminForm file, and then click View Code.

2.

Locate the TODO 2 comment in the RefreshAppointmentList_Click method,


and then change the code in this method, as shown here.
[Visual Basic]
' TODO 2
Try
Dim proxy As AppointmentServiceContract = _
GetAppointmentServiceProxy()
appointmentsToday.DataSource = proxy.ListTodaysAppointments()
Catch unknown As Exception
MessageBox.Show(unknown.Message, _
"Clinic Admin: Error", _
MessageBoxButtons.OK)
End Try

[Visual C#]
// TODO 2
try
{
AppointmentServiceContract proxy =
GetAppointmentServiceProxy();
appointmentsToday.DataSource = proxy.ListTodaysAppointments();
}
catch (Exception unknown)
{
MessageBox.Show(unknown.Message,
"Clinic Admin: Error",
MessageBoxButtons.OK);
}

3.

On the Debug menu, click Exceptions.

4.

In the Exceptions dialog box, clear the User-unhandled check box for
Common Language Runtime Exceptions, and then click OK.

5.

On the Debug menu, click Start Debugging.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Handling Errors

Module 6: Handling Errors

6.

In the Clinic Administration Client form, click the Todays Appointments tab,
and then click Refresh.
After 5 seconds, you will see the Clinic Admin: Error message box. Verify that
it displays the following message, and then click OK:
"The server was unable to process the request due to an internal error. For
more information about the error, either turn on
IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from
the <serviceDebug> configuration behavior) on the server in order to send the
exception information back to the client, or turn on tracing as per the
Microsoft .NET Framework 3.0 SDK documentation and inspect the server
trace logs."

7.

On the Debug menu, click Stop Debugging.

f Task 5: Pass exception detail from service to client


1.

In Solution Explorer, expand the ContosoServicesSelfHostExtConfig project,


right-click app.config, and then click Edit WCF Configuration.

2.

In the Configuration pane, expand the Advanced folder, expand the Service
Behaviors folder, and then click the AppointmentServiceBehavior node.

3.

In the Behavior: AppointmentServiceBehavior pane, click Add.

4.

In the Adding Behavior Element Extension Sections dialog box, click


serviceDebug and then click Add.

5.

In the Configuration pane, expand the AppointmentServiceBehavior behavior


node, and then click serviceDebug.

6.

In the serviceDebug pane on the right side, set the value of the
IncludeExceptionDetailInFaults property to True.

7.

In the Windows Communication Foundation (WCF) Service Configuration


Editor window, on the File menu, click Save.

8.

Close the WCF Service Configuration Editor window.

9.

On the Debug menu, click Start Debugging.

MCT USE ONLY. STUDENT USE PROHIBITED

L6-110

L6-111

10. In the Clinic Administration Client form, click the Today's Appointments tab,
and then click Refresh.
After 5 seconds, you will see the Clinic Admin: Error message box. Verify that
it displays the following message, and then click OK:
"An error has occurred while establishing a connection to the server. When
connecting to SQL Server 2005, this failure may be caused by the fact that
under the default settings SQL Server does not allow remote connections.
(provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance
Specified)"
11. On the Debug menu, click Stop Debugging.
12. Close Microsoft Visual Studio 2008 development system.

Results: After completing this exercise, you have seen how to handle service
exceptions on the client and how to pass more detail from service to client.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Handling Errors

Module 6: Handling Errors

Exercise 2: Add Fault Handling to a WCF Service and the


Service Contract
Scenario
When you define and implement a consistent error handling policy for your
services, you should specify which errors your services generate and under what
conditions they generate these errors. These error definitions form part of the
contract between the services and the applications that use them.
In this exercise, you will add code to catch errors on the client and change the
service behavior to pass more information about the errors to the client.
The main tasks for this exercise are as follows:
1.

Define a fault contract.

2.

Adjust the service contract and run-time behavior so that the fault is the only
mechanism for passing error information to the client.

3.

Catch and handle the exception on the server side.

4.

Adjust the client code to work with the service fault.

f Task 1: Define a fault contract


1.

On the taskbar, click Start, point to All Programs, point to Microsoft Visual
Studio 2008, right-click Microsoft Visual Studio 2008, and then click Run as
administrator.

2.

In the User Account Control dialog box, click Continue.

3.

On the File menu, point to Open, and then click Project/Solution.

If you are using Visual Basic, in the Open Project dialog box, go to the
folder E:\Labfiles\Starter\VB\ServiceErrors\ConnectedWCF, and then
double-click ConnectedWCF.sln.

If you are using Visual C#, in the Open Project dialog box, go to the
folder E:\Labfiles\Starter\CS\ServiceErrors\ConnectedWCF, and then
double-click ConnectedWCF.sln.

4.

In Solution Explorer, right-click the AppointmentService project, point to


Add, and then click New Item.

5.

In the Add New Item - AppointmentService dialog box, in the Templates


pane, click Class, set the Name to UnexpectedServiceFault, and then click
Add.

MCT USE ONLY. STUDENT USE PROHIBITED

L6-112

6.

In Solution Explorer, expand the AppointmentService project, right-click


UnexpectedServiceFault, and then click View Code.

7.

Make the following changes to the generated code:

L6-113

If you are using Visual C#, delete the following statements.

[Visual C#]
using System.Collections.Generic;
using System.Linq;
using System.Text;

Add a statement to bring the namespace System.Runtime.Serialization


into scope.

If you are using Visual C#, set the namespace containing the class to be
com.contoso.

Your code should now look like the following.


[Visual Basic]
Imports System.Runtime.Serialization
Class UnexpectedServiceFault
End Class

[Visual C#]
using System;
using System.Runtime.Serialization;
namespace com.contoso
{
class UnexpectedServiceFault
{
}
}

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Handling Errors

Module 6: Handling Errors

8.

Modify the definition of the UnexpectedServiceFault class as follows.


[Visual Basic]
<DataContract([Namespace] := _
"http://contoso.com/ClinicManagementSystem/2007/10")> _
Public Class UnexpectedServiceFault
End Class

[Visual C#]
[DataContract(Namespace="http://contoso.com/ClinicManagementSystem/
2007/10")]
public class UnexpectedServiceFault
{
}

9.

Add the following code to the UnexpectedServiceFault class.


[Visual Basic]
Private _endUserMessage As String = "UNDEFINED"
<DataMember()> _
Public Property EndUserMessage() As String
Get
Return _endUserMessage
End Get
Set
_endUserMessage = value
End Set
End Property
Private _errorCode As Integer = -1
<DataMember()> _
Public Property ErrorCode() As Integer
Get
Return _errorCode
End Get
Set
_errorCode = value
End Set
End Property

MCT USE ONLY. STUDENT USE PROHIBITED

L6-114

L6-115

[Visual C#]
private string _endUserMessage = "UNDEFINED";
[DataMember]
public string EndUserMessage
{
get
{
return _endUserMessage;
}
set
{
_endUserMessage = value;
}
}
private int _errorCode = -1;
[DataMember]
public int ErrorCode
{
get
{
return _errorCode;
}
set
{
_errorCode = value;
}
}

f Task 2: Adjust the service contract and run-time behavior so that the
fault is the only mechanism for passing error information to the client
1.

In Solution Explorer, expand the AppointmentService project, right-click the


AppointmentServiceContract file, and then click View Code.

2.

Locate the TODO 3 comment above the ListTodaysAppointments method


and add the following FaultContract to the method.
[Visual Basic]
' TODO 3
<OperationContract()> _
<FaultContract(GetType(UnexpectedServiceFault))> _
Function ListTodaysAppointments() As List(Of Appointment)

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Handling Errors

Module 6: Handling Errors

[Visual C#]
// TODO 3
[OperationContract]
[FaultContract(typeof(com.contoso.UnexpectedServiceFault))]
List<Appointment> ListTodaysAppointments();

3.

In Solution Explorer, expand the ContosoServicesSelfHostExtConfig project,


right-click app.config, and then click Edit WCF Configuration.

4.

In the Configuration pane, expand the Advanced folder, expand the Service
Behaviors folder, expand the AppointmentServiceBehavior node, and then
click serviceDebug.

5.

In the serviceDebug pane on the right side, set the value of the
IncludeExceptionDetailInFaults property to False.

6.

In the WCF Service Configuration Editor window, on the File menu, click
Save.

7.

Close the WCF Service Configuration Editor window.

f Task 3: Catch and handle the exception on the server side


1.

In Solution Explorer, in the AppointmentService project, right-click the


AppointmentServiceImplementation file, and then click View Code.

2.

Locate the TODO 4 comment in the ListTodaysAppointments method and


surround the call to AppointmentHelper.ListTodaysAppointments with a
Try/Catch block (for Visual Basic) or a try/catch block (for Visual C#) that
will catch any form of Exception, as shown in the following code.
[Visual Basic]
' TODO 4
Try
Return New AppointmentHelper().ListTodaysAppointments()
Catch unexpected As Exception
End Try

MCT USE ONLY. STUDENT USE PROHIBITED

L6-116

L6-117

[Visual C#]
// TODO 4
try
{
return new AppointmentHelper().ListTodaysAppointments();
}
catch (Exception unexpected)
{
}

3.

In the catch block, add the following code.


[Visual Basic]
Catch unexpected As Exception
LogException(unexpected, "ListTodaysAppointments")
Dim fault As New UnexpectedServiceFault()
fault.EndUserMessage = "There was an unexpected error " & _
"on the server. You may be able to " & _
"try this operation again." & _
" If it still does not work then " & _
"please contact your support
department."
fault.ErrorCode = 101
Throw New FaultException(Of UnexpectedServiceFault)(fault, _
"An unexpected error occurred inside the service.")
End Try

[Visual C#]
catch (Exception unexpected)
{
LogException(unexpected, "ListTodaysAppointments");
UnexpectedServiceFault fault = new UnexpectedServiceFault();
fault.EndUserMessage = "There was an unexpected error " +
"on the server. You may be able to " +
"try this operation again." +
" If it still does not work then " +
"please contact your support
department.";
fault.ErrorCode = 101;
throw new FaultException<UnexpectedServiceFault>(fault,
"An unexpected error occurred inside the service.");
}

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Handling Errors

Module 6: Handling Errors

4.

In Solution Explorer, right-click the ConnectedWCF solution, and then click


Rebuild Solution.

f Task 4: Adjust the client code to work with the service fault
1.

On the taskbar, click Start, point to All Programs, point to Accessories, and
then click Windows Explorer.

2.

In Windows Explorer, go to the following folder:

If you are using Visual Basic, go to


E:\Labfiles\Starter\VB\ServiceErrors\ConnectedWCF\ContosoService
sSelfHostExtConfig\bin\Debug

If you are using Visual C#, go to


E:\Labfiles\Starter\CS\ServiceErrors\ConnectedWCF\ContosoService
sSelfHostExtConfig\bin\Debug

3.

Right-click the file ContosoServicesSelfHostExtConfig.exe, and then click


Run as Administrator.

4.

In the User Account Control dialog box, click Allow.

5.

In the Windows Security Alert dialog box, click Unblock.

6.

Switch to Visual Studio 2008. In Solution Explorer, expand the


ClinicAdminClient project, expand the Service References folder, right-click
AppointmentServiceReference, and then click Update Service Reference.

7.

Switch to the ContosoServicesSelfHostExtConfig console window and press


ENTER to close the service host.

8.

Switch to Visual Studio 2008. In Solution Explorer, in the ClinicAdminClient


project, right-click the ClinicAdminForm file, and then click View Code.

MCT USE ONLY. STUDENT USE PROHIBITED

L6-118

9.

L6-119

Locate the TODO 2 comment in the RefreshAppointmentList_Click method


and change the Try/Catch block (for Visual Basic) or a try/catch block (for
Visual C#) as shown in the following code.
[Visual Basic]
' TODO 2
Try
Dim proxy As AppointmentServiceContract = _
GetAppointmentServiceProxy()
appointmentsToday.DataSource = proxy.ListTodaysAppointments()
Catch ex As FaultException(Of UnexpectedServiceFault)
MessageBox.Show(ex.Detail.EndUserMessage, _
"Clinic Admin: Error", _
MessageBoxButtons.OK)
End Try

[Visual C#]
// TODO 2
try
{
AppointmentServiceContract proxy =
GetAppointmentServiceProxy();
appointmentsToday.DataSource = proxy.ListTodaysAppointments();
}
catch (FaultException<UnexpectedServiceFault> ex)
{
MessageBox.Show(ex.Detail.EndUserMessage,
"Clinic Admin: Error",
MessageBoxButtons.OK);
}

10. On the Debug menu, click Start Without Debugging.


11. In the Windows Security Alert dialog box, click Unblock.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Handling Errors

Module 6: Handling Errors

12. In the Clinic Administration Client form, click the Todays Appointments tab,
and then click Refresh.
After 5 seconds, you will see the Clinic Admin: Error message box. Verify that
it displays the following message:
"There was an unexpected error on the server. You may be able to try this
operation again. If it still does not work then please contact your support
department"
13. Close Visual Studio 2008.

Results: After completing this exercise, you have defined a fault contract and used
this to pass error detail between a WCF service and a client.

MCT USE ONLY. STUDENT USE PROHIBITED

L6-120

Module 7: Improving WCF Service Quality

Lab: Improving Service Quality


Logon Information:

Virtual Machine: 6461A-LON-DEV-07

User Name: Student

Password: Pa$$w0rd

Estimated time: 80 minutes

L7-121

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 7: Improving WCF Service Quality

Exercise 1: Managing WCF Service Instances


Scenario
You must determine the best instance management and threading approach for the
Contoso Clinic Management System. Opinion is divided on whether to have a
single service instance or multiple instances. You have been asked to demonstrate
some of the issues to the development manager and some of the more technically
aware stakeholders. To do this, you need to show how problems such as lost or
corrupt data might occur if the wrong option is selected.
In this exercise, you will replace the appointment service implementation with one
that stores appointments on a linked list. You will then set the state management
style so that multiple clients can "see" the appointments and then load the service
until it clearly demonstrates concurrency issues.
The main tasks for this exercise are as follows:
1.

Start the 6461-LON-DEV-07 virtual machine and log on as Student.

2.

Replace the appointment service implementation with one based on an inmemory linked list.

3.

Set the instance context mode to share the appointment data between clients.

f Task 1: Start the 6461-LON-DEV-07 virtual machine and log on as


Student
1.

Open the Virtual Server Remote Control Client and double-click 6461-LONDEV-07.

2.

Log on to 6461-LON-DEV-07 as Student using the password Pa$$w0rd.

f Task 2: Replace the appointment service implementation with one


based on an in-memory linked list
1.

On the Start menu, point to All Programs, point to Microsoft Visual Studio
2008, right-click Microsoft Visual Studio 2008, and then click Run as
administrator.

2.

In the User Account Control dialog box, click Continue.

MCT USE ONLY. STUDENT USE PROHIBITED

L7-122

3.

4.

5.

L7-123

On the File menu, point to Open, and then click Project/Solution:

If you are using Microsoft Visual Basic development system, in the


Open Project dialog box, go to the folder
E:\Labfiles\Starter\VB\InstanceManagement\ConnectedWCF, and
then double-click ConnectedWCF.sln.

If you are using Microsoft Visual C# development tool, in the Open


Project dialog box, go to the folder
E:\Labfiles\Starter\CS\InstanceManagement\ConnectedWCF, and
then double-click ConnectedWCF.sln.

In Solution Explorer, expand the AppointmentService project, right-click the


AppointmentServiceLinkedListImplementation file, and then click View
Code. Examine the code in this file to see how:

The constructor creates an instance of the LinkedListAppointmentHelper


class.

The CreateAppointment and ListTodaysAppointments methods


delegate their functionality to the LinkedListAppointmentHelper
instance.

In Solution Explorer, right-click the LinkedListAppointmentHelper file, and


then click View Code. Examine the code in this file to see how:

The CreateAppointment method wraps the Appointment passed in as


the parameter in a linked-list wrapper, steps through the linked list to find
the end, and appends the wrapped appointment to the list.

The ListTodaysAppointments method walks through the linked list and


places any appointments that occur today into a List<Appointment> that
it returns.

6.

In Solution Explorer, expand the ContosoServicesSelfHostExtConfig project,


right-click the ContosoServicesHost file, and then click View Code.

7.

In the View Code window, locate the TODO 1 comment in the Main method.
Change the service instance type for the appointment service to
com.contoso.AppointmentService.AppointmentServiceLinkedList
Implementation.
[Visual Basic]
' TODO 1
Dim appointmentInstanceType As Type = _
GetType(com.contoso.AppointmentService. _
AppointmentServiceLinkedListImplementation)

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 7: Improving WCF Service Quality

[Visual C#]
// TODO 1
Type appointmentInstanceType =
typeof(com.contoso.AppointmentService.
AppointmentServiceLinkedListImplementation);

8.

In Solution Explorer, right-click app.config, and then click Edit WCF


Configuration.

9.

Expand the Services folder, and then click


com.contoso.AppointmentService.AppointmentServiceImplementation. In
the right pane, set the Name value to
com.contoso.AppointmentService.AppointmentServiceLinkedList
Implementation.

10. In the WCF Service Configuration Editor window, on the File menu, click
Save.
11. Close the WCF Service Configuration Editor window.
12. In Solution Explorer, right-click Solution 'Connected WCF', and then click
Rebuild Solution.
13. On the Debug menu, click Start Debugging.
14. In the Windows Security Alert dialog box, click Unblock.
15. In the Clinic Administration Client form, click the Create Appointment tab.
16. Click Find Slots, and then verify that a list of available slots is displayed. This
confirms that the linked list form of the appointment service is running
correctly.
17. On the Debug menu, click Stop Debugging.

MCT USE ONLY. STUDENT USE PROHIBITED

L7-124

L7-125

f Task 3: Set the instance management style to share the appointment


data between clients
1.

In Solution Explorer, expand the HighSpeedAppointmentMaker project,


right-click the HighSpeedMainForm file, and then click View Code. This form
starts multiple client threads, each of which makes calls to the appointment
service.
Examine the AddAppointments method that each thread calls. This method
creates a proxy for the appointment service and then calls the
CreateAppointment operation 20 times. This method reports its progress by
asking the appointment service for a list of the current appointments and
displaying the number of appointments currently reported by the service,
together with the number of appointments this thread has added so far.
If you run this application with 4 threads, you would expect 80 (4 x 20)
appointments to be made on the service.

2.

In Solution Explorer, right-click the ConnectedWCF solution, and then click


Set Startup Projects.

3.

In the Solution 'ConnectedWCF' Property Pages dialog box, click Multiple


startup projects.

4.

In the Multiple startup projects list, set the Action for the
ContosoServicesSelfHostExtConfig and HighSpeedAppointmentMaker
projects to Start. Set the Action for the remaining projects to None.

5.

In the Solution 'ConnectedWCF' Property Pages dialog box, click OK.

6.

On the Debug menu, click Start Debugging.

7.

In the High Speed Appointment Maker window, increase the number of


client threads to 4, and then click Go.
Each row shows the results from one thread. Verify that each thread reports
that it has added 20 appointments but that the number that the service reports
in each case is only 20. At least one of the values reported by the service
should be 80 because that would be the last value reported by the service if it
had received all 80 appointment requests. The problem is that the default
instance management mode is PerSession, so each client thread gets its own
instance of the appointment service and cannot see the appointments made by
the other client threads.

8.

On the Debug menu, click Stop Debugging.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 7: Improving WCF Service Quality

9.

In Solution Explorer, expand the AppointmentService project, right-click the


AppointmentServiceLinkedListImplementation file, and then click View
Code.

10. Locate the TODO 2 comment above the


AppointmentServiceLinkedListImplementation class definition, and then
add a ServiceBehaviorAttribute with its InstanceContextMode property set
to InstanceContextMode.Single. All client threads will now interact with the
same instance of the appointment service.
[Visual Basic]
' TODO 2
<ServiceBehavior(InstanceContextMode :=
InstanceContextMode.[Single])> _
Public Class AppointmentServiceLinkedListImplementation
Implements AppointmentServiceContract
...

[Visual C#]
// TODO 2
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class AppointmentServiceLinkedListImplementation :
AppointmentServiceContract
...

11. On the Debug menu, click Start Debugging.


12. In the High Speed Appointment Maker window, increase the number of
client threads to 4, and then click Go.
Verify that the service reports that it has received 80 appointment requests (at
least one of the lines should report 80 appointments).
13. On the Debug menu, click Stop Debugging.
14. Close Visual Studio 2008.

Results: After completing this exercise, you have seen how to change the instance
management mode on your service and what effect this has.

MCT USE ONLY. STUDENT USE PROHIBITED

L7-126

L7-127

Exercise 2: Managing Concurrency Issues


Scenario
You have been asked to demonstrate the problems that might occur from longerrunning methods and resource contention. To do this, you need to show how
corruption might occur if the wrong combination of threading and instance
management is selected.
In this exercise, you will intentionally create a threading problem in the linked-list
version of the appointment service implementation. You will then modify the
threading mode so that multiple clients can access the service without corruption.
The main tasks for this exercise are as follows:
1.

Demonstrate that the service defaults to a safe threading mode.

2.

Show that attempts to speed up the service can lead to corruption due to
multi-threading.

f Task 1: Demonstrate that the service defaults to a safe threading


mode
1.

On the Start menu, point to All Programs, point to Microsoft Visual Studio
2008, right-click Microsoft Visual Studio 2008, and then click Run as
administrator.

2.

In the User Account Control dialog box, click Continue.

3.

On the File menu, point to Open and then click Project/Solution:

4.

If you are using Visual Basic, in the Open Project dialog box, go to the
folder E:\Labfiles\Starter\VB\Concurrency\ConnectedWCF, and then
double-click ConnectedWCF.sln.

If you are using Visual C#, in the Open Project dialog box, go to the
folder E:\Labfiles\Starter\CS\Concurrency\ConnectedWCF, and then
double-click ConnectedWCF.sln.

In Solution Explorer, expand the AppointmentService project, right-click the


LinkedListAppointmentHelper file, and then click View Code.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 7: Improving WCF Service Quality

5.

Locate the TODO 3 comment in the CreateAppointment method, and then


add the following code.
[Visual Basic]
' TODO 3
Console.WriteLine([String].Format("{0}: called with {1} & {2}" & _
", id is {3} : about to sleep", _
DateTime.Now.ToLongTimeString(), _
appointment.DoctorId, _
appointment.PatientId, _
appointment.Id))
Thread.Sleep(500)
Console.WriteLine([String].Format("{0}: woken up", _
DateTime.Now.ToLongTimeString()))

[Visual C#]
// TODO 3
Console.WriteLine(String.Format("{0}: called with {1} & {2}" +
", id is {3} : about to sleep",
DateTime.Now.ToLongTimeString(),
appointment.DoctorId,
appointment.PatientId,
appointment.Id));
Thread.Sleep(500);
Console.WriteLine(String.Format("{0}: woken up",
DateTime.Now.ToLongTimeString()));

The call to Sleep should allow any other thread running in the service to
obtain a duplicate place in the linked list and so the service should gradually
"lose" appointments.
6.

On the Debug menu, click Start Debugging.

7.

In the Windows Security Alert dialog box, click Unblock.

MCT USE ONLY. STUDENT USE PROHIBITED

L7-128

8.

L7-129

In the High Speed Appointment Maker window, increase the number of


client threads to 4, and then click Go.
Verify that each thread reports that it has added 20 appointments and that at
least one of the values reported by the service is 80. Because the instance life
cycle management value is Single, you might expect that the Sleep call you
added would cause corruption as described in step 5.
The reason that there is no corruption is because the default threading mode is
Single; this prevents any other calling thread from accessing the service
instance even while an earlier caller is sleeping in the service. However, the
price you pay for this safety is in terms of potential performance.

9.

On the Debug menu, click Stop Debugging.

f Task 2: Show that attempts to speed up the service can lead to


corruption due to multi-threading
1.

In Solution Explorer, expand the AppointmentService project, right-click the


AppointmentServiceLinkedListImplementation file, and then click View
Code.

2.

Locate the TODO 2 comment above the


AppointmentServiceLinkedListImplementation class definition, and then
amend the ServiceBehaviorAttribute, as shown in the following code.
[Visual Basic]
' TODO 2
<ServiceBehavior(InstanceContextMode:=InstanceContextMode.[Single],
_
ConcurrencyMode:=ConcurrencyMode.Multiple)> _
Public Class AppointmentServiceLinkedListImplementation
Implements AppointmentServiceContract
...

[Visual C#]
// TODO 2
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single,
ConcurrencyMode=ConcurrencyMode.Multiple)]
public class AppointmentServiceLinkedListImplementation :
AppointmentServiceContract
...

3.

On the Debug menu, click Start Debugging.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 7: Improving WCF Service Quality

4.

In the High Speed Appointment Maker window, increase the number of


client threads to 4, and then click Go.
Verify that each thread reports that it has added 20 appointments but that the
values reported by the service are well below 80. As you can see, in an effort to
improve performance, this has opened up potential for corruption due to
resource contention (in this case, the resource is the linked list).

5.

On the Debug menu, click Stop Debugging.

6.

Close Visual Studio 2008.

Results: After completing this exercise, you have seen how to control the threading
mode of a service.

MCT USE ONLY. STUDENT USE PROHIBITED

L7-130

L7-131

Exercise 3: Throttling Access to a WCF Service


Scenario
The level of load placed on the Contoso Clinic Management System will vary over
time as more family practitioners sign up to the service. Also, the level of load from
the family practitioners will be unpredictable over the course of a week. However,
one thing is for certain: when a patient stands at the administrator's desk in the
practice waiting for their appointment, they will not appreciate the system running
slowly. Because you will probably initially deploy the system on a limited amount
of hardware, you must explore how effective throttling the number of clients will
be in terms of maintaining service performance.
In this exercise, you will investigate how the service throttling setting affects the
response time for successful callers and its overall impact on response times and
throughput.
The main tasks for this exercise are as follows:
1.

Take an initial measure of the response times.

2.

Determine the effect of throttling on overall response times.

3.

Determine the effect of throttling on successful caller response times.

f Task 1: Take an initial measure of the response times


1.

On the Start menu, point to All Programs, point to Microsoft Visual Studio
2008, right-click Microsoft Visual Studio 2008, and then click Run as
administrator.

2.

In the User Account Control dialog box, click Continue.

3.

On the File menu, point to Open, and then click Project/Solution.

4.

If you are using Visual Basic, in the Open Project dialog box, go to the
folder E:\Labfiles\Starter\VB\Throttling\ConnectedWCF, and then
double-click ConnectedWCF.sln.

If you are using Visual C#, in the Open Project dialog box, go to the
folder E:\Labfiles\Starter\CS\Throttling\ConnectedWCF, and then
double-click ConnectedWCF.sln.

In Solution Explorer, expand the HighSpeedAppointmentMaker project,


right-click the HighSpeedMainForm file, and then click View Code. This
version of the application times the duration of the calls made by each client
thread and provides you with an overall average.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 7: Improving WCF Service Quality

5.

Locate the TODO 4 comment in the AddAppointments method, and then


examine the code below it. This code takes a timestamp before the calls to the
CreateAppointment and ListTodaysAppointments operations, and then it
uses this information to calculate an average timing across the 20 pairs of calls.

Note: Because these timings are taken on the client side, they will include any
waiting time encountered by the call, such as if it is blocked waiting for a service
instance.

6.

On the Debug menu, click Start Debugging.

7.

In the Windows Security Alert dialog box, click Unblock.

8.

In the High Speed Appointment Maker window, increase the number of


client threads to 10, and then click Go.
After all the threads finish, make a note of the average value for the call
duration across the 10 threads reported in the dialog box, and then click OK.

9.

On the Debug menu, click Stop Debugging.

f Task 2: Determine the effect of throttling on overall response times


1.

In Solution Explorer, expand the ContosoServicesSelfHostExtConfig project,


right-click app.config, and then click Edit WCF Configuration.

2.

Expand the Advanced folder, expand the Service Behaviors folder, and then
click the HttpMexAndExceptionDetail behavior. In the right pane, click Add.

3.

In the Adding Behavior Element Extension Sections dialog box, select


serviceThrottling, and then click Add.

4.

In the Configuration pane, expand the HttpMexAndExceptionDetail behavior


node, and then click serviceThrottling.

5.

In the serviceThrottling pane, set the value of MaxConcurrentCalls property


to 3.

6.

In the WCF Service Configuration Editor window, on the File menu, click
Save.

7.

Close the WCF Service Configuration Editor window.

8.

On the Debug menu, click Start Debugging.

MCT USE ONLY. STUDENT USE PROHIBITED

L7-132

9.

L7-133

In the High Speed Appointment Maker window, increase the number of


client threads to 10, and then click Go.
After all the threads finish running, you will see a dialog box that contains an
average value for the call duration across the 10 threads. Make a note of this
value, and then click OK.
Verify that this value is more than that reported earlier.
You should find that setting a throttling value of less than the number of
calling threads has increased the average time taken per-call when measured
from the client side. This is because calling threads are now having to block
waiting for another calling thread to leave a service instance so that the
number of concurrent calls drops below 3.

10. On the Debug menu, click Stop Debugging.

f Task 3: Determine the effect of throttling on successful caller response


times
1.

In Solution Explorer, expand the HighSpeedAppointmentMaker project,


right-click the HighSpeedMainForm file, and then click View Code.

2.

Locate the TODO 4 comment in the AddAppointments method, and then


perform the following steps:

Delete the statement that creates the startTimestamp variable.

Delete the statement that calls the CreateAppointment method.

Delete the statement that calls the ListTodaysAppointments method.

Delete the statement that creates the endTimestamp variable.

Delete the statement that creates the millisThisCall variable.

Add the following code:


[Visual Basic]
' TODO 4
Dim callTime As TimeSpan = _
appointmentService.TimedCreateAppointment(myPatient, myDoctor,
_
start.AddMinutes(i * 30))
callTime += appointmentService.TimedListTodaysAppointments()
Dim millisThisCall As Integer = callTime.Milliseconds

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 7: Improving WCF Service Quality

[Visual C#]
// TODO 4
TimeSpan callTime =
appointmentService.TimedCreateAppointment(myPatient,
myDoctor, start.AddMinutes(i * 30));
callTime += appointmentService.TimedListTodaysAppointments();
int millisThisCall = callTime.Milliseconds;

3.

On the Debug menu, click Start Debugging.

4.

In the High Speed Appointment Maker window, increase the number of


client threads to 10, and then click Go.
After all the threads finish running, make a note of the average value for the
call duration across the 10 threads reported in the dialog box, and then click
OK.
Compare this value with the ones you recorded in Task 2. Verify that this new
value is significantly lower because it is recording the duration of calls on the
service side when there are only 3 concurrent calls. This does not include any
wait time.

5.

On the Debug menu, click Stop Debugging.

6.

In Solution Explorer, expand the ContosoServicesSelfHostExtConfig project,


right-click app.config, and then click Edit WCF Configuration.

7.

Expand Advanced folder, expand the Service Behaviors folder, expand the
HttpMexAndExceptionDetail behavior, and then click serviceThrottling.

8.

In the serviceThrottling pane on the right side, set the value of


MaxConcurrentCalls property to 20.

9.

In the WCF Service Configuration Editor window, on the File menu, click
Save.

10. Close the WCF Service Configuration Editor window.


11. On the Debug menu, click Start Debugging.

MCT USE ONLY. STUDENT USE PROHIBITED

L7-134

L7-135

12. In the High Speed Appointment Maker window, increase the number of
client threads to 10, and then click Go.
After all the threads finish running, make a note of the average value for the
call duration across the 10 threads reported in the dialog box, and then click
OK.
Verify that this value is slightly higher than the value you recorded earlier in
this task. Has removing throttling increased or decreased this overall serviceside time?
You should find that setting the throttling value to more than the number of
calling threads has increased the average time taken per-call when measured
from the service side. This is because there are now potentially 10 concurrent
calling threads contending for service-side resources at the same time. This will
slow things down and so a higher call time will be seen.
13. On the Debug menu, click Stop Debugging.
14. Close Visual Studio 2008.

Results: After completing this exercise, you have seen how to use throttling and
how it affects the callers to a service.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 7: Improving WCF Service Quality

Exercise 4: Passing Bulk Data Between a WCF Client and


Service
Scenario
The consultants using the Contoso Clinic Management System will need access to
large amounts of patient data in the form of MRI scan and X-ray images. These files
will be far larger than is reasonable to pass as a standard parameter, so they will
need some form of special handling.
In this exercise, you will pass large binary data across a WCF service interface
using both MTOM and streaming.
The main tasks for this exercise are as follows:
1.

Add an operation to return an image as a byte array to a WCF service.

2.

Add a service endpoint that uses MTOM encoding.

3.

Add code to the client to call the new operation.

4.

Configure the client to use MTOM encoding.

5.

View the raw MTOM messages.

6.

Add a streamed method to the contract.

7.

Change the service-side endpoint to support streaming.

8.

Change the client code to call the new operation.

9.

Configure the client to use streaming.

10. View the raw streamed messages.

f Task 1: Add an operation to return an image as a byte array to a WCF


service
1.

On the Start menu, point to All Programs, point to Microsoft Visual Studio
2008, right-click Microsoft Visual Studio 2008, and then click Run as
administrator.

2.

In the User Account Control dialog box, click Continue.

MCT USE ONLY. STUDENT USE PROHIBITED

L7-136

3.

L7-137

On the File menu, point to Open, and then click Project/Solution.

If you are using Visual Basic, in the Open Project dialog box, go to the
folder E:\Labfiles\Starter\VB\BulkData\ConnectedWCF, and then
double-click ConnectedWCF.sln.

If you are using Visual C#, in the Open Project dialog box, go to the
folder E:\Labfiles\Starter\CS\BulkData\ConnectedWCF, and then
double-click ConnectedWCF.sln.

4.

In Solution Explorer, expand the PatientManagementService project, rightclick the PatientManagementServiceImageContract file, and then click View
Code.

5.

Locate the TODO 5 comment, and then add the following code to the
PatientManagementServiceImageContract interface.
[Visual Basic]
' TODO 5
<OperationContract()> _
Function GetXrayImage(ByVal patientId As String, _
ByVal type As String) As Byte()

[Visual C#]
// TODO 5
[OperationContract]
byte[] GetXrayImage(string patientId, string type);

6.

In Solution Explorer, under the PatientManagementService project, rightclick the PatientManagementServiceImplementation file, and then click
View Code.

7.

Locate the TODO 6 comment, and then add


PatientManagementServiceImageContract to the list of interfaces
implemented by the PatientManagementServiceImplementation class.
[Visual Basic]
' TODO 6
Public Class PatientManagementServiceImplementation
Implements PatientManagementServiceContract
Implements PatientManagementServiceImageContract

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 7: Improving WCF Service Quality

[Visual C#]
// TODO 6
public class PatientManagementServiceImplementation :
PatientManagementServiceContract,
PatientManagementServiceImageContract

8.

If you are using Visual Basic, click after


PatientManagementServiceImageContract, and then press ENTER. If you are
using Visual C#, right-click PatientManagementServiceImageContract, point
to Implement Interface, and then click Implement Interface.

9.

Locate the GetXrayImage method and modify the code as shown in the
following code.
[Visual Basic]
Public Function GetXrayImage(ByVal patientId As String, _
ByVal type As String) As Byte() Implements _
PatientManagementServiceImageContract.GetXrayImage
Dim memoryStream As MemoryStream = GetImageAsStream(type)
Return memoryStream.ToArray()
End Function

[Visual C#]
public byte[] GetXrayImage(string patientId, string type)
{
MemoryStream memoryStream = GetImageAsStream(type);
return memoryStream.ToArray();
}

f Task 2: Add an endpoint for the contract that uses MTOM encoding
1.

In Solution Explorer, expand the ContosoServicesSelfHostExtConfig project,


right-click app.config, and then click Edit WCF Configuration.

2.

Expand the Services folder, and then expand the


com.contoso.PatientManagementService.PatientManagementServiceImple
mentation node.

3.

Right-click Endpoints, and then click New Service Endpoint.

MCT USE ONLY. STUDENT USE PROHIBITED

L7-138

4.

L7-139

In the Service Endpoint pane on the right side, configure the endpoint as
follows:

Name: PMIService_WS

Address: PatientManagementServiceImages

Binding: wsHttpBinding

Contract:
com.contoso.PatientManagementService.PatientManagementServiceIm
ageContract

5.

In the Configuration pane, right-click Bindings, and then click New Binding
Configuration.

6.

In the Create a New Binding dialog box, click wsHttpBinding, and then click
OK.

7.

In the right pane, configure the binding as follows:

Name: WebServiceMtomBindingConfig

MessageEncoding: Mtom

8.

In the Configuration pane, click the PMIService_WS endpoint. In the right


pane, set the BindingConfiguration property to
WebServiceMtomBindingConfig.

9.

In the WCF Service Configuration Editor window, on the File menu, click
Save.

10. Close the WCF Service Configuration Editor window.


11. In Solution Explorer, right-click Solution 'Connected WCF', and then click
Rebuild Solution.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 7: Improving WCF Service Quality

f Task 3: Add code to the client to call the new operation


1.

On the Start menu, point to All Programs, point to Accessories, and then
click Windows Explorer.

2.

In Windows Explorer, move to the following location:

If you are using Visual Basic, go to


E:\Labfiles\Starter\VB\BulkData\ConnectedWCF\ContosoServicesSel
fHostExtConfig\bin\Debug.

If you are using Visual C#, go to


E:\Labfiles\Starter\CS\BulkData\ConnectedWCF\ContosoServicesSel
fHostExtConfig\bin\Debug.

Right-click the file ContosoServicesSelfHostExtConfig.exe, and then click


Run as Administrator.
3.

In the User Account Control dialog box, click Allow.

4.

In the Windows Security Alert dialog box, click Unblock.

5.

Switch to Visual Studio 2008.

6.

In Solution Explorer, expand the ConsultantClient project, expand the


Service References folder, right-click PatientManagementServiceReference,
and then click Update Service Reference.

7.

Switch to the ContosoServicesSelfHostExtConfig console window, and then


press ENTER to close the service host application.

8.

Switch to Visual Studio 2008.

9.

In Solution Explorer, in the ConsultantClient project, right-click the


ConsultantForm file, and then click View Code.

10. Locate the TODO 7 comment in the GetImageStreamFromBytes method, and


then make the following changes to the code:

Remove the existing line of code that throws a


NotImplementedException.

MCT USE ONLY. STUDENT USE PROHIBITED

L7-140

L7-141

Add the following code to this method.

[Visual Basic]
Private Function GetImageStreamFromBytes(ByVal typeOfXray As
String) _
As MemoryStream
' TODO 7
Dim patientManagementServiceImages As _
PatientManagementServiceImageContract = New _
PatientManagementServiceImageContractClient()
Dim imageBytes As Byte() = _
patientManagementServiceImages.GetXrayImage(PatientId.Text,
_
typeOfXray)
Return New MemoryStream(imageBytes)
End Function

[Visual C#]
private MemoryStream GetImageStreamFromBytes(string typeOfXray)
{
// TODO 7
PatientManagementServiceImageContract
patientManagementServiceImages =
new PatientManagementServiceImageContractClient();
byte[] imageBytes =
patientManagementServiceImages.GetXrayImage(PatientId.Text,
typeOfXray);
return new MemoryStream(imageBytes);
}

11. Locate the TODO 8 comment in the GetImage_Click method. Add the
following line of code to the method.
[Visual Basic]
' TODO 8
imageStream.Close()

[Visual C#]
// TODO 8
imageStream.Close();

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 7: Improving WCF Service Quality

f Task 4: Configure and run the client


1.

In Solution Explorer, in the ConsultantClient project, right-click app.config,


and then click Edit WCF Configuration.

2.

Expand the Client folder, expand the Endpoints folder, and then click
PMIService_WS and verify that this endpoint already has a binding
configuration named PMIService_WS.

3.

In the Configuration pane, expand the Bindings folder, and then click
PMIService_WS (wsHttpBinding). In the wsHttpBinding : PMIService_WS
pane, do the following:

Examine the value of the MessageEncoding and verify that it is already set
to Mtom.

Set the value of the MaxReceivedMessageSize property to 12000000 (12


million).

Set the value of the MaxArrayLength under ReaderQuotasProperties to


12000000 (12 million).

4.

On the File menu, click Save.

5.

Close the WCF Service Configuration Editor window.

6.

On the Debug menu, click Start Debugging.

7.

In the Windows Security Alert message box, click Unblock.

8.

In the Consultant Client window, click the Patient Information tab. On the
Patient Information tab, click Chest, and then click Get Image.
Verify that an X-ray image is displayed on the Patient Information tab.

9.

On the Debug menu, click Stop Debugging.

f Task 5: View the raw MTOM messages


1.

On the Windows Start menu, point to All Programs, point to Microsoft


Windows SDK v6.0A, point to Tools, and then click Service Trace Viewer.

2.

In the Service Trace Viewer, on the File menu, click Add.

3.

In the Open dialog box, go to the E:\LabFiles\logs folder, click the file
messages.svclog, and then click Open.

MCT USE ONLY. STUDENT USE PROHIBITED

L7-142

L7-143

4.

In the Service Trace Viewer, in the left pane, click the Message tab to display a
list of messages passed between the client and the service. This tab lists the
messages by their Action values and sorts them in time order.

5.

Click a message with an action of


http://contoso.com/ClinicManagementSystem/2007/10/PatientManagem
entServiceImageContract/GetXrayImage, scrolling down the list if necessary.

Note: You will see each message and response listed twice. This is because the
service has been configured to log each message at the message level and the
transport level.

6.

In the lower-right pane, click the Message tab, and then examine the HTTP
request header. Verify that the WebHeaders element contains a Content-Type
element that in turn contains a string that starts with
multipart/related;type="application/xop+xml". This confirms that it is using
MTOM encoding.

7.

Click a message with an action of


http://contoso.com/ClinicManagementSystem/2007/10/PatientManagem
entServiceImageContract/GetXrayImageResponse.

8.

In the lower-right pane, click the Message tab, and then examine the SOAP
message. Scroll down to find the SOAP body and verify that its <s:Body>
element contains an empty GetXrayImageResult element. This is because the
content is in a separate MIME part.

f Task 6: Add a streamed method to the contract


1.

In Solution Explorer, under the PatientManagementService project, rightclick the PatientManagementServiceImageContract file, and then click View
Code.

2.

Locate the TODO 5 comment, and then add the following WCF operation.
[Visual Basic]
' TODO 5
<OperationContract()> _
Function StreamXrayImage(ByVal patientId As String, ByVal type As _
String) As Stream

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 7: Improving WCF Service Quality

[Visual C#]
// TODO 5
[OperationContract]
Stream StreamXrayImage(string patientId, string type);

3.

Locate the TODO 9 comment and add the following statement.


[Visual Basic]
' TODO 9
Imports System.IO

[Visual C#]
// TODO 9
using System.IO;

4.

In Solution Explorer, under the PatientManagementService project, rightclick the PatientManagementServiceImplementation file, and then click
View Code.

5.

Locate the TODO 6 comment. If you are using Visual Basic, click after
PatientManagementServiceImageContract, and then press ENTER. If you are
using Visual C#, right-click PatientManagementServiceImageContract, point
to Implement Interface, and then click Implement Interface.

6.

Locate the StreamXrayImage method, and then make the following changes
to the code.
[Visual Basic]
Public Function StreamXrayImage(ByVal patientId As String, _
ByVal type As String) As System.IO.Stream Implements _
PatientManagementServiceImageContract.StreamXrayImage
Dim imagePath As String = "..\..\DataFiles\xray_" & type &
".bmp"
Return File.OpenRead(imagePath)
End Function

[Visual C#]
public Stream StreamXrayImage(string patientId, string type)
{
string imagePath = @"..\..\DataFiles\xray_" + type + ".bmp";
return File.OpenRead(imagePath);
}

MCT USE ONLY. STUDENT USE PROHIBITED

L7-144

L7-145

f Task 7: Change the service-side endpoint to support streaming


1.

In Solution Explorer, expand the ContosoServicesSelfHostExtConfig project,


right-click app.config, and then click Edit WCF Configuration.

2.

Expand the Services folder, and then expand the


com.contoso.PatientManagementService.PatientManagementServiceImple
mentation node.

3.

Right-click Endpoints, and then click the New Service Endpoint. In the
Service Endpoint pane on the right side, configure the endpoint as follows:

Name: PMIService_TCP

Address: PatientManagementServiceImages

Binding: netTcpBinding

Contract:
com.contoso.PatientManagementService.PatientManagementServiceIm
ageContract

4.

In the Configuration pane, right-click Bindings, and then click New Binding
Configuration.

5.

In the Create a New Binding dialog box, click netTcpBinding, and then click
OK.

6.

In the right pane, configure the binding as follows:

Name: NetTcpStreamingBindingConfig

TransferMode: Streamed

7.

In the Configuration pane, click the PMIService_TCP endpoint. In the right


pane, set the BindingConfiguration to NetTcpStreamingBindingConfig.

8.

In the WCF Service Configuration Editor window, on the File menu, click
Save.

9.

Close the WCF Service Configuration Editor window.

10. In Solution Explorer, right-click Solution 'Connected WCF', and then click
Rebuild Solution.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 7: Improving WCF Service Quality

f Task 8: Change the client code to call the new operation


1.

Switch to Windows Explorer.

2.

In Windows Explorer, go to the following location:

If you are using Visual Basic, go to


E:\Labfiles\Starter\VB\BulkData\ConnectedWCF\
ContosoServicesSelfHostExtConfig\bin\Debug.

If you are using Visual C#, go to


E:\Labfiles\Starter\CS\BulkData\ConnectedWCF\
ContosoServicesSelfHostExtConfig\bin\Debug.

Right-click the file ContosoServicesSelfHostExtConfig.exe, and click Run as


Administrator.
3.

In the User Account Control dialog box, click Allow.

4.

In the Windows Security Alert dialog box, click Unblock.

5.

In Solution Explorer, expand the ConsultantClient project, expand the


Service References folder, right-click PatientManagementServiceReference,
and then click Update Service Reference.

6.

Return to the ContosoServicesSelfHostExtConfig console window, and then


press ENTER to close the service host.

7.

In Solution Explorer, in the ConsultantClient project, right-click the


ConsultantForm file, and then click View Code.

8.

Locate the TODO 10 comment in the GetImageStream method, and then


modify the method as shown in the following code.
[Visual Basic]
Private Function GetImageStream(ByVal typeOfXray As String) As
Stream
' TODO 10
Dim patientManagementServiceImages As _
PatientManagementServiceImageContract = _
New
PatientManagementServiceImageContractClient("PMIService_TCP")
Return _
patientManagementServiceImages. _
StreamXrayImage(PatientId.Text, typeOfXray)
End Function

MCT USE ONLY. STUDENT USE PROHIBITED

L7-146

L7-147

[Visual C#]
private Stream GetImageStream (string typeOfXray)
{
// TODO 10
PatientManagementServiceImageContract
patientManagementServiceImages =
new
PatientManagementServiceImageContractClient("PMIService_TCP");
return
patientManagementServiceImages.
StreamXrayImage(PatientId.Text, typeOfXray);
}

9.

Locate the TODO 11 comment, and then replace the call to


GetImageStreamFromBytes with a call to GetImageStream.
[Visual Basic]
' TODO 11
Dim imageStream As Stream = GetImageStream(typeOfXray)

[Visual C#]
// TODO 11
Stream imageStream = GetImageStream(typeOfXray);

f Task 9: Configure and run the client


1.

In Solution Explorer, under the ConsultantClient project, right-click


app.config, and then click Edit WCF Configuration.

2.

Expand the Endpoints folder under the Client folder, and then click
PMIService_TCP.

3.

In the Configuration pane, expand the Bindings folder, and then click
PMIService_TCP (netTcpBinding). In the netTcpBinding : PMIService_TCP
pane, do the following:

Examine the value of the TransferMode and verify that it is already set to
Streamed.

Set the value of the MaxReceivedMessageSize property to 12000000 (12


million).

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 7: Improving WCF Service Quality

4.

In the WCF Service Configuration Editor window, on the File menu, click
Save.

5.

Close the WCF Service Configuration Editor window.

6.

On the Debug menu, click Start Debugging.

7.

In the Consultant Client window, click the Patient Information tab. On the
Patient Information tab, click Chest, and then click Get Image.
You should see an X-ray image displayed on the Patient Information tab.

8.

On the Debug menu, click Stop Debugging.

f Task 10: View the raw streamed messages


1.

Switch to the Service Trace Viewer.

2.

In the Service Trace Viewer, on the File menu, click Open.

3.

In the Open dialog box, go to the E:\LabFiles\logs folder, click the file
messages.svclog, and then click Open.

4.

In the Service Trace Viewer, in the left pane, click the Message tab to display a
list of messages passed between the client and the service. This tab lists the
messages by their Action values and sorts them in time order.

5.

Click a message with an action of


http://contoso.com/ClinicManagementSystem/2007/10/PatientManagem
entServiceImageContract/StreamXrayImageResponse, scrolling down the
list if necessary.

Note: You will see each message and response listed twice. This is because the
service has been configured to log each message at the message level and the
transport level.

MCT USE ONLY. STUDENT USE PROHIBITED

L7-148

6.

L7-149

In the lower-right pane, click the Message tab, and then examine the SOAP
message. Scroll down to find the SOAP body and verify that its <s:Body>
element contains stream.

Results: After completing this exercise, you have seen how to pass bulk binary data
between a WCF client and service.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Improving Service Quality

Module 8: Implementing WCF Security

Lab: Protecting a Service


Logon Information:

Virtual Machine: 6461A-LON-DEV-08

User Name: Student

Password: Pa$$w0rd

Estimated time: 40 minutes

L8-151

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Protecting a Service

Module 8: Implementing WCF Security

Exercise 1: Applying Security for Internal Network


Communication
Scenario
The clinic management system allows users to access sensitive patient data, and
the system then passes that data across the clinic network. You need to be sure that
only authorized users can access the patient data and that this data is encrypted at
all times when in transit.
In this exercise, you will start to secure the connections made by the clinic
administration client application. This requires you to apply message-level security
to a message exchange to sign and encrypt message contents. You will then ensure
that only authorized users can access patient data.
The main tasks for this exercise are as follows:
1.

Start the 6461-LON-DEV-08 virtual machine and log on as Student.

2.

Apply message-level encryption to a service.

3.

Apply message-level encryption to a client.

4.

Use message logging to see the effects of message-level encryption on the


message contents.

5.

Display caller credentials in the service.

6.

Provide Windows credentials from the client to the service.

f Task 1: Start the 6461-LON-DEV-08 virtual machine and log on as


Student
1.

Open the Virtual Server Remote Control Client, and then double-click 6461LON-DEV-08.

2.

Log on to 6461-LON-DEV-08 as Student using the password Pa$$w0rd.

f Task 2: Apply message-level encryption to a service


1.

On the taskbar, click Start, point to All Programs, point to Microsoft Visual
Studio 2008, right-click Microsoft Visual Studio 2008, and then click Run as
administrator.

2.

In the User Account Control dialog box, click Continue.

MCT USE ONLY. STUDENT USE PROHIBITED

L8-152

3.

On the File menu, point to Open, and then click Project/Solution.

4.

Do one of the following:

L8-153

If you are using Microsoft Visual Basic development system, in the


Open Project dialog box, go to the folder
E:\Labfiles\Starter\VB\InternalNetwork\ConnectedWCF, and then
double-click ConnectedWCF.sln.

If you are using Microsoft Visual C# development tool, in the Open


Project dialog box, go to the folder
E:\Labfiles\Starter\CS\InternalNetwork\ConnectedWCF, and then
double-click ConnectedWCF.sln.

5.

In Solution Explorer, expand the ContosoServicesSelfHostExtConfig project,


right-click the app.config file (for Visual Basic) or the App.config file (for
Visual C#), and then click Edit WCF Configuration.

6.

In the WCF Service Configuration Editor, right-click the Bindings folder, and
then click New Binding Configuration.

7.

In the Create a New Binding dialog box, select the netTcpBinding binding
type, and then click OK.
The WCF Service Configuration Editor generates a binding configuration with
the default settings for the NetTcpBinding binding.

8.

In the right pane of the WCF Service Configuration Editor, change the Name
property of the binding to NetTcpSecureMessageBindingConfig.

9.

Click the Security tab.

10. Change the Mode property to Message. Under MessageSecurityProperties,


change the AlgorithmSuite property to Basic128. Leave the
MessageClientCredentialType property set to Windows.

Note: These settings cause the binding to apply message-level security so that the
message contents will be encrypted and signed as defined by WS-Security. Users will
be expected to provide a valid Microsoft Windows operating system user name
and password for the credentials, and then all messages will be encrypted by a 128bit algorithm, which is relatively quick, but it provides sufficient privacy for messages
inside an organization.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Protecting a Service

Module 8: Implementing WCF Security

11. In the left pane of the WCF Service Configuration Editor, in the Services
folder, expand the
com.contoso.AppointmentService.AppointmentServiceImplementation
service, expand the Endpoints folder, and then click the APService_TCP
endpoint.
12. In the right pane, set the BindingConfiguration property to
NetTcpSecureMessageBindingConfig.
13. On the File menu, click Save.
14. On the File menu, click Exit.

f Task 3: Apply message-level encryption to a client


1.

In Solution Explorer, expand the ClinicAdminClient project, right-click the


app.config file (for Visual Basic) or the App.config file (for Visual C#), and
then click Edit WCF Configuration.

2.

In the WCF Service Configuration Editor, expand the Bindings folder, and
then click the APService_TCP binding configuration.

3.

Click the Security tab.

4.

Change the Mode property to Message. Under MessageSecurityProperties,


change the AlgorithmSuite property to Basic128. Leave the
MessageClientCredentialType property set to Windows.

5.

On the File menu, click Save.

6.

On the File menu, click Exit.

7.

In Solution Explorer, right-click Solution 'Connected WCF', and then click


Rebuild Solution. Ensure that the solution builds successfully before
continuing.

f Task 4: Use message logging to see the effects of message-level


encryption on the message contents
1.

On the Debug menu, click Start Debugging.

2.

In the Windows Security Alert dialog box, click Unblock.

3.

On the Clinic Administration Client form, click the Create Appointment tab.

4.

Click Find Slots, and then make sure that a list of available slots displays.

MCT USE ONLY. STUDENT USE PROHIBITED

L8-154

L8-155

5.

On the Debug menu, click Stop Debugging.

6.

On the taskbar, click Start, point to All Programs, point to Microsoft


Windows SDK v6.0A, point to Tools, and then click Service Trace Viewer.

7.

In the Service Trace Viewer, on the File menu, click Add.

8.

In the Open dialog box, go to the E:\LabFiles\logs folder, click the file
messages.svclog, and then click Open.

9.

In the Service Trace Viewer, in the left pane, click the Message tab to display a
list of messages passed between the client and the service. This tab lists the
messages by their Action values and sorts them in time order.

10. Click the most recent message with an action of


http://contoso.com/ClinicManagementSystem/2007/10/AppointmentServ
iceContract/ListAvailableAppointmentTimesResponse, scrolling down the
list if necessary.

Note: You will see each message and response listed twice. This is because the
service has been configured to log each message at the message level and the
transport level.

11. In the lower-right pane, click the Message tab, and then examine the SOAP
message that was passed from the transport-level to the message-level. Scroll
down to find the SOAP body, and then verify that it contains an
<e:CipherValue> element.
12. In the left pane, click the penultimate message with an action of
http://contoso.com/ClinicManagementSystem/2007/10/AppointmentServ
iceContract/ListAvailableAppointmentTimesResponse. In the lower-right
pane, scroll down again to the SOAP message body, and then verify that it
contains an unencrypted list of available appointment times.
13. In the Service Trace Viewer, on the File menu, click Exit.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Protecting a Service

Module 8: Implementing WCF Security

f Task 5: Display caller credentials in the service


1.

In Solution Explorer, expand the AppointmentService project, right-click the


AppointmentServiceImplementation class file, and then click View Code.

2.

In the Code Editor window for the AppointmentServiceImplementation class


file, locate the TODO 1 comment, and then add the
ShowSecurityInformation method shown in the following code example. This
method writes a message to the console to show the identity under which the
operation is running.
[Visual Basic]
...
' TODO 1.
Private Shared Sub ShowSecurityInformation(ByVal methodName As
String)
Console.WriteLine("{0} thread principal is {1}", methodName, _
Thread.CurrentPrincipal.Identity.Name)
Console.WriteLine("{0} security context primary identity is "
_
& "{1}", methodName, _
ServiceSecurityContext.Current.PrimaryIdentity.Name)
Console.WriteLine("{0} security context windows identity is " _
& "{1}", methodName, _
ServiceSecurityContext.Current.WindowsIdentity.Name)
End Sub
...

[Visual C#]
// TODO 1
private static void ShowSecurityInformation(string methodName)
{
Console.WriteLine("{0} thread principal is {1}",
methodName,
Thread.CurrentPrincipal.Identity.Name);
Console.WriteLine("{0} security context primary identity is
{1}",
methodName,
ServiceSecurityContext.Current.PrimaryIdentity.Name);
Console.WriteLine("{0} security context windows identity is
{1}",
methodName,
ServiceSecurityContext.Current.WindowsIdentity.Name);
}

MCT USE ONLY. STUDENT USE PROHIBITED

L8-156

3.

L8-157

Locate the TODO 2 comment in the ListAvailableAppointmentTimes


method, and then add a statement to call the ShowSecurityInformation
method, passing "ListAvailableAppointmentTimes" as the parameter.
[Visual Basic]
...
' TODO 2.
ShowSecurityInformation("ListAvailableAppointmentTimes")
...

[Visual C#]
// TODO 2
ShowSecurityInformation("ListAvailableAppointmentTimes");

4.

On the Debug menu, click Start Debugging.

5.

On the Clinic Administration Client form, click the Create Appointment tab.

6.

Click Find Slots.

7.

In the console window for the ContosoServicesSelfHostExtConfig


application, verify that the security information displayed shows LONDEV\Student for the thread principal, the primary identity, and the Windows
identity of the request.

8.

In Visual Studio 2008, on the Debug menu, click Stop Debugging.

f Task 6: Provide Windows credentials from the client to the service


1.

In Solution Explorer, expand the ClinicAdminClient project, right-click the


ClinicAdminForm class file, and then click View Code.

2.

In the Code Editor window for the ClinicAdminForm class file, locate the
TODO 3 comment in the findSlots_Click method, and then change the type
of the proxy variable to AppointmentServiceContractClient.
[Visual Basic]
' TODO 3.
Dim proxy As New AppointmentServiceContractClient()

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Protecting a Service

Module 8: Implementing WCF Security

[Visual C#]
// TODO 3
AppointmentServiceContractClient proxy =
new AppointmentServiceContractClient();

3.

Locate the TODO 4 comment, and then add code to explicitly set the
credentials used when calling the service. In this case, this uses an
intentionally fake user name to prove that authentication must take place
correctly.
[Visual Basic]
' TODO 4.
proxy.ClientCredentials.Windows.ClientCredential.UserName = "Fred"
proxy.ClientCredentials.Windows.ClientCredential.Password =
"Secret"
proxy.ClientCredentials.Windows.ClientCredential.Domain =
"TestDomain"

[Visual C#]
// TODO 4
proxy.ClientCredentials.Windows.ClientCredential.UserName = "Fred";
proxy.ClientCredentials.Windows.ClientCredential.Password =
"Secret";
proxy.ClientCredentials.Windows.ClientCredential.Domain =
"TestDomain";

4.

On the Debug menu, click Start Debugging.

5.

On the Clinic Administration Client form, click the Create Appointment tab.

6.

Click Find Slots, and then examine the SecurityNegotiationException


exception that occurs because of the invalid credentials. Verify that it contains
the message "The caller was not authenticated by the service."

7.

In Visual Studio 2008, on the Debug menu, click Stop Debugging.

MCT USE ONLY. STUDENT USE PROHIBITED

L8-158

8.

L8-159

In the Code Editor window for the ClinicAdminForm class file, locate the
TODO 4 comment, and then change the values for the Windows credentials to
valid credentials to prove that the authentication works correctly when
specifying credentials programmatically.
[Visual Basic]
' TODO 4.
proxy.ClientCredentials.Windows.ClientCredential.UserName = _
"LocalAdmin"
proxy.ClientCredentials.Windows.ClientCredential.Password =
"Pa$$w0rd"
proxy.ClientCredentials.Windows.ClientCredential.Domain = "LON-DEV"

[Visual C#]
// TODO 4
proxy.ClientCredentials.Windows.ClientCredential.UserName =
"LocalAdmin";
proxy.ClientCredentials.Windows.ClientCredential.Password =
"Pa$$w0rd";
proxy.ClientCredentials.Windows.ClientCredential.Domain = "LONDEV";

9.

On the Debug menu, click Start Debugging.

10. On the Clinic Administration Client form, click the Create Appointment tab.
11. Click Find Slots.
12. In the console window for the ContosoServicesSelfHostExtConfig
application, verify that the security information displayed shows LONDEV\LocalAdmin for the thread principal, the primary identity, and the
Windows identity of the request.
13. In Visual Studio 2008, on the Debug menu, click Stop Debugging.
14. Close Visual Studio 2008.

Results: After completing this exercise, you have seen how to secure message
contents using message-level security and how to pass Windows credentials from a
client to a service.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Protecting a Service

Module 8: Implementing WCF Security

Exercise 2: Applying Security for Internet Communication


Scenario
The clinic management system allows remote family practitioner administrators to
make appointments for patients. You need to be sure that only authorized users
can make such appointments and that the system encrypts the data when in transit
across the Internet.
In this exercise, you will secure the connections made by the family practitioner
client application to the appointment service. This requires you to apply transportlevel security to a message exchange that encrypts the entire communication,
including message headers. You will then ensure that only authorized users can
access patient data.
The main tasks for this exercise are as follows:
1.

Create and install an SSL certificate on IIS.

2.

Create an IIS-based Web site to host your service.

3.

Add the service functionality to your IIS-based Web site.

4.

Call the SSL-protected service.

f Task 1: Create and install an SSL certificate on IIS


1.

On the taskbar, click Start, point to All Programs, point to Microsoft Visual
Studio 2008, point to Visual Studio Tools, right-click Microsoft Visual
Studio 2008 Command Prompt, and then click Run as administrator.

2.

In the User Account Control dialog box, click Continue.

3.

In the command prompt window, type the following command:


makecert -sr LocalMachine -ss My -n CN=LON-DEV -sky exchange -sk
HTTPS-Key

You should see the message "Succeeded" if makecert created the certificate
correctly. If you have any problems with makecert, run it with the /? flag to
see its options.
4.

On the taskbar, click Start, click Control Panel, click System and
Maintenance, click Administrative Tools, and then double-click Internet
Information Services (IIS) Manager.

5.

In the User Account Control dialog box, click Continue.

MCT USE ONLY. STUDENT USE PROHIBITED

L8-160

L8-161

6.

In the Internet Information Services (IIS) Manager, in the left pane, expand
the LON-DEV node, expand Web Sites, right-click Default Web Site, and then
click Edit Bindings.

7.

In the Web Site Bindings dialog box, click Add.

8.

In the Add Web Site Binding dialog box, set Type to https, set the SSL
certificate to LON-DEV, and then click OK.

9.

In the Web Site Bindings dialog box, click Close.

f Task 2: Create an IIS-based Web site to host your service


1.

On the taskbar, click Start, point to All Programs, point to Microsoft Visual
Studio 2008, right-click Microsoft Visual Studio 2008, and then click Run as
administrator

2.

In the User Account Control dialog box, click Continue.

3.

On the File menu, point to Open, and then click Project/Solution.

4.

Do one of the following:

If you are using Visual Basic, in the Open Project dialog box, go to the
folder E:\Labfiles\Starter\VB\Internet\ConnectedWCF, and then
double-click ConnectedWCF.sln.

If you are using Visual C#, in the Open Project dialog box, go to the
folder E:\Labfiles\Starter\CS\ Internet\ConnectedWCF, and then
double-click ConnectedWCF.sln.

5.

In Solution Explorer, right-click Solution 'ConnectedWCF', point to Add, and


then click New Web Site.

6.

In the Add New Web Site dialog box, select the WCF Service template. Set the
Location to HTTP and specify the language as follows:

If you are using Visual Basic, set the Language to Visual Basic.

If you are using Visual C#, set the Language to Visual C#.

7.

Click Browse.

8.

In the left pane of the Choose Location dialog box, click Local IIS. In the right
pane, click Default Web Site, and then click the Create New Virtual
Directory icon in the upper-right corner of the dialog box.

9.

In the New Virtual Directory dialog box, enter ContosoInternetGateway as


the Alias name.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Protecting a Service

Module 8: Implementing WCF Security

10. Click Browse next to the Folder box.


11. In the Browse For Folder dialog box, do one of the following:

If you are using Visual Basic, go to the folder


E:\Labfiles\Starter\VB\Internet\ConnectedWCF.

If you are using Visual C#, go to the folder E:\Labfiles\Starter\CS\


Internet\ConnectedWCF.

12. Click the New Folder icon in the toolbar.


13. Rename the new folder ContosoInternetGateway, and then press ENTER.
14. In the Browse For Folder dialog box, click Select Folder.
15. In the New Virtual Directory dialog box, click OK.
16. In the Choose Location dialog box, click the ContosoInternetGateway folder.
Select the Use Secure Sockets Layer check box at the bottom of the dialog
box, and then click Open.
17. In the Add New Web Site dialog box, verify that the address for the new Web
site is https://localhost/ContosoInternetGateway, and then click OK.
18. Switch to the Internet Information Services (IIS) Manager.
19. In the left pane, expand the LON-DEV node, expand Web Sites, expand
Default Web Site, and then click the ContosoInternetGateway node.
20. At the bottom of the main pane, click Features View.
21. In the IIS section of the main panel, double-click SSL Settings.
22. In the SSL Settings pane, select Require SSL, but leave all the other properties
at their default values.
23. In the right pane, click Apply. You should see the message "The changes have
been successfully saved".
24. In the Internet Information Services (IIS) Manager navigation bar, click Back,
and then in the main panel, double-click Authentication.
25. In the Authentication pane, click Basic Authentication. In the right pane,
click Enable.
26. Close the Internet Information Services (IIS) Manager.

MCT USE ONLY. STUDENT USE PROHIBITED

L8-162

L8-163

f Task 3: Add the service functionality to your IIS-based Web site


1.

Switch to Microsoft Visual Studio 2008.

2.

In Solution Explorer, expand the


https://localhost/ContosoInternetGateway/ Web site.

3.

Expand the App_Code folder, and do one of the following:

If you are using Visual Basic, delete the files IService.vb and Service.vb.

If you are using Visual C#, delete the files IService.cs and Service.cs.

4.

Right-click https://localhost/ContosoInternetGateway/, and then click Add


Reference.

5.

In the Add Reference dialog box, click the Projects tab, click
AppointmentService, and then click OK.

6.

In Solution Explorer, rename Service.svc as AppointmentService.svc.

7.

Right-click the AppointmentService.svc file, and then click View Markup. In


the code view window, remove the CodeBehind attribute, and then change the
value of the Service attribute to
com.contoso.AppointmentService.AppointmentServiceImplementation.
[Visual Basic]
<%@ ServiceHost Language="vb" Debug="true"
Service="com.contoso.AppointmentService.AppointmentServiceImplement
ation" %>

[Visual C#]
<%@ ServiceHost Language="C#" Debug="true"
Service="com.contoso.AppointmentService.AppointmentServiceImplement
ation" %>

8.

In Solution Explorer, right-click web.config, and then click Edit WCF


Configuration.

9.

Expand the Services folder, and then click Service. In the right pane, set the
Name value to
com.contoso.AppointmentService.AppointmentServiceImplementation.

10. In the left pane, expand the Endpoints folder under


com.contoso.AppointmentService.AppointmentServiceImplementation,
and then click the first (Empty Name) node.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Protecting a Service

Module 8: Implementing WCF Security

11. Change the Binding to basicHttpBinding, change the contract to


com.contoso.AppointmentService.AppointmentServiceContract, and then
set the name to APService_HTTPS. Leave the Address empty.
12. In the left pane, click the second (Empty Name) node, change the binding to
mexHttpsBinding, and then set the name to Metadata_HTTPS.
13. In the left pane, right-click the Bindings folder, and then click New Binding
Configuration. In the Create a New Binding dialog box, click
basicHttpBinding, and then click OK.
14. In the right pane, set the Name property of the binding to
BasicHttpSecureTransportBindingConfig.
15. Click the Security tab.
16. Change the Mode property to Transport. Under
TransportSecurityProperties, set the TransportClientCredentialType to
None.
17. In the left pane, click the APService_HTTPS endpoint.
18. In the right pane, set the BindingConfiguration property to
BasicHttpSecureTransportBindingConfig.
19. In the left pane, expand the Advanced folder, expand the Service Behaviors
folder, expand the ServiceBehavior folder, and then click serviceMetadata. In
the right pane, change the value of HttpsGetEnabled to true and the value of
HttpGetEnabled to false.
20. On the File menu, click Save.
21. On the File menu, click Exit.
22. In Solution Explorer, right-click Solution 'Connected WCF', and then click
Rebuild Solution. Ensure that the solution builds successfully.
23. Start Internet Explorer, and then go to the URL
https://localhost/ContosoInternetGateway/AppointmentService.svc.
Internet Explorer will display the message "There is a problem with this
Website's security certificate." Click Continue to this Website. Verify that you
see the service test page for the AppointmentServiceImplementation.
24. Close Internet Explorer.

MCT USE ONLY. STUDENT USE PROHIBITED

L8-164

L8-165

f Task 4: Call the SSL-protected service


1.

Switch to Visual Studio 2008.

2.

In Solution Explorer, expand the FPAdminClient project.

3.

Right-click the FPAdminForm class file, and then click View Code.

4.

In the GetAppointmentServiceProxy method, locate the TODO 5 comment,


and then make the following changes:
a.

Change the URL of the endpoint address to


https://localhost/ContosoInternetGateway/AppointmentService.svc.

b.

Alter the BasicHttpBinding to pass the value


BasicHttpSecurityMode.Transport into the constructor.

Your code should now look like the following.


[Visual Basic]
' TODO 5
Dim address As New _
EndpointAddress("https://localhost/ContosoInternetGateway/" _
& "AppointmentService.svc")
Dim binding As New
BasicHttpBinding(BasicHttpSecurityMode.Transport)

[Visual C#]
// TODO 5
EndpointAddress address = new
EndpointAddress("https://localhost/ContosoInternetGateway/"
+ "AppointmentService.svc");
BasicHttpBinding binding =
new
BasicHttpBinding(BasicHttpSecurityMode.Transport);

5.

In Solution Explorer, right-click app.config, and then click Edit WCF


Configuration.

6.

In the Service Configuration Editor, expand the Bindings folder, and then
click APService_HTTP.

7.

In the right pane, click the Security tab.

8.

Change the Mode property to Transport. Under


TransportSecurityProperties, set the TransportClientCredentialType to
None.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Protecting a Service

Module 8: Implementing WCF Security

9.

On the File menu, click Save.

10. On the File menu, click Exit.


11. On the Debug menu, click Start Debugging.
12. On the Clinic Administration Client form, click Find Slots. Verify that the
application throws an exception with the message "Could not establish a trust
relationship for the SSL/TLS secure channel with authority 'localhost'."
13. In Visual Studio 2008, on the Debug menu, click Stop Debugging.
14. In Solution Explorer, right-click the FPAdminForm class file, and then click
View Code. Locate the TODO 5 comment, and then add the following
statement that calls the Enact method on PermissiveCertificatePolicy,
passing the name used in the certificate: "CN=LON-DEV".
[Visual Basic]
' TODO 5
PermissiveCertificatePolicy.Enact("CN=LON-DEV")

[Visual C#]
// TODO 5
PermissiveCertificatePolicy.Enact("CN=LON-DEV");

15. On the Debug menu, click Start Without Debugging.


16. On the Clinic Administration Client form, click the Create Appointment tab.
17. Click Find Slots. Verify that no exception occurs and that the list of possible
appointment times appears.
18. Close the FP Appointment Client form.

Results: After completing this exercise, you have seen how to secure message
contents across the Internet using transport-level security.

MCT USE ONLY. STUDENT USE PROHIBITED

L8-166

Module 9: Implementing Transactions

Lab: Implementing Transactions


for a Service
Logon Information:

Virtual Machine: 6461A-LON-DEV-09

User Name: Student

Password: Pa$$w0rd

Estimated time: 40 minutes

L9-167

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Transactions for a Service

Module 9: Implementing Transactions

Exercise 1: Control the Flow of a Transaction from Client to


Service
Scenario
You are a developer for the Contoso Clinic Management System. The requirement
for making an appointment says that the creation of the appointment and the
issuing of the appointment letter must be performed together.
In this exercise, you will flow a transaction from client to service to ensure that
appointments are not marked as taken unless subsequent processing succeeds.
The main tasks for this exercise are as follows:
1.

Start the 6461-LON-DEV-09 virtual machine and log on as Student.

2.

Add transactional requirements to the appointment service contract.

3.

Configure the service to flow transactions.

4.

Configure the client to flow transactions.

5.

Start a transaction from the client.

Ensure that failure in the client transaction rolls back the changes to the
appointment service.

f Task 1: Start the 6461-LON-DEV-09 virtual machine and log on as


Student
1.

Open the Virtual Server Remote Control Client, and then double-click 6461LON-DEV-09.

2.

Log on to 6461-LON-DEV-09 as Student using the password Pa$$w0rd.

f Task 2: Add transactional requirements to the appointment service


contract
1.

On the taskbar, click Start, point to All Programs, point to Microsoft Visual
Studio 2008, right-click Microsoft Visual Studio 2008, and then click Run as
administrator.

2.

In the User Account Control dialog box, click Continue.

3.

On the File menu, point to Open, and then click Project/Solution.

MCT USE ONLY. STUDENT USE PROHIBITED

L9-168

4.

L9-169

Do one of the following:

If you are using Microsoft Visual Basic development system, in the


Open Project dialog box, go to the folder
E:\Labfiles\Starter\VB\TransactionFlow\ConnectedWCF, and then
double-click ConnectedWCF.sln.

If you are using Microsoft Visual C# development tool, in the Open


Project dialog box, go to the folder
E:\Labfiles\Starter\CS\TransactionFlow\ConnectedWCF, and then
double-click ConnectedWCF.sln.

5.

In Solution Explorer, expand the AppointmentService project.

6.

Right-click AppointmentServiceContract, and then click View Code.

7.

In the Code Editor window for the AppointmentServiceContract class file,


locate the TODO 1 comment, and then add the TransactionFlow attribute to
the CreateAppointment operation with a parameter of
TransactionFlowOption.Mandatory.
[Visual Basic]
...
' TODO 1.
<TransactionFlow(TransactionFlowOption.Mandatory)> _
...

[Visual C#]
...
// TODO 1
[TransactionFlow(TransactionFlowOption.Mandatory)]
...

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Transactions for a Service

Module 9: Implementing Transactions

f Task 3: Configure the service to flow transactions


1.

In Solution Explorer, right-click AppointmentServiceImplementation, and


then click View Code.

2.

In the Code Editor window for the AppointmentServiceImplementation class


file, locate the TODO 2 comment, and then add the OperationBehavior
attribute to the CreateAppointment operation with a parameter of
TransactionsScopeRequired set to true.
[Visual Basic]
...
' TODO 2.
<OperationBehavior(TransactionScopeRequired:=True)> _
...

[Visual C#]
...
// TODO 2
[OperationBehavior(TransactionScopeRequired=true)]
...

3.

In Solution Explorer, under the AppointmentService project, right-click


References, and then click Add Reference. In the Add Reference dialog box,
click the .NET tab, click the System.Transactions assembly, and then click
OK.

4.

In the Code Editor window, locate the TODO 3 comment, and then import the
System.Transactions namespace.
[Visual Basic]
...
' TODO 3.
Imports System.Transactions
...

[Visual C#]
...
// TODO 3
using System.Transactions;
...

MCT USE ONLY. STUDENT USE PROHIBITED

L9-170

5.

L9-171

Locate the TODO 4 comment, and then add the ShowTransactionalStatus


method to the AppointmentServiceImplementation class.
[Visual Basic]
...
' TODO 4.
Private Shared Sub ShowTransactionalStatus(ByVal methodName As
String)
If Transaction.Current IsNot Nothing Then
Console.WriteLine("{0} called in transactional scope, " & _
"id is {1}", methodName, _
Transaction.Current.TransactionInformation.LocalIdentifier)
Else
Console.WriteLine("{0} called outside of transactional " &
_
"scope", methodName)
End If
End Sub
...

[Visual C#]
...
// TODO 4
private static void ShowTransactionalStatus(string methodName)
{
if (Transaction.Current != null)
{
Console.WriteLine("{0} called in transactional scope, " +
"id is {1}", methodName,
Transaction.Current.TransactionInformation.LocalIdentifier);
}
else
{
Console.WriteLine("{0} called outside of transactional
scope",
methodName);
}
}
...

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Transactions for a Service

Module 9: Implementing Transactions

6.

Locate the TODO 5 comment, and then invoke the ShowTransactionalStatus


method from inside the CreateAppointment method.
[Visual Basic]
...
' TODO 5.
ShowTransactionalStatus("CreateAppointment")
...

[Visual C#]
...
// TODO 5
ShowTransactionalStatus("CreateAppointment");
...

7.

In Solution Explorer, expand the ContosoServicesSelfHostExtConfig project,


right-click the app.config file and then click Edit WCF Configuration.

8.

In the Configuration pane of the WCF Configuration Editor, right-click


Bindings, and then click New Binding Configuration.

9.

In the Create a New Binding dialog box, click wsHttpBinding, and then click
OK.

10. In the wsHttpBinding: NewBinding0 pane of the WCF Configuration Editor,


do the following:
a.

On the Binding tab, set the Name property to


WsHttpTransactionalBindingConfig in the (Configuration) category.

b.

On the Binding tab, set the TransactionFlow property to True in the


(General) category.

11. In the Configuration pane of the WCF Configuration Editor, right-click


Bindings, and then click New Binding Configuration.
12. In the Create a New Binding dialog box, select netTcpBinding, and then click
OK.
13. In the netTcpBinding: NewBinding0 pane of the WCF Configuration Editor,
do the following:
a.

On the Binding tab, set the Name property to


NetTcpTransactionalBindingConfig in the (Configuration) category.

b.

On the Binding tab, set the TransactionFlow property to True in the


(General) category.

MCT USE ONLY. STUDENT USE PROHIBITED

L9-172

L9-173

14. In the Configuration pane of the WCF Configuration Editor, expand Services,
expand
com.contoso.AppointmentService.AppointmentServiceImplementation,
and then expand Endpoints.
15. Click the APService_WS entry and select
WsHttpTransactionalBindingConfig as the value of the
BindingConfiguration property.
16. Click the APService_TCP entry and select
NetTcpTransactionalBindingConfig as the value of the
BindingConfiguration property.
17. On the File menu, click Save.
18. On the File menu, click Exit.
19. In Solution Explorer, right-click Solution 'Connected WCF', and then click
Rebuild Solution. Ensure that the solution builds successfully before moving
on.

f Task 4: Configure the client to flow transactions


1.

On the taskbar, click Start, point to All Programs, point to Accessories, and
then click Windows Explorer.

2.

Locate the transactional service host in Windows Explorer:

If you are using Visual Basic, go to the folder


E:\Labfiles\Starter\VB\TransactionFlow\ConnectedWCF\ContosoSer
vicesSelfHostExtConfig\bin\debug.

If you are using Visual C#, go to the folder


E:\Labfiles\Starter\CS\TransactionFlow\ConnectedWCF\ContosoSer
vicesSelfHostExtConfig\bin\debug.

3.

Right-click ContosoServicesSelfHostExtConfig.exe, and then click Run as


administrator.

4.

In the User Account Control dialog box, click Allow.

5.

In the Windows Security Alert dialog box, click Unblock.

6.

Switch to Microsoft Visual Studio 2008 development system. In Solution


Explorer, expand the ClinicAdminClient project.

7.

Expand Service References, right-click AppointmentServiceReference, and


then click Update Service Reference.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Transactions for a Service

Module 9: Implementing Transactions

8.

After the service reference updates, stop the


ContosoServicesSelfHostExtConfig by pressing ENTER in the console
window.

9.

In Visual Studio 2008, in the ClinicAdminClient project, right-click the


app.config file, and then click Edit WCF Configuration.

10. In the Configuration pane of the WCF Configuration Editor, expand Bindings.
11. Click the binding configuration named APService_WS (wsHttpBinding), and
then set the TransactionFlow property to True in the (General) category of
the Binding tab.
12. Click the binding configuration named APService_TCP (netTcpBinding), and
then set the TransactionFlow property to True in the (General) category of
the Binding tab.
13. On the File menu, click Save.
14. On the File menu, click Exit.

f Task 5: Start a transaction from the client


1.

In Solution Explorer, expand the ClinicAdminClient project.

2.

Right-click References, and then click Add Reference. In the Add Reference
dialog box, click the .NET tab, click the System.Transactions assembly, and
then click OK.

3.

In Solution Explorer, right-click ClinicAdminForm, and then click View Code.

4.

In the Code Editor window, locate the TODO 9 comment, and then import the
System.Transactions namespace.
[Visual Basic]
...
' TODO 9.
Imports System.Transactions
...

[Visual C#]
...
// TODO 9
using System.Transactions;
...

MCT USE ONLY. STUDENT USE PROHIBITED

L9-174

5.

L9-175

Locate the TODO 10 comment in the


MakeAppointmentWithClientTransaction method. Wrap the lines of code
that create proxies for the Appointment Service and Patient Letters Service,
and then use these proxies to create an appointment and send a letter in a
TransactionScope. Call Complete() at the end of the scope.
[Visual Basic]
...
' TODO 10.
Using scope As New TransactionScope()
Dim proxy As AppointmentServiceContract = _
GetAppointmentServiceProxy()
appointmentId = proxy.CreateAppointment(patientId, doctorId,
slot)
Dim patientLetterServiceProxy As PatientLetterServiceContract =
_
New PatientLetterServiceContractClient("PLService_HTTP")
'TODO 11.
patientLetterServiceProxy.SendLetter(LetterType. _
ConsultationBooked, patientId, doctorId, slot)
scope.Complete()
End Using
...

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Transactions for a Service

Module 9: Implementing Transactions

[Visual C#]
...
// TODO 10.
using (TransactionScope scope = new TransactionScope())
{
AppointmentServiceContract proxy =
GetAppointmentServiceProxy();
appointmentId = proxy.CreateAppointment(patientId,
doctorId, slot);
PatientLetterServiceContract patientLetterServiceProxy =
new PatientLetterServiceContractClient("PLService_HTTP");
// TODO 11.
patientLetterServiceProxy.SendLetter(LetterType.
ConsultationBooked, patientId, doctorId, slot);
scope.Complete();
}
...

6.

In Solution Explorer, right-click Solution 'Connected WCF', and then click


Rebuild Solution. Ensure that the solution builds successfully before moving
on.

f Task 6: Ensure that failure in the client transaction rolls back the
changes to the appointment service
1.

On the Debug menu, click Start Debugging.

2.

In the Windows Security Alert dialog box, click Unblock.

3.

In the Clinic Administration Client form, click the Create Appointment tab.

4.

Click Find Slots, and then click the first slot on the list. Make a note of the
time for the slot that you have selected. Type the patient ID NH991199Z into
the Patient drop-down list box, and then click Create.

5.

In the dialog box confirming that the appointment has been made, click OK.

6.

Click Find Slots again, and then ensure that the slot you chose is no longer
listed as available.

7.

On the Debug menu, click Stop Debugging.

MCT USE ONLY. STUDENT USE PROHIBITED

L9-176

8.

In Solution Explorer, expand the ClinicAdminClient project.

9.

Right-click ClinicAdminForm, and then click View Code.

L9-177

10. In the Code Editor window for the ClinicAdminForm class file, in the
MakeAppointmentWithClientTransaction method, locate the TODO 11
comment, and then add the following code.
[Visual Basic]
...
' TODO 11.
If causeAnIntentionalError Then
Throw New ApplicationException("This is an intentional error" &
_
"to cause problems for a transaction")
End If
...

[Visual C#]
...
// TODO 11
if (causeAnIntentionalError)
{
throw new ApplicationException("This is an intentional error "
+
"to cause problems for a transaction");
}
...

11. In Solution Explorer, right-click Solution 'Connected WCF', and then click
Rebuild Solution.
12. On the Debug menu, click Start Debugging.
13. In the Clinic Administration Client form, click the Create Appointment tab.
14. Click Find Slots, and then click to select the first slot on the list. Make a note
of which slot you have selected. Type the patient ID NH991199Z into the
Patient drop-down list box, and then click Create.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Transactions for a Service

Module 9: Implementing Transactions

15. In the dialog box displaying the error message, click OK.
16. Click Find Slots again, and then verify that the slot you chose is still available.
This proves that the effects of the CreateAppointment operation have been
rolled back because of this client-side exception that aborts the transaction.
17. On the Debug menu, click Stop Debugging.

Results: After completing this exercise, you have seen how to flow a transaction
from a client application to a service and ensure that when the transaction is
aborted, the changes made by the service are rolled back.

MCT USE ONLY. STUDENT USE PROHIBITED

L9-178

L9-179

Exercise 2: Force a Transaction to Start When a Service


Operation Is Called
To avoid the need for transactions on the client, you have decided to refactor the
small piece of transactional workflow code you created earlier so that the server
creates all the transactions.
In this exercise, you will move the workflow code that creates the appointment and
send the patient letter from the client to the Clinic Management Service.
The main tasks for this exercise are as follows:
1.

Add references to the Clinic Management Service so that it can act as a client
for the Appointment Service and Patient Letter Service.

2.

Enable transaction flow on the client endpoints.

3.

Implement the appointment and letter workflow in the Clinic Management


Service.

4.

Replace the client invocations with a call to the Clinic Management Service.

5.

Ensure that failure in the Clinic Management Service transaction rolls back
the changes to the appointment service.

f Task 1: Add references to the Clinic Management Service so that it can


act as a client for the Appointment Service and Patient Letter Service
1.

Switch to Microsoft Visual Studio 2008.

2.

On the File menu, point to Open, and then click Project/Solution.

3.

In the Open Project dialog box, do one of the following:

4.

If you are using Visual Basic, go to


E:\Labfiles\Starter\VB\AutomaticTransactions\ConnectedWCF, and
then double-click ConnectedWCF.sln.

If you are using Visual C#, go to


E:\Labfiles\Starter\CS\AutomaticTransactions\ConnectedWCF, and
then double-click ConnectedWCF.sln.

In Solution Explorer, right-click Solution 'Connected WCF', and then click


Rebuild Solution.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Transactions for a Service

Module 9: Implementing Transactions

5.

Switch to Windows Explorer, and then locate the service host executable file:

If you are using Visual Basic, go to the folder


E:\Labfiles\Starter\VB\AutomaticTransactions\ConnectedWCF\Cont
osoServicesSelfHostExtConfig\bin\debug.

If you are using Visual C#, go to the folder


E:\Labfiles\Starter\CS\AutomaticTransactions\ConnectedWCF\Cont
osoServicesSelfHostExtConfig\bin\debug.

6.

Right-click ContosoServicesSelfHostExtConfig.exe, and then click Run as


administrator.

7.

In the User Account Control dialog box, click Allow.

8.

In the Windows Security Alert dialog box, click Unblock.

9.

Switch to Visual Studio 2008. In Solution Explorer, right-click the


ClinicManagementService project, and then click Add Service Reference.

10. In the Add Service Reference dialog box, perform the following tasks:
a.

In the Address box, type http://localhost:8001/Contoso

b.

Click Go.

c.

In the Namespace box, type PatientLetterServiceReference

d. Click OK.
11. Right-click Service References, and then click Add Service Reference.
12. In the Add Service Reference dialog box, do the following:
a.

Type http://localhost:8000/Contoso into the Address box

b.

Click Go

c.

Type AppointmentServiceReference into the Namespace box

d. Click OK
13. Stop the ContosoServicesSelfHostExtConfig by pressing ENTER in the
console window.
14. In Solution Explorer, expand the ClinicManagementService project.
15. Right-click on the app.config file and click Delete.
16. Right-click ClinicManagementServiceImplementation, and then click View
Code.

MCT USE ONLY. STUDENT USE PROHIBITED

L9-180

L9-181

17. Locate the TODO 12 comment, and then import the


com.contoso.ClinicManagementService.AppointmentServiceReference and
com.contoso.ClinicManagementService.PatientLetterServiceReference
namespaces.
[Visual Basic]
...
' TODO 12.
Imports Com.contoso.ClinicManagementService. _
AppointmentServiceReference
Imports com.contoso.ClinicManagementService. _
PatientLetterServiceReference
...

[Visual C#]
...
// TODO 12
using
com.contoso.ClinicManagementService.AppointmentServiceReference;
using com.contoso.ClinicManagementService.
PatientLetterServiceReference;
...

f Task 2: Enable transaction flow on the appointment service client


endpoint
1.

In Solution Explorer, in the ContosoServicesSelfHostExtConfig project, rightclick the app.config file, and then click Edit WCF Configuration.

2.

In the Configuration pane of the WCF Configuration Editor, expand Bindings.

3.

Click the binding configuration named APService_TCP, and then verify that
the TransactionFlow property is set to True in the (General) category of the
Binding tab.

4. On the File menu, click Save.


5. On the File menu, click Exit.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Transactions for a Service

Module 9: Implementing Transactions

f Task 3: Implement the appointment and letter workflow in the Clinic


Management Service
1.

In Solution Explorer, expand the ClinicManagementService project.

2.

Right-click ClinicManagementServiceContract, and then click View Code.

3.

In the Code Editor window for the ClinicManagementServiceContract class


file, locate the TODO 13 comment, and then add a definition for the
CreateAppointmentWorkflow operation.
[Visual Basic]
...
' TODO 13.
<OperationContract()> _
Function CreateAppointmentWorkflow(ByVal patientId As String, _
ByVal doctorId As String, ByVal slot As DateTime, ByVal _
causeAnIntentionalError As Boolean) As String
...

[Visual C#]
// TODO 13
[OperationContract]
string CreateAppointmentWorkflow(string patientId, string doctorId,
DateTime slot, bool causeAnIntentionalError);

4.

In Solution Explorer, expand the ClinicAdminClient project.

5.

Right-click ClinicAdminForm, and then click View Code.

6.

Locate the MakeAppointmentWithClientTransaction method, select the


code for the method, including the method signature and parentheses, rightclick the selected code, and then click Copy.

7.

In Solution Explorer, return to the ClinicManagementService project.

8.

Right-click ClinicManagementServiceImplementation, and then click View


Code.

MCT USE ONLY. STUDENT USE PROHIBITED

L9-182

9.

L9-183

In the Code Editor window for the


ClinicManagementServiceImplementation file, locate the TODO 14
comment, right-click in the code window, and then click Paste.
[Visual Basic]
...
' TODO 14.
Private Function MakeAppointmentWithClientTransaction(ByVal _
patientId As String, ByVal doctorId As String, ByVal slot As _
DateTime) As String
Dim causeAnIntentionalError As Boolean = True
Dim appointmentId As String = "UNDEFINED"
' TODO 10.
Using scope As New TransactionScope()
Dim proxy As AppointmentServiceContract = _
GetAppointmentServiceProxy()
appointmentId = proxy.CreateAppointment(patientId, _
doctorId, slot)
Dim patientLetterServiceProxy As _
PatientLetterServiceContract = _
New
PatientLetterServiceContractClient("PLService_HTTP")
'TODO 11.
If causeAnIntentionalError Then
Throw New ApplicationException("This is an intentional"
_
" error to cause problems for a transaction")
End If
patientLetterServiceProxy.SendLetter(LetterType. _
ConsultationBooked, patientId, doctorId, slot)
scope.Complete()
End Using
Return appointmentId
End Function
...

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Transactions for a Service

Module 9: Implementing Transactions

[Visual C#]
...
// TODO 14
private string MakeAppointmentWithClientTransaction(string
patientId,
string doctorId, DateTime slot)
{
bool causeAnIntentionalError = true;
string appointmentId = "UNDEFINED";
// TODO 10
using (TransactionScope scope = new TransactionScope())
{
AppointmentServiceContract proxy =
GetAppointmentServiceProxy();
appointmentId = proxy.CreateAppointment(patientId,
doctorId, _
slot);
PatientLetterServiceContract patientLetterServiceProxy =
new
PatientLetterServiceContractClient("PLService_HTTP");
// TODO 11
if (causeAnIntentionalError)
{
throw new ApplicationException("This is an intentional"
" error to cause problems for a transaction");
}
patientLetterServiceProxy.SendLetter(LetterType.
ConsultationBooked, patientId, doctorId,slot);
scope.Complete();
}
return appointmentId;
}
...

MCT USE ONLY. STUDENT USE PROHIBITED

L9-184

L9-185

10. Change the method name to CreateAppointmentWorkflow, make the


method public, and then change the method signature to match that defined
in the service contract.
[Visual Basic]
...
' TODO 14.
Public Function CreateAppointmentWorkflow(ByVal patientId As
String, _
ByVal doctorId As String, ByVal slot As Date, ByVal _
causeAnIntentionalError As Boolean) As String Implements _
ClinicManagementServiceContract.CreateAppointmentWorkflow
...

[Visual C#]
...
// TODO 14
public string CreateAppointmentWorkflow(string patientId, string
doctorId, DateTime slot, bool causeAnIntentionalError)
...

11. Inside the CreateAppointmentWorkflow method, perform the following


tasks:
a.

Remove the using statement that creates the TransactionScope object,


and then delete the scope.Complete() statement.

b.

Remove the definition of the local variable causeAnIntentionalError.

c.

Add a statement that calls the


ClinicManagementServiceHelper.ShowTransactionalStatus message,
passing the name of the CreateAppointmentWorkflow method as the
parameter after the declaration of appointmentId local variable.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Transactions for a Service

Module 9: Implementing Transactions

The completed code should look like the following.


[Visual Basic]
...
' TODO 14.
Public Function CreateAppointmentWorkflow(ByVal patientId As
String, _
ByVal doctorId As String, ByVal slot As DateTime, ByVal _
causeAnIntentionalError As Boolean) As String Implements _
ClinicManagementServiceContract.CreateAppointmentWorkflow
Dim appointmentId As String = "UNDEFINED"
ClinicManagementServiceHelper.ShowTransactionalStatus( _
"CreateAppointmentWorkflow")
Dim proxy As AppointmentServiceContract = _
GetAppointmentServiceProxy()
appointmentId = proxy.CreateAppointment(patientId, doctorId,
slot)
Dim patientLetterServiceProxy As PatientLetterServiceContract =
_
New PatientLetterServiceContractClient("PLService_HTTP")
' TODO 11
If causeAnIntentionalError Then
Throw New ApplicationException("This is an intentional" & _
" error to cause problems for a transaction")
End If
patientLetterServiceProxy.SendLetter(LetterType. _
ConsultationBooked, patientId, doctorId, slot)
Return appointmentId
End Function
...

MCT USE ONLY. STUDENT USE PROHIBITED

L9-186

L9-187

[Visual C#]
...
// TODO 14
public string CreateAppointmentWorkflow(string patientId, string
doctorId, DateTime slot, bool causeAnIntentionalError)
{
string appointmentId = "UNDEFINED";
ClinicManagementServiceHelper.ShowTransactionalStatus(
"CreateAppointmentWorkflow");
AppointmentServiceContract proxy = GetAppointmentServiceProxy();
appointmentId = proxy.CreateAppointment(patientId, doctorId,
slot);
PatientLetterServiceContract patientLetterServiceProxy =
new PatientLetterServiceContractClient("PLService_HTTP");
// TODO 11
if (causeAnIntentionalError)
{
throw new ApplicationException("This is an intentional" +
"error to cause problems for a transaction");
}
patientLetterServiceProxy.SendLetter(LetterType.
ConsultationBooked, patientId, doctorId, slot);
return appointmentId;
}
...

12. Locate the statement that calls the GetAppointmentServiceProxy method in


the CreateAppointmentWorkflow method, and then replace it with a
statement that creates a new instance of the
AppointmentServiceContractClient passing the endpoint name
APService_TCP.
[Visual Basic]
...
Dim proxy As AppointmentServiceContract = _
New AppointmentServiceContractClient("APService_TCP")
...

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Transactions for a Service

Module 9: Implementing Transactions

[Visual C#]
...
AppointmentServiceContract proxy =
new AppointmentServiceContractClient("APService_TCP");
...

13. Locate the TODO 14 comment, and add a OperationBehavior to the


CreateAppointmentWorkflow then set its TransactionScopeRequired
property to true.
[Visual Basic]
...
' TODO 14.
<OperationBehavior(TransactionScopeRequired:=True)> _
...

[Visual C#]
...
// TODO 14
[OperationBehavior(TransactionScopeRequired = true)]
...

14. In Solution Explorer, right-click Solution 'Connected WCF', and then click
Rebuild Solution. Ensure that the solution builds successfully before moving
on.

f Task 4: Replace the client invocations with a call to the Clinic


Management Service
1.

Switch to Windows Explorer.

2.

Locate the transactional service host application:

3.

If you are using Visual Basic, go to the folder


E:\Labfiles\Starter\VB\AutomaticTransactions\ConnectedWCF\Cont
osoServicesSelfHostExtConfig\bin\debug.

If you are using Visual C#, go to the folder


E:\Labfiles\Starter\CS\AutomaticTransactions\ConnectedWCF\Cont
osoServicesSelfHostExtConfig\bin\debug.

Right-click ContosoServicesSelfHostExtConfig.exe, and then click Run as


administrator.

MCT USE ONLY. STUDENT USE PROHIBITED

L9-188

L9-189

4.

In the User Account Control dialog box, click Allow.

5.

Switch to Visual Studio 2008.

6.

In Solution Explorer, expand the ClinicAdminClient project.

7.

Expand Service References, right-click ClinicManagementServiceReference,


and then click Update Service Reference.

8.

After the service reference updates, stop the


ContosoServicesSelfHostExtConfig by pressing ENTER in the console
window.

9.

In Solution Explorer, right-click ClinicAdminForm, and then click View Code.

10. Locate the TODO 15 comment in the createAppointment_Click method, and


then replace the statement that calls the
MakeAppointmentWithClientTransaction method with statement that calls
the MakeAppointmentWithServerTransaction method, passing the same
parameters.
[Visual Basic]
...
' TODO 15.
Dim appointmentId As String = _
MakeAppointmentWithServerTransaction(patientId.Text, _
doctorId.Text, slot)
...

[Visual C#]
...
// TODO 15
string appointmentId =
MakeAppointmentWithServerTransaction(patientId.Text,
doctorId.Text, slot);
...

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Transactions for a Service

Module 9: Implementing Transactions

11. Locate the TODO 16 comment, and then add the following
MakeAppointmentWithServerTransaction method to the ClinicAdminForm
class.
[Visual Basic]
...
' TODO 16.
Private Function MakeAppointmentWithServerTransaction(ByVal _
patientId As String, ByVal doctorId As String, ByVal slot As _
DateTime) As String
Dim causeAnIntentionalError As Boolean = False
Dim clinicManagementServiceProxy As _
ClinicManagementServiceContract = New _
ClinicManagementServiceContractClient()
Return clinicManagementServiceProxy.CreateAppointmentWorkflow(
_
patientId, doctorId, slot, causeAnIntentionalError)
End Function
...

[Visual C#]
...
// TODO 16
private string MakeAppointmentWithServerTransaction(string
patientId,
string doctorId, DateTime slot)
{
bool causeAnIntentionalError = false;
ClinicManagementServiceContract clinicManagementServiceProxy =
new
ClinicManagementServiceContractClient();
return clinicManagementServiceProxy.CreateAppointmentWorkflow(
patientId, doctorId, slot, causeAnIntentionalError);
}
...

MCT USE ONLY. STUDENT USE PROHIBITED

L9-190

L9-191

f Task 5: Ensure that failure in the Clinic Management Service


transaction rolls back the changes to the appointment service
1.

On the Debug menu, click Start Debugging.

2.

In the Clinic Administration Client form, click the Create Appointment tab.

3.

Click Find Slots, and then click the first slot on the list. Make a note of which
slot you have selected. Type the patient ID NH991199Z into the Patient dropdown list box, and then click Create.

4.

In the dialog box that confirms the appointment has been made, click OK.

5.

Click Find Slots again, and then verify that the slot you chose is no longer
available.

6.

On the Debug menu, click Stop Debugging.

7.

In Solution Explorer, expand the ClinicAdminClient project.

8.

Right-click ClinicAdminForm, and then click View Code.

9.

In the Code Editor window for the ClinicAdminForm class file, locate the
MakeAppointmentWithServerTransaction method. Change the value of the
causeAnIntentionalError variable to true.
[Visual Basic]
...
Dim causeAnIntentionalError As Boolean = True
...

[Visual C#]
...
bool causeAnIntentionalError = true;
...

10. In Solution Explorer, right-click Solution 'Connected WCF', and then click
Rebuild Solution.
11. On the Debug menu, click Start Debugging.
12. In the Clinic Administration Client form, click the Create Appointment tab.
13. Click Find Slots, and then click to select the first slot on the list. Make a note
of which slot you have selected. Type the patient ID NH991199Z into the
Patient drop-down list box, and then click Create.

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Transactions for a Service

Module 9: Implementing Transactions

14. When the dialog box titled 'ApplicationException was unhandled by user
code' is displayed, on the Debug menu click Continue.
15. Switch to the Clinic Administration Client.
16. In the dialog box that states there has been an error, click OK.
17. Click Find Slots again, and then verify that the slot you chose is still available.
This proves that the effects of the CreateAppointment operation have been
rolled back because of this server-side exception that aborts the transaction.
18. In Visual Studio 2008, on the Debug menu, click Stop Debugging.
19. Close Visual Studio 2008.

Results: After this exercise, you should have removed the transaction code from the
client and used WCF to automatically start a transaction on the service.

MCT USE ONLY. STUDENT USE PROHIBITED

L9-192