Beruflich Dokumente
Kultur Dokumente
LEARNING
PRODUCT
6461A
Visual Studio 2008: Windows
Communication Foundation
OFFICIAL
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.
ii
updates,
supplements,
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
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.
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.
protective order or otherwise protect the information. Confidential information does not
include information that
you received from a third party who did not breach confidentiality obligations to
Microsoft or its suppliers; or
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.
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;
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;
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;
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.
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
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
1-16
1-22
1-27
1-31
2-17
2-21
2-30
2-36
3-3
3-14
3-20
3-27
4-3
4-12
4-17
5-3
5-10
5-16
5-23
5-30
6-3
6-8
6-17
6-24
7-3
7-11
7-17
7-23
7-31
8-3
8-14
8-25
8-34
8-41
iv
9-3
9-10
9-16
9-22
Course Evaluation
9-34
L1-1 -L1-22
L2-23 - L2-44
L3-45 - L3-64
L4-65 - L4-74
L5-75 - L5-104
L6-105- L6-120
L7-121 - L7-150
L8-151 - L8-166
L9-167 - L9-192
L1-1
Logon Information:
Password: Pa$$w0rd
2.
3.
4.
5.
6.
7.
8.
Open the Virtual Server Remote Control Client and double-click 6461-LONDEV-01.
2.
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.
L1-2
3.
L1-3
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.
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.
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.
2.
3.
2.
If you are using Visual Basic, in the Microsoft Visual Studio dialog box, click
Yes.
3.
4.
L1-4
5.
L1-5
6.
7.
All comments
[Visual C#]
...
[ServiceContract(Namespace =
"http://contoso.com/services/AppointmentService")]
...
8.
9.
[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);
...
L1-6
L1-7
[Visual C#]
...
[OperationContract]
List<DateTime> ListAvailableAppointmentTimes(string doctorId,
DateTime day);
...
[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);
}
}
2.
If you are using Visual Basic, in the Microsoft Visual Studio dialog box, click
Yes.
3.
4.
If you are using Visual C#, rename the Service1 class definition to
AppointmentServiceImplementation.
6.
All comments
L1-8
L1-9
7.
8.
If you are using Visual C#, remove the following code from the
CreateAppointment, CancelAppointment and
ListAvailableAppointmentTimes methods.
[Visual C#]
...
throw new NotImplementedException();
...
9.
[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
...
[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);
}
...
L1-10
L1-11
[Visual C#]
...
public List<DateTime> ListAvailableAppointmentTimes(string
doctorId,
DateTime day)
{
return AppointmentHelperClass.GetAvailableAppointments(doctorId,
day);
}
...
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
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.
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.
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.
6.
If you are using Visual Basic, in Solution Explorer, click Show All Files.
7.
8.
9.
10. In Solution Explorer, within the AppointmentServiceIISHost project, rightclick the Service1.svc file, click Rename, type AppointmentService.svc and
then press ENTER.
L1-14
L1-15
[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" %>
In Solution Explorer, within the AppointmentServiceIISHost project, rightclick Web.config, and then click Edit WCF Configuration.
2.
3.
In the right pane, in the General section, in the Name box, type
AppointmentServiceIISHost.ServiceBehavior
4.
5.
6.
8.
In the Microsoft Service Configuration Editor window, on the File menu, click
Save.
9.
2.
3.
4.
5.
6.
7.
Results: After this exercise, you should have developed a WCF service in Visual
Studio 2008.
L1-16
L1-17
2.
3.
2.
In the Add Service Reference dialog box, define a service reference with the
following information, and then click OK.
a.
b.
2.
[Visual C#]
...
//TODO 1.
using ClinicAdminClient.AppointmentServiceReference;
...
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:
[Visual Basic]
...
' TODO 3.
Dim proxy As AppointmentServiceContract = _
GetAppointmentServiceProxy()
slots = proxy.ListAvailableAppointmentTimes(doctorId.Text, _
dateRequested.Value)
...
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:
[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);
...
6.
Locate the TODO 5 comment, and then add code to do the following:
[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);
...
L1-20
L1-21
2.
3.
4.
Create an appointment with the following information, and then click Create:
Slots: In the Slots list, click any of the available time slots.
5.
6.
On the Cancel Appointment tab, in the Appt ID box, type your Appointment
identifier, and then click Delete.
7.
8.
9.
Results: After this exercise, you should have enhanced the existing
ClinicAdminClient application to invoke the methods in the AppointmentService.
L2-23
Logon Information:
Password: Pa$$w0rd
2.
3.
4.
5.
6.
7.
Open the Virtual Server Remote Control Client, and then double-click 6461LON-DEV-02.
2.
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.
3.
L2-24
4.
L2-25
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.
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
2.
In the Add Reference dialog box, on the .NET tab, in the Component Name
column, double-click the System.ServiceModel assembly.
3.
4.
In the Add Reference dialog box, on the Projects tab, in the Project Name
column, double-click the AppointmentService assembly.
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.
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)
{
}
...
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.
c.
f.
Invoke the ReadLine method on the Console class to stop the console
from closing.
g.
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();
}
...
In the Microsoft Service Configuration Editor, in the left pane, expand the
Endpoints folder under the Client folder, and then click
WSHttpBinding_AppointmentServiceContract.
4.
On the File menu, click Save, and then close the Microsoft Service
Configuration Editor.
2.
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.
2.
3.
4.
Results: After this exercise, you should have developed an EXE host for the
appointment service.
L2-30
L2-31
2.
3.
In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.
2.
3.
4.
In the Code Editor window for the configuration file, remove the
<system.serviceModel> </system.serviceModel> element and all its subelements.
5.
2.
If you are using Visual Basic, bring the System.ServiceModel namespace into
scope.
[Visual Basic]
...
Imports System.ServiceModel
...
3.
4.
b.
c.
[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...
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;
}
...
2.
3.
4.
Results: After this exercise, you should have programmatically defined the WCF
configuration for the AppontmentServiceSelfHost and ClinicAdminClient
projects.
2.
3.
4.
In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.
2.
3.
4.
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.
L2-34
L2-35
5.
6.
7.
8.
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.
2.
In the Main method, make the following changes to the existing code:
a.
b.
c.
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();
}
}
...
L2-36
L2-37
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.
6.
b.
[Visual C#]
...
private AppointmentServiceContract GetAppointmentServiceProxy()
{
return new AppointmentServiceContractClient();
}
...
2.
3.
4.
Results: After this exercise, you should have defined the WCF configuration for the
AppontmentServiceSelfHost and ClinicAdminClient projects in external
configuration files.
L2-38
L2-39
2.
3.
4.
5.
6.
7.
2.
3.
4.
5.
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.
8.
9.
In the Add Application dialog box, add a new application with the following
details, and then click OK.
Alias: AppointmentServiceIISHost
2.
3.
4.
5.
2.
3.
4.
5.
6.
L2-40
L2-41
In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.
2.
3.
4.
5.
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.
2.
In the Microsoft Service Configuration Editor, in the left pane, under the
Client folder, 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_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.
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");
}
...
L2-42
L2-43
2.
3.
2.
3.
4.
Results: After this exercise, you should have hosted the appointment service in IIS
using WAS.
L3-45
Logon Information:
Password: Pa$$w0rd
2.
3.
4.
5.
6.
7.
8.
Open the Virtual Server Remote Control Client and double-click 6461-LONDEV-03.
2.
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.
3.
In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.
L3-46
4.
L3-47
2.
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
6.
7.
8.
In the Base Address Editor dialog box, in the Base address box, type
http://localhost:8002/Contoso and then click OK.
9.
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.
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.
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.
6.
L3-48
L3-49
2.
3.
In the Add Existing Item - FPAdminClient dialog box, go to the following file,
and then click Add:
4.
5.
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.
9.
2.
3.
4.
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.
8.
L3-50
L3-51
2.
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.
2.
3.
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,
7.
Results: After this exercise, you should have exposed the Appointment service over
a netTcpBinding and wsHttpBinding endpoint.
2.
3.
4.
5.
6.
In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.
2.
3.
4.
L3-52
5.
6.
7.
8.
9.
L3-53
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.
2.
3.
4.
5.
6.
2.
3.
4.
5.
L3-54
L3-55
6.
7.
8.
In the Add Service Reference dialog box, define a service reference with the
following information, and then click OK.
9.
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
...
[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.
2.
3.
In the Solution Explorer window, in the ClinicAdminClient project, doubleclick the following file:
4.
5.
6.
7.
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.
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");
}
...
2.
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.
2.
3.
4.
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,
8.
L3-58
L3-59
2.
3.
4.
5.
6.
2.
3.
4.
5.
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.
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
2.
3.
4.
5.
6.
L3-60
L3-61
In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.
2.
3.
4.
2.
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.
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;
...
L3-62
3.
L3-63
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);
...
2.
3.
4.
Wait for the Console window to display the message Appointment service
and patient letter service running. Press <ENTER> to quit.
5,
6.
7.
8.
9.
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.
L3-64
L4-65
Logon Information:
Password: Pa$$w0rd
2.
3.
4.
5.
6.
Open the Virtual Server Remote Control Client and double-click 6461-LONDEV-04.
2.
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.
3.
In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.
L4-66
4.
L4-67
2.
3.
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.
6.
7.
8.
9.
In the Microsoft Service Configuration Editor window, on the File menu, click
Save.
2.
3.
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.
6.
7.
8.
9.
In the Microsoft Service Configuration Editor window, on the File menu, click
Save.
2.
3.
L4-68
L4-69
4.
Wait for the Console window to display the message Service running.
5,
6.
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.
4.
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.
Results: After this exercise, you should have enabled message logging for the
AppointmentService, PatientManagementService, and the ClinicAdminClient
application.
2.
3.
4.
5.
In Visual Studio 2008, on the File menu, point to Open, and then click
Project/Solution.
2.
2.
L4-70
3.
L4-71
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.
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.
2.
3.
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.
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.
2.
3.
4.
Wait for the Console window to display the message Service running.
5,
6.
In the Patient box, type NH991199Z and then click Create. Make a note of
the appointment ID.
7.
8.
9.
The Appt ID box, type your appointment ID, and then click Delete.
2.
In the Microsoft Service Trace Viewer, on the File menu, click Open.
3.
L4-72
4.
L4-73
5.
6.
7.
8.
9.
Building the channel stack for the client to communicate with the
AppointmentService
b.
c.
e.
f.
Building the channel stack for the client to communicate with the
PatientManagementService
g.
h.
i.
j.
Results: After this exercise, you should have enabled tracing for the
AppointmentService, PatientManagementService, and the ClinicAdminClient
application.
L4-74
Password: Pa$$w0rd
L5-75
2.
Add a call from the clinic admin client to the patient letter service.
3.
4.
5.
6.
Open the Virtual Server Remote Control Client and double-click 6461-LONDEV-05.
2.
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.
3.
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.
4.
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)
f Task 3: Add a delay and diagnostic output to the patient letter service
1.
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()
L5-78
L5-79
2.
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:
Patient: NH991199Z
5.
Verify that both of the messages from the SendLetter method appear before
you see the Clinic Admin: Appointment Created window.
6.
7.
8.
On the Start menu, point to All Programs, point to Accessories, and then
click Windows Explorer.
9.
10. Verify that the appointment time in the letter is the one you selected.
11. Close Notepad.
2.
3.
[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.
5.
6.
7.
8.
9.
L5-80
L5-81
2.
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:
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.
7.
8.
9.
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.
2.
3.
4.
2.
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.
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
5.
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
(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
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.
L5-86
4.
L5-87
[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.
2.
3.
4.
5.
6.
7.
8.
9.
[Visual Basic]
'TODO 7
Dim proxy As AppointmentServiceContract =
GetAppointmentServiceProxy()
appointmentsToday.DataSource = proxy.ListTodaysAppointments()
2.
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:
Patient: NH991199Z
L5-88
L5-89
4.
5.
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.
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.
2.
3.
4.
Implement the callback contract in the clinic admin client and register with the
service.
5.
6.
7.
2.
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.
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
2.
[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
L5-92
L5-93
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
3.
[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:
[Visual C#]
throw new NotImplementedException();
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.
2.
3.
4.
5.
6.
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.
9.
[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:
L5-96
L5-97
[Visual C#]
throw new NotImplementedException();
[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)
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
2:
[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
L5-100
L5-101
2.
3.
4.
5.
6.
7.
8.
In Solution Explorer, right-click the ConsultantForm file, and then click View
Code.
9.
[Visual Basic]
'TODO 16
Imports ConsultantClient.ClinicManagementServiceReference
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.
2.
3.
4.
5.
L5-102
L5-103
6.
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.
Results: After completing this exercise, you have defined a callback contract and
used this to communicate an event between two different service clients.
Password: Pa$$w0rd
L6-105
2.
3.
4.
Add an outer try block to the client and report the exception to the user.
5.
Open the Virtual Server Remote Control Client and double-click 6461-LONDEV-06.
2.
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.
L6-106
3.
L6-107
4.
5.
6.
In the Clinic Administration Client form, click the Create Appointment tab.
Enter the following data, and then click Create:
Doctor: Gastro_Jones
Slot: Click Find Slots (this selects the first slot shown)
Patient: NH991199Z
7.
8.
9.
2.
Locate the TODO 1 comment in the GetConnection method and change the
connection string passed into the SqlConnection constructor as follows:
Connection Timeout: 5
[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.
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.
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.
L6-108
L6-109
f Task 4: Add an outer try block to the client and report the exception
to the user
1.
2.
[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.
4.
In the Exceptions dialog box, clear the User-unhandled check box for
Common Language Runtime Exceptions, and then click OK.
5.
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.
2.
In the Configuration pane, expand the Advanced folder, expand the Service
Behaviors folder, and then click the AppointmentServiceBehavior node.
3.
4.
5.
6.
In the serviceDebug pane on the right side, set the value of the
IncludeExceptionDetailInFaults property to True.
7.
8.
9.
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.
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.
4.
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.
3.
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.
5.
L6-112
6.
7.
L6-113
[Visual C#]
using System.Collections.Generic;
using System.Linq;
using System.Text;
If you are using Visual C#, set the namespace containing the class to be
com.contoso.
[Visual C#]
using System;
using System.Runtime.Serialization;
namespace com.contoso
{
class UnexpectedServiceFault
{
}
}
8.
[Visual C#]
[DataContract(Namespace="http://contoso.com/ClinicManagementSystem/
2007/10")]
public class UnexpectedServiceFault
{
}
9.
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.
2.
[Visual C#]
// TODO 3
[OperationContract]
[FaultContract(typeof(com.contoso.UnexpectedServiceFault))]
List<Appointment> ListTodaysAppointments();
3.
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.
2.
L6-116
L6-117
[Visual C#]
// TODO 4
try
{
return new AppointmentHelper().ListTodaysAppointments();
}
catch (Exception unexpected)
{
}
3.
[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.");
}
4.
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.
3.
4.
5.
6.
7.
8.
L6-118
9.
L6-119
[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);
}
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.
L6-120
Password: Pa$$w0rd
L7-121
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.
Open the Virtual Server Remote Control Client and double-click 6461-LONDEV-07.
2.
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.
L7-122
3.
4.
5.
L7-123
6.
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)
[Visual C#]
// TODO 1
Type appointmentInstanceType =
typeof(com.contoso.AppointmentService.
AppointmentServiceLinkedListImplementation);
8.
9.
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.
L7-124
L7-125
2.
3.
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.
6.
7.
8.
9.
[Visual C#]
// TODO 2
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class AppointmentServiceLinkedListImplementation :
AppointmentServiceContract
...
Results: After completing this exercise, you have seen how to change the instance
management mode on your service and what effect this has.
L7-126
L7-127
2.
Show that attempts to speed up the service can lead to corruption due to
multi-threading.
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.
3.
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.
5.
[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.
7.
L7-128
8.
L7-129
9.
2.
[Visual C#]
// TODO 2
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single,
ConcurrencyMode=ConcurrencyMode.Multiple)]
public class AppointmentServiceLinkedListImplementation :
AppointmentServiceContract
...
3.
4.
5.
6.
Results: After completing this exercise, you have seen how to control the threading
mode of a service.
L7-130
L7-131
2.
3.
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.
3.
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.
5.
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.
7.
8.
9.
2.
Expand the Advanced folder, expand the Service Behaviors folder, and then
click the HttpMexAndExceptionDetail behavior. In the right pane, click Add.
3.
4.
5.
6.
In the WCF Service Configuration Editor window, on the File menu, click
Save.
7.
8.
L7-132
9.
L7-133
2.
[Visual C#]
// TODO 4
TimeSpan callTime =
appointmentService.TimedCreateAppointment(myPatient,
myDoctor, start.AddMinutes(i * 30));
callTime += appointmentService.TimedListTodaysAppointments();
int millisThisCall = callTime.Milliseconds;
3.
4.
5.
6.
7.
Expand Advanced folder, expand the Service Behaviors folder, expand the
HttpMexAndExceptionDetail behavior, and then click serviceThrottling.
8.
9.
In the WCF Service Configuration Editor window, on the File menu, click
Save.
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.
2.
3.
4.
5.
6.
7.
8.
9.
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.
L7-136
3.
L7-137
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.
[Visual C#]
// TODO 6
public class PatientManagementServiceImplementation :
PatientManagementServiceContract,
PatientManagementServiceImageContract
8.
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.
2.
3.
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.
Name: WebServiceMtomBindingConfig
MessageEncoding: Mtom
8.
9.
In the WCF Service Configuration Editor window, on the File menu, click
Save.
On the Start menu, point to All Programs, point to Accessories, and then
click Windows Explorer.
2.
4.
5.
6.
7.
8.
9.
L7-140
L7-141
[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();
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.
4.
5.
6.
7.
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.
2.
3.
In the Open dialog box, go to the E:\LabFiles\logs folder, click the file
messages.svclog, and then click Open.
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.
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.
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.
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
[Visual C#]
// TODO 5
[OperationContract]
Stream StreamXrayImage(string patientId, string type);
3.
[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);
}
L7-144
L7-145
2.
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.
Name: NetTcpStreamingBindingConfig
TransferMode: Streamed
7.
8.
In the WCF Service Configuration Editor window, on the File menu, click
Save.
9.
10. In Solution Explorer, right-click Solution 'Connected WCF', and then click
Rebuild Solution.
2.
4.
5.
6.
7.
8.
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.
[Visual C#]
// TODO 11
Stream imageStream = GetImageStream(typeOfXray);
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.
4.
In the WCF Service Configuration Editor window, on the File menu, click
Save.
5.
6.
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.
2.
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.
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.
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.
Password: Pa$$w0rd
L8-151
2.
3.
4.
5.
6.
Open the Virtual Server Remote Control Client, and then double-click 6461LON-DEV-08.
2.
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.
L8-152
3.
4.
L8-153
5.
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.
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.
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.
2.
In the WCF Service Configuration Editor, expand the Bindings folder, and
then click the APService_TCP binding configuration.
3.
4.
5.
6.
7.
2.
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.
L8-154
L8-155
5.
6.
7.
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.
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.
2.
[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);
}
L8-156
3.
L8-157
[Visual C#]
// TODO 2
ShowSecurityInformation("ListAvailableAppointmentTimes");
4.
5.
On the Clinic Administration Client form, click the Create Appointment tab.
6.
7.
8.
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()
[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.
5.
On the Clinic Administration Client form, click the Create Appointment tab.
6.
7.
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.
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.
2.
3.
4.
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.
3.
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.
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.
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.
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.
3.
4.
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.
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.
L8-162
L8-163
2.
3.
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.
5.
In the Add Reference dialog box, click the Projects tab, click
AppointmentService, and then click OK.
6.
7.
[Visual C#]
<%@ ServiceHost Language="C#" Debug="true"
Service="com.contoso.AppointmentService.AppointmentServiceImplement
ation" %>
8.
9.
Expand the Services folder, and then click Service. In the right pane, set the
Name value to
com.contoso.AppointmentService.AppointmentServiceImplementation.
L8-164
L8-165
2.
3.
Right-click the FPAdminForm class file, and then click View Code.
4.
b.
[Visual C#]
// TODO 5
EndpointAddress address = new
EndpointAddress("https://localhost/ContosoInternetGateway/"
+ "AppointmentService.svc");
BasicHttpBinding binding =
new
BasicHttpBinding(BasicHttpSecurityMode.Transport);
5.
6.
In the Service Configuration Editor, expand the Bindings folder, and then
click APService_HTTP.
7.
8.
9.
[Visual C#]
// TODO 5
PermissiveCertificatePolicy.Enact("CN=LON-DEV");
Results: After completing this exercise, you have seen how to secure message
contents across the Internet using transport-level security.
L8-166
Password: Pa$$w0rd
L9-167
2.
3.
4.
5.
Ensure that failure in the client transaction rolls back the changes to the
appointment service.
Open the Virtual Server Remote Control Client, and then double-click 6461LON-DEV-09.
2.
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.
3.
L9-168
4.
L9-169
5.
6.
7.
[Visual C#]
...
// TODO 1
[TransactionFlow(TransactionFlowOption.Mandatory)]
...
2.
[Visual C#]
...
// TODO 2
[OperationBehavior(TransactionScopeRequired=true)]
...
3.
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;
...
L9-170
5.
L9-171
[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);
}
}
...
6.
[Visual C#]
...
// TODO 5
ShowTransactionalStatus("CreateAppointment");
...
7.
8.
9.
In the Create a New Binding dialog box, click wsHttpBinding, and then click
OK.
b.
b.
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.
On the taskbar, click Start, point to All Programs, point to Accessories, and
then click Windows Explorer.
2.
3.
4.
5.
6.
7.
8.
9.
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.
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.
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;
...
L9-174
5.
L9-175
[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.
f Task 6: Ensure that failure in the client transaction rolls back the
changes to the appointment service
1.
2.
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.
L9-176
8.
9.
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.
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.
L9-178
L9-179
Add references to the Clinic Management Service so that it can act as a client
for the Appointment Service and Patient Letter Service.
2.
3.
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.
2.
3.
4.
5.
Switch to Windows Explorer, and then locate the service host executable file:
6.
7.
8.
9.
10. In the Add Service Reference dialog box, perform the following tasks:
a.
b.
Click Go.
c.
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.
b.
Click Go
c.
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.
L9-180
L9-181
[Visual C#]
...
// TODO 12
using
com.contoso.ClinicManagementService.AppointmentServiceReference;
using com.contoso.ClinicManagementService.
PatientLetterServiceReference;
...
In Solution Explorer, in the ContosoServicesSelfHostExtConfig project, rightclick the app.config file, and then click Edit WCF Configuration.
2.
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.
2.
3.
[Visual C#]
// TODO 13
[OperationContract]
string CreateAppointmentWorkflow(string patientId, string doctorId,
DateTime slot, bool causeAnIntentionalError);
4.
5.
6.
7.
8.
L9-182
9.
L9-183
[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;
}
...
L9-184
L9-185
[Visual C#]
...
// TODO 14
public string CreateAppointmentWorkflow(string patientId, string
doctorId, DateTime slot, bool causeAnIntentionalError)
...
b.
c.
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;
}
...
[Visual C#]
...
AppointmentServiceContract proxy =
new AppointmentServiceContractClient("APService_TCP");
...
[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.
2.
3.
L9-188
L9-189
4.
5.
6.
7.
8.
9.
[Visual C#]
...
// TODO 15
string appointmentId =
MakeAppointmentWithServerTransaction(patientId.Text,
doctorId.Text, slot);
...
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);
}
...
L9-190
L9-191
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.
7.
8.
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.
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.
L9-192