MCT USE ONLY. STUDENT USE PROHIBITED

the back cover of the book. Be sure toBe sure access the extendedcontent learning on your Course CompanionCD enclosed on Visual Studio® 2008: Windows® Visual Studio® 2008: Foundation Communication OFFICIAL LEARNING PRODUCT PRODUCT LEARNING MICROSOFT OFFICIAL 6461A MCT USE ONLY. STUDENT USE PROHIBITED of Microsoft of the s , are either registered for the contents of any linked site or any link link any or site linked any of contents the for es, and eventsdepicted hereinfictitious,are introduced into a retrieval system, or transmitted transmitted or system, retrieval a into introduced

ived from any linked site. Microsoft is providing e provided for informational purposes only and tes to such sites. Microsoft is not responsible for products with any Microsoft technologies. The the example companies, organizations, products, nization,product,domain name,e- address, ld be inferred. Complyingwith all applicable e inclusion of any link does not imply endorsement document. Except as expressly provided in any not imply endorsement permissionof Microsoft Corporation. crosoft Corporation in the United States and/or other countries.

trademarks or trademarks of Mi All other trademarks are property of their respective owners. 6461A Product Number: 04/2008 Released: these links to you only as a convenience, and th of Microsoftof the site or the products contained therein. 2008 © Corporation.Microsoft All rights reserved. Microsoft, , , MSDN, PowerPoint, SQL Server, , Visual C#, VisualStudio, Windows, Windows CardSpace, contained in a linked site, or any changes or upda webcasting or any other form of transmission rece

Microsoft makes no representations and warranties, either expressed,implied, or statutory, regarding these manufacturers or the use of the inclusion of a manufacturer or product does 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 in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this 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 ar domain names, e-mail addresses, logos, , plac and no association with any real company, orga 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 Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, logo, person, place or event is intended or shou Studio® Visual 2008: Windows® Communication Foundation ii MICROSOFT LICENSE TERMS OFFICIAL MICROSOFT LEARNING PRODUCTS - TRAINER EDITION – Pre-Release and Final Release Versions These license terms are an agreement between Microsoft Corporation and you. Please read them. They apply to the Licensed Content named above, which includes the media on which you received it, if any. The terms also apply to any Microsoft • updates, • supplements, • Internet-based services, and • support services for this Licensed Content, unless other terms accompany those items. If so, those terms apply. By using the Licensed Content, you accept these terms. If you do not accept them, do not use the Licensed Content.

If you comply with these license terms, you have the rights below. 1. DEFINITIONS. a. “Academic Materials” means the printed or electronic documentation such as manuals, workbooks, white papers, press releases, datasheets, and FAQs which may be included in the Licensed Content. b. “Authorized Learning Center(s)” means a Microsoft Certified Partner for Learning Solutions location, an IT Academy location, or such other entity as Microsoft may designate from time to time. c. “Authorized Training Session(s)” means those training sessions authorized by Microsoft and conducted at or through Authorized Learning Centers by a Trainer providing training to Students solely on Official Microsoft Learning Products (formerly known as Microsoft Official Curriculum or “MOC”) and Microsoft Dynamics Learning Products (formerly know as Microsoft Business Solutions Courseware). Each Authorized Training Session will provide training on the subject matter of one (1) Course. d. “Course” means one of the courses using Licensed Content offered by an Authorized Learning Center during an Authorized Training Session, each of which provides training on a particular Microsoft technology subject matter. e. “Device(s)” means a single computer, device, workstation, , or other digital electronic or analog device. f. “Licensed Content” means the materials accompanying these license terms. The Licensed Content may include, but is not limited to, the following elements: (i) Trainer Content, (ii) Student Content, (iii) classroom setup guide, and (iv) Software. There are different and separate components of the Licensed Content for each Course. g. “Software” means the Virtual Machines and Virtual Hard Disks, or other software applications that may be included with the Licensed Content. h. “Student(s)” means a student duly enrolled for an Authorized Training Session at your location.

i. “Student Content” means the learning materials accompanying these license terms that are for use by Students and Trainers during an Authorized Training Session. Student Content may include labs, simulations, and courseware files for a Course. j. “Trainer(s)” means a) a person who is duly certified by Microsoft as a Microsoft Certified Trainer and b) such other individual as authorized in writing by Microsoft and has been engaged by an Authorized Learning Center to teach or instruct an Authorized Training Session to Students on its behalf. k. “Trainer Content” means the materials accompanying these license terms that are for use by Trainers and Students, as applicable, solely during an Authorized Training Session. Trainer Content may include Virtual Machines, Virtual Hard Disks, Microsoft PowerPoint files, instructor notes, and demonstration guides and script files for a Course. l. “Virtual Hard Disks” means Microsoft Software that is comprised of virtualized hard disks (such as a base virtual hard disk or differencing disks) for a Virtual Machine that can be loaded onto a single computer or other device in order to allow end-users to run multiple operating systems concurrently. For the purposes of these license terms, Virtual Hard Disks will be considered “Trainer Content”. m. “Virtual Machine” means a virtualized computing experience, created and accessed using Microsoft® Virtual PC or Microsoft® Virtual Server software that consists of a virtualized hardware environment, one or more Virtual Hard Disks, and a configuration file setting the parameters of the virtualized hardware environment (e.g., RAM). For the purposes of these license terms, Virtual Hard Disks will be considered “Trainer Content”. n. “you” means the Authorized Learning Center or Trainer, as applicable, that has agreed to these license terms. 2. OVERVIEW. Licensed Content. The Licensed Content includes Software, Academic Materials (online and electronic), Trainer Content, Student Content, classroom setup guide, and associated media. License Model. The Licensed Content is licensed on a per copy per Authorized Learning Center location or per Trainer basis. 3. INSTALLATION AND USE RIGHTS. a. Authorized Learning Centers and Trainers: For each Authorized Training Session, you may: i. either install individual copies of the relevant Licensed Content on classroom Devices only for use by Students enrolled in and the Trainer delivering the Authorized Training Session, provided that the number of copies in use does not exceed the number of Students enrolled in and the Trainer delivering the Authorized Training Session, OR ii. install one copy of the relevant Licensed Content on a network server only for access by classroom Devices and only for use by Students enrolled in and the Trainer delivering the Authorized Training Session, provided that the number of Devices accessing the Licensed Content on such server does not exceed the number of Students enrolled in and the Trainer delivering the Authorized Training Session. iii. and allow the Students enrolled in and the Trainer delivering the Authorized Training Session to use the Licensed Content that you install in accordance with (ii) or (ii) above during such Authorized Training Session in accordance with these license terms.

i. Separation of Components. The components of the Licensed Content are licensed as a single unit. You may not separate the components and install them on different Devices. ii. Third Party Programs. The Licensed Content may contain third party programs. These license terms will apply to the use of those third party programs, unless other terms accompany those programs. b. Trainers: i. Trainers may Use the Licensed Content that you install or that is installed by an Authorized Learning Center on a classroom Device to deliver an Authorized Training Session. ii. Trainers may also Use a copy of the Licensed Content as follows: A. Licensed Device. The licensed Device is the Device on which you Use the Licensed Content. You may install and Use one copy of the Licensed Content on the licensed Device solely for your own personal training Use and for preparation of an Authorized Training Session. B. Portable Device. You may install another copy on a portable device solely for your own personal training Use and for preparation of an Authorized Training Session. 4. PRE-RELEASE VERSIONS. If this is a pre-release (“beta”) version, in addition to the other provisions in this agreement, these terms also apply: a. Pre-Release Licensed Content. This Licensed Content is a pre-release version. It may not contain the same information and/or work the way a final version of the Licensed Content will. We may change it for the final, commercial version. We also may not release a commercial version. You will clearly and conspicuously inform any Students who participate in each Authorized Training Session of the foregoing; and, that you or Microsoft are under no obligation to provide them with any further content, including but not limited to the final released version of the Licensed Content for the Course. b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, you give to Microsoft, without charge, the right to use, share and commercialize your feedback in any way and for any purpose. You also give to third parties, without charge, any patent rights needed for their products, technologies and services to use or interface with any specific parts of a Microsoft software, Licensed Content, or service that includes the feedback. You will not give feedback that is subject to a license that requires Microsoft to license its software or documentation to third parties because we include your feedback in them. These rights survive this agreement. c. Confidential Information. The Licensed Content, including any viewer, user interface, features and documentation that may be included with the Licensed Content, is confidential and proprietary to Microsoft and its suppliers. i. Use. For five years after installation of the Licensed Content or its commercial release, whichever is first, you may not disclose confidential information to third parties. You may disclose confidential information only to your employees and consultants who need to know the information. You must have written agreements with them that protect the confidential information at least as much as this agreement. ii. Survival. Your duty to protect confidential information survives this agreement. iii. Exclusions. You may disclose confidential information in response to a judicial or governmental order. You must first give written notice to Microsoft to allow it to seek a

protective order or otherwise protect the information. Confidential information does not include information that • becomes publicly known through no wrongful act; • you received from a third party who did not breach confidentiality obligations to Microsoft or its suppliers; or • you developed independently.

d. Term. The term of this agreement for pre-release versions is (i) the date which Microsoft informs you is the end date for using the beta version, or (ii) the commercial release of the final release version of the Licensed Content, whichever is first (“beta term”). e. Use. You will cease using all copies of the beta version upon expiration or termination of the beta term, and will destroy all copies of same in the possession or under your control and/or in the possession or under the control of any Trainers who have received copies of the pre-released version. f. Copies. Microsoft will inform Authorized Learning Centers if they may make copies of the beta version (in either print and/or CD version) and distribute such copies to Students and/or Trainers. If Microsoft allows such distribution, you will follow any additional terms that Microsoft provides to you for such copies and distribution. 5. ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS. a. Authorized Learning Centers and Trainers: i. Software. ii. Virtual Hard Disks. The Licensed Content may contain versions of Microsoft XP, Vista, , , and 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 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. o 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. o 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. o You will ensure that the Virtual Machines and Virtual Hard Disks are not copied or downloaded from Devices on which you installed them. o You will strictly comply with all Microsoft instructions relating to installation, use, activation and deactivation, and security of Virtual Machines and Virtual Hard Disks. o You may not modify the Virtual Machines and Virtual Hard Disks or any contents thereof. o 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 Material’s original copyright notice, or a copyright notice to Microsoft’s 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 else’s 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 Microsoft’s prior written approval; • work around any technical limitations in the Licensed Content; • reverse engineer, decompile or disassemble the Licensed Content, except and only to the extent that applicable law expressly permits, despite this limitation; • make more copies of the Licensed Content than specified in this agreement or allowed by applicable law, despite this limitation; • publish the Licensed Content for others to copy;

• transfer the Licensed Content, in whole or in part, to a third party; • access or use any Licensed Content for which you (i) are not providing a Course and/or (ii) have not been authorized by Microsoft to access and use; • rent, lease or lend the Licensed Content; or • use the Licensed Content for commercial hosting services or general business purposes. • Rights to access the server software that may be included with the Licensed Content, including the Virtual Hard Disks does not give you any right to implement Microsoft patents or other Microsoft intellectual property in software or devices that may access the server. 8. EXPORT RESTRICTIONS. The Licensed Content is subject to United States export laws and regulations. You must comply with all domestic and international export laws and regulations that apply to the Licensed Content. These laws include restrictions on destinations, end users and end use. For additional information, see www.microsoft.com/exporting. 9. NOT FOR RESALE SOFTWARE/LICENSED CONTENT. You may not sell software or Licensed Content marked as “NFR” or “Not for Resale.” 10. ACADEMIC EDITION. You must be a “Qualified Educational User” to use Licensed Content marked as “Academic Edition” or “AE.” If you do not know whether you are a Qualified Educational User, visit www.microsoft.com/education or contact the Microsoft affiliate serving your country. 11. TERMINATION. Without prejudice to any other rights, Microsoft may this agreement if you fail to comply with the terms and conditions of these license terms. In the event your status as an Authorized Learning Center or Trainer a) expires, b) is voluntarily terminated by you, and/or c) is terminated by Microsoft, this agreement shall automatically terminate. Upon any termination of this agreement, you must destroy all copies of the Licensed Content and all of its component parts. 12. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates, Internet- based services and support services that you use, are the entire agreement for the Licensed Content and support services. 13. APPLICABLE LAW. a. United States. If you acquired the Licensed Content in the United States, Washington state law governs the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws principles. The laws of the state where you live govern all other claims, including claims under state consumer protection laws, unfair competition laws, and in tort. b. Outside the United States. If you acquired the Licensed Content in any other country, the laws of that country apply. 14. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the laws of your country. You may also have rights with respect to the party from whom you acquired the Licensed Content. This agreement does not change your rights under the laws of your country if the laws of your country do not permit it to do so. 15. DISCLAIMER OF WARRANTY. The Licensed Content is licensed “as-is.” You bear the risk of using it. Microsoft gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this agreement cannot change. To the extent permitted under your local laws, Microsoft excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement.

16. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES. This limitation applies to • anything related to the Licensed Content, software, services, content (including code) on third party Internet sites, or third party programs; and • claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law. It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the exclusion or limitation of incidental, consequential or other damages. Please note: As this Licensed Content is distributed in Quebec, Canada, some of the clauses in this agreement are provided below in French.

Remarque : Ce le contenu sous licence étant distribué au Québec, Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en français. EXONÉRATION 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 péril. Microsoft n’accorde aucune autre garantie expresse. Vous pouvez bénéficier 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, d’adéquation à un usage particulier et d’absence de contrefaçon sont exclues. LIMITATION DES DOMMAGES-INTÉRÊTS 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 prétendre à aucune indemnisation pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices. Cette limitation concerne: • tout ce qui est relié au le contenu sous licence , aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers ; et • les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur. Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel dommage. Si votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne s’appliquera pas à votre égard. EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas.

MCT USE ONLY. STUDENT USE PROHIBITED

iii 3-3 1-9 2-36 3-14 2-21 3-20 3-27 2-30 1-31 of a Service Oriented Architecture Architecture Oriented of a Service ce in Visual Studio 2008 2008 Studio ce in Visual 1-22 ace As a Service Contract ace As a Service 1-16 Visual Studio® 2008: Windows® CommunicationFoundation Configure and Host a WCF Service a Host and Configure and Behaviors Endpoints Service Changing Creating a Simple Service Service a Simple Creating

ver Different Endpoints Endpoints o ver Different Services Exposing WCF 1: Lesson Deploying a WCF Service a WCF Deploying 5: Lesson Lab: Endpoints to Services and Adding Behaviors 2: Lesson Services Web Non-WCF with Interoperating 3: Lesson Lab: Programmatically Configuring 1: Lesson Application a Managed HostWCF to a 2-3 Service Programmatically Configuring 2: Lesson Application a Managed Call a WCF to 2-12 Service File-Based Client Service and by Using Defining 3: Lesson 2-17 Configuration a WCF Service for Option Hosting a Selecting 4: Lesson (SOA) 1-3 (SOA) Architecture of WCF 2: Overview Lesson Lesson 1: Designing Application an Lesson be Partto Using a Language-Level Interf a Language-Level Using 3: Lesson Implementing a Simple WCF Servi WCF 4: Implementing a Simple Lesson Consuming a simple WCF service in Visual Studio 2008 2008 Studio in Visual simple WCF service a 5: Consuming Lesson Lab: 1-27 Module 3: Endpoints and Behaviors Module 2: Configuring Hostingand WCF Services Contents Contents 1: Module Getting Started with Windows Communication Foundation

MCT USE ONLY. STUDENT USE PROHIBITED 6-3 8-3 7-3 6-8 4-3 7-17 7-31 8-25 8-34 6-17 5-10 5-23 5-30 7-11 8-41 5-16 4-17 8-14 6-24 4-12

to Service-level Faults Faults to Service-level Improving Data Transfer Throughput 7-23 7-23 Throughput Transfer Data Improving : Handling Faults and Exceptions on Exceptions Handling Clients and : Faults : Designing a Coherent and Cohesive WCF Service Interface Interface WCF Service Cohesive and a Coherent : Designing Contract a Service : Defining 5-3 Exceptions .NET : Relating : Defining Operations on a Service on a Service Operations : Defining : Defining a Data Contract Contract a Data : Defining Protecting a Service a Service Protecting Error Handling Error Improving WCF Service Quality Message Logging and Activity Tracing Applying Overall Security Requirements to a Binding to Security Requirements Applying Overall 2: Lesson Service Credentials Client and Required 3: Specifying Lesson with 4: Working Information Security Lesson Lab:

Overview of Security in WCF in WCF of Security Overview 1: Lesson Managing WCF Service Instances Managing 1: Lesson Using Faults in a Service a Using Faults in 2: Lesson 3 Lesson Lab: Issues Concurrency Managing 2: Lesson Improving 3: WCF Service QualityLesson 4: Lesson Lab: Lesson 1 Lesson Lesson 1 Lesson 2 Lesson Logging Messages Messages Logging 1: Lesson Activity Tracing 2: Activity Tracing Lesson Lab: Lesson 3 Lesson Lesson 4 Lesson Lab: Contracts for Services and Data Data and for Services Lab: Contracts Visual Studio® Windows® 2008: CommunicationFoundation Module 8: Implementing WCF Security Module 7: Improving WCF Service Quality Module 6: Handling Errors Module 5: Designing and Defining Contracts Module 4: DebuggingModule Diagnostics and iv MCT USE ONLY. STUDENT USE PROHIBITED

v 9-34 9-10 9-22 L8-151 - L8-166 L9-167 - L9-192 L9-192 - L9-167 ns from Client to Service from Client to Service ns 9-16 Service-Oriented ApplicationService-Oriented 9-3 Visual Studio® 2008: Windows® CommunicationFoundation Endpoints and Behaviors Behaviors and Endpoints Diagnostics and Debugging Contracts Defining and Designing Errors Handling Quality WCF Service Improving L5-104 - L5-75 L3-64 - L3-45 L4-74 - L4-65 Transactions Implementing - L7-150 L7-121 L6-120 L6-105- : Overview of Transactions in a in of Transactions : Overview Operations Service Transactional : Creating Enabling: the Flowof Transactio : Implementing Transactions for a Service a Service for Transactions : Implementing Course Evaluation Evaluation Course

Lab Answer Key 9: Lab Answer Key Lab Answer Key 4: Lab Answer Key 5: Lab Answer Key 6: Lab Answer Key 7: Lab Answer Key 8: ImplementingLab Answer Key WCF Security : Getting Started with Windows Communication Communication Windows with Started 1: Lab Answer Key Getting Foundation 2: ConfiguringLab Answer Key HostingWCF Services and 3: Lab Answer Key L2-44 L2-23 - L1-1 -L1-22 Lesson 1 Lesson Lesson 2 Lesson 3 Lesson Lab Lab Answer Keys Module 9: ImplementingModule Transactions

MCT USE ONLY. STUDENT USE PROHIBITED

1 - Lab: Creating Simplea Service L1

6461A-LON-DEV-01 Student User Name: Virtual Machine: Virtual Machine: Password: Pa$$w0rd Password:

• • Estimated time: 40 minutes Scenario You are team. product Management Clinic Contoso on the developer You are a service in appointments to the assigned been have and you starting development this initial phase. Logon Information: Module 1: Getting Started with Windows Windows Started with 1: Getting Module Foundation Communication a Simple Service Lab: Creating

MCT USE ONLY. STUDENT USE PROHIBITED

. Studio

. 6461-LON- Visual

Pa$$w0rd define a service define a service Student , and then click , and then Open 2008.

to the solution. the solution. to using the password using the Studio

and configure the service's endpoints. endpoints. the service's and configure menu, point to point to menu, Student , point to Microsoft , point Programs Visual Control Client and double-click Control

Internet Information Service (IIS). Service (IIS). Internet Information File rtual machine and log on as on and log rtual machine as All , on the Microsoft . AppointmentHelperClass Windows Communication Foundation menu, point to menu, point to 6461-LON-DEV-01 Start Visual Studio 2008 Visual Studio 2008, and then click Project/Solution solution. DEV-01. 2. In 2. 1. On the the On 1. 1. 1. Server Remote Virtual Open the Task 2: Add a new WCF Service project to the existing ConnectedWCF solution. 2. 2. existing ConnectedWCF the to project Library Service Add a new WCF 3. existing the Add 4. contract. Define the service 5. contract. service Implement the 6. solution. ConnectedWCF the to Application project Add a WCF Service 7. AppointmentService. the service. for endpoints Configure the the Test 8. Task 1: Start the 6461-LON-DEV-01 virtual machine and log on as Student. Finally, you will host the service in host the service in Finally, you will exercise are as follows: for this The main tasks 1. Start the 6461-LON-DEV-01 vi Exercise 1: Creating a Simple WCF Service WCF a Simple Creating 1: Exercise Service the WCF by using service WCF the you will develop In this exercise, then will 2008. You Visual Studio® in Microsoft® Library template to on Log 2. contract, service implement the contract,

f f L1-2 Module 1: Started with Getting MCT USE ONLY. STUDENT USE PROHIBITED 3 - box

, andthen , and then click , and then . box, type box, project, and then and project,

Visual Basic Visual Project

Visual C# Lab: Creating Simplea Service L1 Location New project template. project template. If you are using Visual C#, in If you are using Root namespace Root the tab, in AppointmentService

AppointmentService Application . , and then click then , and : All

box for Visual C#), type Visual for namespace box

E:\Labfiles\Starter\CS\ConnectedWCF Add OK WCF Service Library WCF Service file. file. Save box, type type box, dialog box, define a project with the following the following with a project define dialog box, Default dialog box, browse to either of the following: following: of the either to browse box, dialog Name box, box, type Project

menu, point to menu, click menu, New

. If you are using Visual C#, expand Visual C#, using you are WCF. If Location File File Open Project Open Add Properties. E:\Labfiles\Starter\VB\ConnectedWCF the If you are using Visual C#, browse to the the to Visual C#, browse If you are using double-click the then folder, and E:\Labfiles\Starter\CS\ConnectedWCF ConnectedWCF.sln Name: In the Visual Basic, in the are using Location: If you If you are using Visual Basic, browse to the to the browse Visual Basic, using If you are the double-click then folder, and E:\Labfiles\Starter\VB\ConnectedWCF ConnectedWCF.sln WCF. Templates: Click the click Project types: If you are using Visual Basic, expand Visual Basic, expand If you are using types: Project

• • • • • properties, and then click then and properties, • click (for Visual Basic) or com.contoso.AppointmentService the In 3. 7. on the Properties window, In the 6. 6. the right-click Explorer, In Solution 4. On the the On 4. 5. In the In 5. 8. On the the On 8.

MCT USE ONLY. STUDENT USE PROHIBITED

,

Add folder, file. , and then click , and then dialog box, click dialog box, file. , and then click , and then project, click click project, , type dialog box, browse to the the to browse dialog box, Rename E:\Labfiles\Starter\VB\ E:\Labfiles\Starter\CS\ , click AppointmentHelperClass.vb entHelperClassto the solution. AppointmentService Visual Microsoft . (for Visual Basic) or Basic) (for Visual (for Visual C#), and then press ENTER. ENTER. press and then C#), (for Visual AppointmentServiceContract AppointmentHelperClass IService1 AppointmentHelperClass.cs . Item

C#, change the namespace to namespace the C#, change Windows Communication Foundation Existing . . Add Existing Item - AppointmentService Existing Item - Add Code Code

folder, and then double-click the double-click then folder, and the and then double-click If you are using Visual Basic, browse to the to the Visual Basic, browse If you are using the to Visual C#, browse If you are using .

Yes View com.contoso.AppointmentService View following file: • • AppointmentServiceContract.vb AppointmentServiceContract.cs ... } [Visual C#] ... namespace com.contoso.AppointmentService { and then click and then 3. 3. right-click Explorer, In Solution 4. 4. Visual If you are using 2. 2. Basic, in the Visual If you are using 3. 3. right-click Explorer, In Solution 2. In the In 2. Task 4: Define the service contract. 1. right-click Explorer, In Solution Task 3: Add the existing Appointm 1. the right-click Explorer, In Solution

f f L1-4 Module 1: Started with Getting MCT USE ONLY. STUDENT USE PROHIBITED

5 -

parameter class file, string ] )> _ a DateTime , and . methods in the Lab: Creating Simplea Service L1

doctorId AppointmentServiceContract definition, define a method named a method definition, define and that accepts a and that accepts AppointmentServiceContract interface definition definition interface . attribute on the change the interface name to interface the change ces/AppointmentService parameter named named parameter . GetDataUsingDataContract that returns a string Namespace:= _ AppointmentServiceContract start and , a string ServiceContract AppointmentServiceContract GetData class CompositeType definition The All comments AppointmentServiceContract

The

named patientId AppointmentServiceContract • definition to include the namespace namespace definition to include the http://contoso.com/servi ... [Visual C#] ... [ServiceContract(Namespace = "http://contoso.com/services/AppointmentService") ... [Visual Basic] ...

MCT USE ONLY. STUDENT USE PROHIBITED

value doctorId bool method. method. that returns a returns that . that returns a returns that parameter named named parameter string CreateAppointment CancelAppointment appointmentId . day CancelAppointment ListAvailableAppointmentTimes and accepts a and accepts attribute to the attribute to the parameter named DataTime string parameter named named parameter Windows Communication Foundation of type OperationContract OperationContract List DataTime [Visual C#] ... [OperationContract] bool CancelAppointment(string appointmentId); ... [Visual Basic ... _ Function CancelAppointment(ByVal appointmentId As String) _ As Boolean ... DateTime start); ...... [Visual C#] ... [OperationContract] string CreateAppointment(stringpatientId, stringdoctorId, [Visual Basic ... _ Function CreateAppointment(ByVal patientId As String, _ ByVal doctorId As String,ByVal start As DateTime) As String generic and that accepts a and a 12. 12. method named Define a third 10. 10. named method Define a second the Add 9. 11. Add the the Add 11. L1-6 Module 1: Started with Getting MCT USE ONLY. STUDENT USE PROHIBITED

7 - Lab: Creating Simplea Service L1 class should resemble the resemble class should ListAvailableAppointmentTimes attribute to the AppointmentServiceContract OperationContract _ ByVal day As DateTime) As List(Of DateTime) End Interface _ Function CancelAppointment(ByVal appointmentId As String) _ As Boolean _ Function ListAvailableAppointmentTimes(ByVal doctorId As String, following. [Visual Basic] _ Public InterfaceAppointmentServiceContract _ Function CreateAppointment(ByVal patientId AsString, _ ByVal doctorId As String, ByVal start As DateTime) As String List ListAvailableAppointmentTimes(string doctorId, DateTime day); ... the Your code for ByVal day As DateTime) As List(Of DateTime) ... [Visual C#] ... [OperationContract] [Visual Basic ... _ Function ListAvailableAppointmentTimes(ByVal doctorId As String, _ method. the Add 13.

MCT USE ONLY. STUDENT USE PROHIBITED

, and class: dialog box, click dialog box, , type , type methods class definition to class definition Rename (for Visual Basic) or (for Visual Basic) , click (for Visual C#), and then press and then press (for Visual C#), Service1 . Microsoft Visual Studio Visual Microsoft . AppointmentServiceImplementation Service1 AppointmentServiceImplementation C#, change the namespace to namespace the C#, change GetDataUsingDataContract . and Windows Communication Foundation Code

GetData All comments The .

• • Yes com.contoso.AppointmentService then click View AppointmentServiceImplementation ENTER. ENTER. AppointmentServiceImplementation.vb AppointmentServiceImplementation.cs [OperationContract] List ListAvailableAppointmentTimes(string doctorId, DateTime day); } } public interface AppointmentServiceContract { [OperationContract] string CreateAppointment(string patientId, string doctorId, DateTime start); [OperationContract] bool CancelAppointment(string appointmentId); [Visual C#] ... namespace com.contoso.AppointmentService { [ServiceContract(Namespace = "http://contoso.com/services/AppointmentService")] 3. 3. right-click Explorer, In Solution 6. from the Remove the following 4. 4. Visual If you are using 5 Visual C#, rename the If you are using 2. 2. Basic, in the Visual If you are using Task 5: Implement the service contract. 1. right-click Explorer, In Solution

f L1-8 Module 1: Started with Getting MCT USE ONLY. STUDENT USE PROHIBITED 9 -

object as a Implement method in the , and then pass Lab: Creating Simplea Service L1 as parameters to the to as parameters . newAppointment interface. If you are using Visual If you are using interface. newAppointment and terface terface name generate the method to Interface , and start methods. GenerateNewAppointment class. Pass the Pass the class. in the class definition, point to to definition, point class in the move the following code from the move the following object named named object doctorId , CancelAppointment , patientId AppointmentServiceContract Appointment click Implement then , and method, add code to do the following: following: to do the method, add code CreateAppointment the variables parameter. AppointmentHelperClass Create an constructor. static of the result the Return

Basic, press ENTER after you type the in type the you ENTER after Basic, press stubs. If you are using Visual C#, right-click the text the text C#, right-click are using Visual stubs. If you AppointmentServiceContract ... 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 Basic] ... Public Function CreateAppointment(ByVal patientId As String, _ ... [Visual C#] ... throw new NotImplementedException(); • • Interface CreateAppointment ListAvailableAppointmentTimes 9. In the In 9. the Implement 7. 8. 8. Visual C#, re If you are using

MCT USE ONLY. STUDENT USE PROHIBITED

class. AppointmentHelperClass method in the method, add code to return the result of the static of the result the return to method, add code variable as a parameter. Windows Communication Foundation appointmentId CancelAppointment CancelAppointment Return AppointmentHelperClass.CancelExistingAppointment( _ Pass the Pass the CancelExistingAppointment CancelExistingAppointment ... [Visual C#] ... public bool CancelAppointment(stringappointmentId) { return AppointmentHelperClass.CancelExistingAppointment( appointmentId); } As Boolean Implements AppointmentServiceContract.CancelAppointment appointmentId) End Function ... [Visual Basic] ... Public Function CancelAppointment(ByVal appointmentIdString)As _ doctorId, start); return AppointmentHelperClass.GenerateNewAppointment( newAppointment); } ... [Visual C#] ... public string CreateAppointment(string patientId, string doctorId, DateTime start) { Appointment newAppointment = new Appointment(patientId, 10. In the In 10.

L1-10 Module 1: with Started Getting MCT USE ONLY. STUDENT USE PROHIBITED

11 - variables as variables project, and then and project, day and Lab: Creating Simplea Service L1 doctorId method, add code to return the result result the return to code add method, method in the method in AppointmentService class. Pass the Pass the class. GetAvailableAppointments GetAvailableAppointments . ListAvailableAppointmentTimes ListAvailableAppointmentTimes Build return AppointmentHelperClass.GetAvailableAppointments(doctorId, Return AppointmentHelperClass.GetAvailableAppointments(doctorId, AppointmentHelperClass parameters. of the static of the public List ListAvailableAppointmentTimes(string doctorId, DateTime day) { day); } ... day) End Function ... [Visual C#] ... [Visual Basic] ... Public Function ListAvailableAppointmentTimes(ByVal doctorId _ As String, ByVal day Date)As As System.Collections. _ Generic.List(Of Date)Implements _ AppointmentServiceContract.ListAvailableAppointmentTimes _ click 12. 12. the right-click Explorer, In Solution the In 11.

MCT USE ONLY. STUDENT USE PROHIBITED class should resemble class should AppointmentServiceImplementation Windows Communication Foundation Return AppointmentHelperClass.GetAvailableAppointments( _ doctorId, day) End Function End Class ... Return AppointmentHelperClass.CancelExistingAppointment( _ appointmentId) End Function Public Function ListAvailableAppointmentTimes(ByVal doctorId _ As String, ByVal day As Date) As System.Collections. _ Generic.List(Of Date) Implements _ AppointmentServiceContract.ListAvailableAppointmentTimes Return AppointmentHelperClass. _ GenerateNewAppointment(newAppointment) End Function Public Function CancelAppointment(ByVal appointmentId As String) _ As Boolean Implements _ AppointmentServiceContract.CancelAppointment Public Function CreateAppointment(ByVal patientId As String, _ ByVal doctorId As String, ByVal start As Date) _ As String Implements _ AppointmentServiceContract.CreateAppointment Dim newAppointmentAs New Appointment(patientId, doctorId, _ start) [Visual Basic] ... Public ClassAppointmentServiceImplementation Implements AppointmentServiceContract Your code for the for Your code the following. the following.

L1-12 Module 1: with Started Getting MCT USE ONLY. STUDENT USE PROHIBITED

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

MCT USE ONLY. STUDENT USE PROHIBITED and .

, andthen Files project, and project, and

All project, right- project,

, and then click click and then , . (for Visual C#) (for Visual C#) box, type box, section, click Show Visual Basic Visual 8001 Project

project project template. Visual C# Location Servers tab, double-click double-click tab, AppointmentServiceIISHost AppointmentServiceIISHost New AppointmentService.svc If you are using Visual C#, in If you are using Service.svc.cs Projects , type tab, in the in the tab, AppointmentServiceIISHost AppointmentServiceIISHost AppointmentServiceIISHost AppointmentServiceIISHost AppointmentServiceIISHost Web . AppointmentServiceIISHost AppointmentServiceIISHost , and then click then , and Rename : All

E:\Labfiles\Starter\CS\ConnectedWCF Add OK . WCF Service Application WCF Service (for Visual Basic) or Basic) Visual (for Save box, type type box, dialog box, define a project with the following the following with a project define dialog box, iles and folders from the file, click dialog box, on the on the box, dialog folder class file Name box, box, type Project Windows Communication Foundation

Reference

. If you are using Visual C#, expand C#, using Visual are . If you Data , and then in the corresponding box, type box, corresponding in the and then , menu, click menu, menu, point to New

Web . Service1.svc Service1.svc.vb IService1 App_ Location File File Add Reference Add The The Templates: Click the Templates: Click the Web The E:\Labfiles\Starter\VB\ConnectedWCF Name: In the Basic, in the Visual are using Location: If you the click Project types: If you are using Visual Basic, expand Visual Basic, expand If you are using types: Project

project: • • • click the ENTER. then press AppointmentService. • Specific port • • properties, and then click then and properties, • then click Add . then click Properties 6. 6. in Solution Explorer, click Basic, Visual If you are using 7. Remove the following f 10. 10. the within Explorer, In Solution 5. On the the On 5. 9. In the In 9. 8. 8. the right-click Explorer, In Solution 4. on the Properties window, In the 3. 3. the right-click Explorer, In Solution Task 6:AddTask a WCF Service ApplicationConnectedWCFproject tothe solution. the On 1. the In 2.

f L1-14 Module 1: with Started Getting MCT USE ONLY. STUDENT USE PROHIBITED

. 15 -

and View pane, project, and ServiceHost project, right- project, , and then click click , and then Configuration box, type box, Lab: Creating Simplea Service L1 Name , and then click , and then file: ppointmentServiceImplementation AppointmentServiceIISHost for the AppointmentServiceIISHost.for the section, in the . . Configuration Edit WCF AppointmentServiceIISHost AppointmentServiceIISHost AppointmentService.svc box, type box, type attribute and value. attribute and value. All

ServiceBehaviors st.Service1Behavior. st.Service1Behavior. Save Name General . Services, click AppointmentServiceIISHost.Service1 , expand , expand , and then click CodeBehind Service attribute value to . AppointmentService.svc menu, click menu, in the . Advanced

File Web.config Remove the Change the pointmentServiceImplementation com.contoso.AppointmentService.Ap

element • then click Build • Markup ation" %> [Visual C#] <%@ ServiceHost Language="c#"Debug="true" Service="com.contoso.AppointmentService.AppointmentServiceImplement ation" %> [Visual Basic] <%@ ServiceHost Language="vb"Debug="true" Service="com.contoso.AppointmentService.AppointmentServiceImplement click then press ENTER. ENTER. then press com.contoso.AppointmentService.A expand AppointmentServiceIISHost.ServiceBehavior AppointmentServiceIISHo 14. 14. the right-click Explorer, In Solution 12. 12. the to changes make the following window, Editor Code In the 2. Editorwindow, in the Service Configuration In the WCF Task 7: Configure the endpoints 1. the within Explorer, In Solution 13. On the the On 13. 11. right-click Explorer, In Solution 4. 4. pane under In the left 5. pane, in the right In the 3. 3. pane, in the right In the

f

MCT USE ONLY. STUDENT USE PROHIBITED

,

menu, click menu, project, project, File node. . . Yes , AppointmentService . OK . page, click {EmptyName] Close Listing

ppointmentServiceImplementation AppointmentServiceIISHost dialog box, dialog box, click AppointmentServiceImplementation box, type type box, dialog box, click box, dialog Start new instance Start new iguration Editor window, on the iguration Editor window, Directory Configuration Editor window. Configuration Editor . Contract dialog box, click dialog box, , expand Services, expand Windows Communication Foundation , and then click Debug , and then click the first click the first then , and Endpoints Script Debugging Disabled Debugging Not Not Enabled Debugging Information Bar Information After this exercise, you should have developed a WCF service in Visual . service default page. Internet Explorer will display the AppointmentService.svc com.contoso.AppointmentService.AppointmentServiceContract expand Save point to com.contoso.AppointmentService.A Results: Studio 2008. 7. 7. Explorer. Close Internet 6. 6. the hosted configured and successfully If you have 2. In the In 2. 8. 8. Service Conf Microsoft In the the In 3. 9. 9. Service Microsoft Close the 7 in the right-pane, In the 5. 5. the on Explorer, In Internet 4. In the In 4. 1. 1. the right-click Explorer, In Solution Task 8: Test the AppointmentService. 6. pane under In the left

f L1-16 Module 1: with Started Getting MCT USE ONLY. STUDENT USE PROHIBITED

.

17 - Code

. Go View project, and then click and then project, and then click and then into scope. , and then click then , and Lab: Creating Simplea Service L1 AppointmentServiceReference . OK ClinicAdminClient the existing the existing Windows ClinicAdminClient ClinicAdminForm e Simple WCF Service WCF Service e Simple ClinicAdminClient class. box, type box, type Namespace and then click and then Address box, type comment, and bring the the and bring comment, linicAdminClient class. linicAdminClient Reference. TODO 1 TODO dialog box, define a service reference with the the with reference define a service dialog box, Reference Service Add Service

http://localhost:8001/AppointmentService.svc ClinicAdminClient.AppointmentServiceReference //TODO 1. usingClinicAdminClient.AppointmentServiceReference; ... 'TODO 1. Imports ClinicAdminClient.AppointmentServiceReference ... [Visual C#] ... [Visual Basic] ... Add following information, a. In the Address: b. the Namespace: In 1. 1. right-click Explorer, In Solution 2. In the In 2. Task 2: Add code to the Task 1: Add a reference to the AppointmentService. 1. the right-click Explorer, In Solution Exercise 2: Calling th 2: Calling Exercise code to you will add In this exercise, timeslots, the available appointment users to find all Forms to enable application appointment. existing delete an and appointment, create a new exercise are as follows: for this The main tasks 1. AppointmentService. to the Add a reference 2. C the to code Add the Locate 2. 3. solution. the and run Build

f f

MCT USE ONLY. STUDENT USE PROHIBITED

, and then , and then proxy class. Pass the proxy object object called GetAppointmentServiceProxy method in the in the method object. object. property of the of the field and the Value property doctorId return value of the of the value return comment, and then add code to do the following: the following: do code to add and then comment, comment, and then add code to return a new a new return code to add and then comment, field as parameters. field as parameters. AppointmentServiceContract object to the return value of the value of the return to the object Windows Communication Foundation TODO 3 TODO TODO 2 TODO initialize it to the method. slots Set the ListAvailableAppointmentTimes dateRequested Text property of the Create a new returnAppointmentServiceContractClient(); new ReturnAppointmentServiceContractClient() New

• • AppointmentServiceContractClient ' TODO 3. Dim proxyAppointmentServiceContract As _ = GetAppointmentServiceProxy() slots = proxy.ListAvailableAppointmentTimes(doctorId.Text, _ dateRequested.Value) ... [Visual Basic] ...... private AppointmentServiceContract GetAppointmentServiceProxy() { // TODO 2. } ... ' TODO 2. End Function ... [Visual C#] [Visual Basic] ... Private Function GetAppointmentServiceProxy() As _ AppointmentServiceContract 4. Locate the the Locate 4. the Locate 3. L1-18 Module 1: with Started Getting MCT USE ONLY. STUDENT USE PROHIBITED

19

-

slot , and , and property of property proxy Text field, and the Lab: Creating Simplea Service L1 doctorId object named named object class. Pass the class. Pass the GetAppointmentServiceProxy proxy property of property the Text variable to the returnvalue of the method in the in the method comment, and then add code to do the following: the following: do code to add and then comment, AppointmentServiceContract field, the TODO 4 TODO patientId the variable as parameters. CreateAppointment method. appointmentId Set the then initialize it to the return value of the return value the then initialize it to Create a new

• • ... [Visual C#] ... // TODO 4. AppointmentServiceContract proxy = GetAppointmentServiceProxy(); appointmentId = proxy.CreateAppointment(patientId.Text, doctorId.Text, slot); ... ' TODO 4. Dim proxyAppointmentServiceContract As _ = GetAppointmentServiceProxy() appointmentId = _ proxy.CreateAppointment(patientId.Text, doctorId.Text, slot) ... [Visual Basic] ... [Visual C#] ... // TODO 3. AppointmentServiceContract proxy = GetAppointmentServiceProxy(); slots = proxy.ListAvailableAppointmentTimes(doctorId.Text, dateRequested.Value); 5. Locate the the Locate 5.

MCT USE ONLY. STUDENT USE PROHIBITED

, and , and proxy appointmentId CancelAppointment CancelAppointment object named named object GetAppointmentServiceProxy property of the property class. Pass the Text class. variable to the return value of the the value of return variable to the comment, and then add code to do the following: the following: do code to add and then comment, proxy AppointmentServiceContract Windows Communication Foundation TODO 5 TODO method in the method. cancelled Set the field as a parameter. then initialize it to the return value of the of the value return it to the then initialize Create a new Create a new

• • // TODO 5. AppointmentServiceContract proxy = GetAppointmentServiceProxy(); cancelled = proxy.CancelAppointment(appointmentId.Text); ... = GetAppointmentServiceProxy() cancelled = proxy.CancelAppointment(appointmentId.Text) ... [Visual C#] ... [Visual Basic] ... ' TODO 5. Dim proxyAppointmentServiceContract As _ the Locate 6. L1-20 Module 1: with Started Getting MCT USE ONLY. STUDENT USE PROHIBITED

21 : -

tab, Create . Appointment Appointment Appointment

. Debugging

OK Lab: Creating Simplea Service L1 Stop box, type your your type box, . . Appt ID form, on the Create the methods in the AppointmentService. methods in the AppointmentService. the llowing information, and then click information, and llowing dialog box, click box, dialog Debugging . ENT_Davies. Solution

tab, in the the tab, in . dialog box, make a note of the the of make a note box, dialog Start box, type your name. your name. box, type Build Delete OK list, click list, list, click any of the available time slots. of the available time list, click any Patient Slots . Doctor menu, click menu, menu, click Slots

, and then click and then , , and then click and then , Cancel Appointment Cancel Build Debug Client Administration Clinic Appointment Cancellation Appointment Appointment Created Appointment After this exercise, you should have enhanced the existing Find Slots: In the Doctor: In In Doctor: Patient: In the the Patient: In

identifier • • identifier • click Results: to invoke ClinicAdminClient application 7. In the In 7. 8. In Visual Studio 2008, menu, click onthe Debug 4. 4. the fo with Create an appointment 6. On the the On 6. 9. 9. 2008. Close Visual Studio 5. In the In 5. 2. On the the On 2. the On 3. Task 3: Build and run the solution. the On 1.

f

MCT USE ONLY. STUDENT USE PROHIBITED

23 - Lab: Configure andHost a WCF Service L2 ce and your task now is to look at the task now is to ce and your

6461A-LON-DEV-02 Student User Name: Virtual Machine: Virtual Machine: Password: Pa$$w0rd Password:

• Estimated time: 80 minutes Logon Information: • Scenario Your team team. product Management Clinic Contoso on the developer You are a servi appointment of the part has developed the and hosting settings WCF configurations the different ways of storing appointments service. Module 2: Configuring and Hosting WCF Hosting WCF and 2: Configuring Module Services a WCF and Host Lab: Configure Service

MCT USE ONLY. STUDENT USE PROHIBITED

.

6461- Studio

as

menu, . Run File Visual

Pa$$w0rd Student .

to host the appointment to host the appointment Continue , and then click 2008, and then

using the password using the Studio

Student , point to Microsoft , point Programs

. Project/Solution as ogrammatically Configured Configured ogrammatically virtual machine and log on as on and log virtual machine All Visual

to Host a Service a Service Host to ess in the ClinicAdminClient. ess in the ClinicAdminClient. velop an EXE application velop an the AppointmentService. AppointmentService. the

, and then click , and then menu, point to menu, point to 6461-LON-DEV-02 6461-LON-DEV-02 Open Start dialog click box, User Account point to point to 2008, right-click Microsoft administrator LON-DEV-02. 3. 3. on the system, development Visual Studio® 2008 In Microsoft® 2. In the In 2. 2. Log on to to on Log 2. Task 2: Open the existing ConnectedWCF solution the On 1. Task 1: Start the 6461-LON-DEV-02 virtual machine and log on as Student 1. double-click Client, and then Control Server Remote Virtual Open the Exercise 1: Creating a Pr 1: Creating Exercise you will de In this exercise, Application Managed service. exercise are as follows: for this The main tasks the Start 1. 2. solution. ConnectedWCF existing Open the 3. solution. ConnectedWCF the to application Console new Windows a Add 4. host to code Add 5. addr endpoint Change the 6. projects. startup solution ConnectedWCF Set the 7. the solution. Build and run

f f L2-24 Module 2: Configuring and Hosting WCF Services MCT USE ONLY. STUDENT USE PROHIBITED

25

-

Name

Name , andthen

project, and project, project, and project, , and then , and then . Project . box, type box, Component Visual C# Visual Basic Visual Project

Location tab, in the tab, in New assembly. assembly. box, type box, type assembly. tab, in the the tab, in Lab: Configure andHost a WCF Service L2 WCF folder, and then double-click folder, and WCF WCF folder, and then double-click folder, WCF Projects .NET sic® development system, go to the the to go system, sic® development Location AppointmentServiceSelfHost AppointmentServiceSelfHost , and then click then , and . file. file. Add OK . . AppointmentService System.ServiceModel ConsoleApplication project template. box type AppointmentServiceSelfHost dialog box, define a project with the following the following with a project define dialog box, dialog box, on the on the box, dialog dialog box, on the on the box, dialog dialog box, go to either of the following: following: the of either to go box, dialog Name Project

Reference Reference

menu, point to New

. If you are using Visual C#, expand Visual C#, expand using Windows. If you are Windows. ConnectedWCF.sln ConnectedWCF.sln File Add Reference Add Reference Add Open Project Open click click Templates: Click the Project types: If you are using Visual Basic, expand Basic, expand Visual If you are using types: Project If you are using Visual C#, in the Visual C#, in the If you are using E:\Labfiles\Starter\CS\Ex1\ConnectedWCF Location: If you are using Visual Basic, in the Visual Basic, in the are using Location: If you E:\Labfiles\Starter\VB\Ex1\ConnectedWCF the the go to tool, Visual C#® development Microsoft If you are using E:\Labfiles\Starter\CS\Ex1\Connected Name: In the If you are using Microsoft Visual Ba Microsoft using If you are E:\Labfiles\Starter\VB\Ex1\Connected the

column, double-click the column, double-click then click Add column, double-click the column, double-click then click Add properties, and then click then and properties, • • • • • • 4. In the In 4. 3. 3. the right-click Explorer, In Solution 2. In the In 2. Task 4: Add code to host the AppointmentService 1. the right-click Explorer, In Solution 2. In the In 2. 1. On the the On 1. Task 3: Add a new application to the solutionConnectedWCF the In 4.

f f

MCT USE ONLY. STUDENT USE PROHIBITED

. namespace namespace instanceType . PassbaseAddress the class (for Visual Basic) or Visual class (for System.ServiceModel as a parameter. a parameter. as object named named object ppointmentServiceImplementation Module1 Uri st:8002/Contoso object. Initialize the named instanceType Type method, create a new new a create method, class (for Visual C#), bring the Visual C#), bring class (for Main http://localho ... Dim instanceType As Type = _ GetType(com.contoso.AppointmentService. _ AppointmentServiceImplementation) ...... [Visual Basic] Dim baseAddressUri("http://localhost:8002/Contoso") As New ... [Visual C#] ... Uri baseAddressnew Uri("http://localhost:8002/Contoso"); = ... [Visual Basic] ... Imports System.ServiceModel ... [Visual C#] ... using System.ServiceModel; [Visual Basic] ... object to to object com.contoso.AppointmentService.A string Program into scope. into scope. 7. 7. Create a new 6. In the In 6. 5. the for window Editor In the Code L2-26 Module 2: Configuring and Hosting WCF Services MCT USE ONLY. STUDENT USE PROHIBITED

27 - and instanceType block (for Visual C#), andVisual block (for then . Pass the Lab: Configure andHost a WCF Service L2 host constructor. constructor. using ServiceHost object named object ServiceHost ServiceHost object as a parameter. as object objects to the block (for Visual Basic) or Visual (for block host Using [Visual Basic] using (host) { } ... End Using ... [Visual C#] ...... Using host ... [Visual C#] ... ServiceHost host = new ServiceHost(instanceType,baseAddress); ... [Visual Basic] ... AsDim host New ServiceHost(instanceType, baseAddress) [Visual C#] ... Type instanceType = typeof(com.contoso.AppointmentService. AppointmentServiceImplementation); ... baseAddress pass the 9. Add a Add 9. 8. 8. a new Create

MCT USE ONLY. STUDENT USE PROHIBITED .

variable variable contractType

, and then initialize it , and relativeAddress . Initialize the contractType object. To do this, invoke the the this, do To invoke object. object. Pass object. the block (for Visual C#), add code Visual C#), add code (for block host object. object. object. relativeAddress using host host . object, and the the and object, class named Type class named ssageto the console: endpoint to the method on the host class to stop the console console the stop class to method on the Console variable named variable WsHttpBinding object to object string method on the on method Open method on the on the Close method ReadLine block (for Visual Basic) or (for Visual block WSHttpBinding Using from closing. relativeAddress) host.Open() Console.WriteLine("Appointment service " & _ "running. Press to quit.") Console.ReadLine() host.Close() End Using ... [Visual Basic] ... Using host Dim contractType As Type = _ GetType(com.contoso.AppointmentService. _ AppointmentServiceContract) Dim relativeAddress As String = "AppointmentService" host.AddServiceEndpoint(contractType, New WSHttpBinding(), _ AddServiceEndpoint contractType pointmentServiceImplementation com.contoso.AppointmentService.Ap AppointmentService text to the variable, a new as parameters. to quit. Appointment service running. Press g. Invoke the g. Invoke c. Add a c. Add d. Invoke the Invoke d. to do the following: to do the following: a. the of Create a new instance b. Create a new e. following me Write the the f. Invoke the In 10. L2-28 Module 2: Configuring and Hosting WCF Services MCT USE ONLY. STUDENT USE PROHIBITED

29 - . project, right-click the the right-click project, Lab: Configure andHost a WCF Service L2 (for Visual C#) file, and then click (for Visual C#) Editor, in the left pane, expand the the left Editor, in folder, and then click and then folder, App.config property to to Address property , and then close the Microsoft Service Microsoft close the , and then Client ClinicAdminClient . Save :8002/Contoso/AppointmentService menu, click menu, (for Visual Basic) or folder under the the under folder File ... 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 to quit."); Console.ReadLine(); host.Close(); } [Visual C#] ... http://localhost Configuration Editor. Edit WCF Configuration Endpoints . WSHttpBinding_AppointmentServiceContract app.config 4. On the the On 4. 3 the change pane, right In the Task 5: Change the endpoint address in the ClinicAdminClient 1. in the Explorer, In Solution

2 Service Configuration Microsoft In the

f

MCT USE ONLY. STUDENT USE PROHIBITED

. Set . Set tab, . OK Multiple Start . Appointment

projects to Debugging

solution, and then click solution, for the for dialog box, click box, dialog dialog box, click box, dialog Stop Action . available appointments. . None. form, on the Create ConnectedWCF ClinicAdminClient Debugging list, set the the list, set Solution

and Start Build . . . You should see the list of see the . You should menu, click menu, menu, click Projects Slots for the remaining projects to remaining projects for the

projects

Build Debug Solution 'ConnectedWCF' Property Pages 'ConnectedWCF' Solution Solution 'ConnectedWCF' Property Pages 'ConnectedWCF' Solution Multiple startup projects Clinic Administration Client Administration Clinic After this exercise, you should have developed an EXE host for the After this exercise, you should have developed an EXE Find Action Startup

click startup AppointmentServiceSelfHost the In the Appointment service running. Press to quit. Appointment service running. Press Set Results: appointment service. 4. In Visual Studio 2008, menu, click on Debug the 3. In the In 3. 4. In the In 4. Task 7: Build and run the solution the On 1. 2. On the the On 2. 3. message: display the following window to Wait for the Console Task 6: Set the ConnectedWCF solution startup projects projects startup solution ConnectedWCF the 6: Set Task 1. the right-click Explorer, In Solution

2. In the In 2.

f f L2-30 Module 2: Configuring and Hosting WCF Services MCT USE ONLY. STUDENT USE PROHIBITED

31 -

, and then click , ClinicAdminClient file (for Visual C#). Open element and all its sub- project, double-click the the double-click project, Lab: Configure andHost a WCF Service L2 WCF folder, and then double-click folder, and then double-click WCF WCF folder, and then double-click folder, and then double-click WCF App.config define the WCF configuration for the configuration WCF define the menu, point to fine the endpoint configuration. configuration. endpoint fine the . the configuration file, remove the ice Hosted in a Managed in a Managed ice Hosted All endpoint configuration the from

file. file. ClinicAdminClient system.serviceModel> oint configuration from the configuration from the oint Save

configuration file. Project/Solution • • app.config elements. < 3. solution. the and run Build 2. 2. de to add code Programmatically Task 1: Remove the existing 1. In Visual Studio 2008,on File the Application by Using Programmatic Configuration Configuration Programmatic by Using Application ClinicAdminClient exercise are as follows: for this The main tasks 1. endp existing Remove the ClinicAdminClient configuration file Exercise 2: Calling a Serv 2: Calling Exercise you will programmatically In this exercise,

2. In the In 2. 3. 3. in the Explorer, In Solution 5. On the the On 5. 4. 4. for window Editor In the Code

f

MCT USE ONLY. STUDENT USE PROHIBITED .

proxy . to the . Pass address named binding namespace into CreateChannel and objects address class, and then click and then class, class named class named class named class named binding class that is specific to the to the specific class that is method, and then remove the remove the then and method, System.ServiceModel method, add code to do the following: following: the do to code add method, ClinicAdminForm Pass the type. AppointmentServiceContract EndpointAddress EndpointAddress WSHttpBinding ChannelFactory object to the return value of the value of the return to the object lly add code to define the endpoint object to the method caller. method to the object proxy proxy http://localhost:8002/Contoso/AppointmentService . GetAppointmentServiceProxy GetAppointmentServiceProxy Code

method of the form of the of the form of the method AppointmentServiceContract as parameters in the method call. the method in as parameters the text the text constructor. e. Return the the e. Return d. Instantiate the d. Instantiate a. the of new instance Create a b. the of Create a new instance c. variable of type Create a new Return proxy End Function... 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) [Visual Basic] ... [Visual Basic] ... Imports System.ServiceModel ... View scope. code. body existing method 3. Locate the the Locate 3. Task 2: Programmatica configuration 1. the right-click Explorer, In Solution the In 4.

2. 2. the Visual Basic, bring If you are using

f L2-32 Module 2: Configuring and Hosting WCF Services MCT USE ONLY. STUDENT USE PROHIBITED

33 - tab,

. Appointment

" + Debugging

ClinicAdminClient Stop and Lab: Configure andHost a WCF Service L2 . available appointments. . ve programmatically defined the ve programmatically WCF form, on the Create Debugging Solution

http://localhost:8002/ Start Build AppontmentServiceSelfHost . You should see the list of see the . You should menu, click menu, menu, click Slots

Build Debug Clinic Administration Client Administration Clinic After this exercise, you should ha Find click ... "Contoso/AppointmentService"); WSHttpBinding binding= new WSHttpBinding(); AppointmentServiceContract proxy = ChannelFactory. CreateChannel(binding,address); return proxy; } [Visual C#] ... private AppointmentServiceContract GetAppointmentServiceProxy() { EndpointAddress address = new EndpointAddress(" Appointment service running. Press to quit. Appointment service running. Press In the projects. projects. Results: the configuration for 4. In Visual Studio 2008, menu, click on Debug the Task 3: Build and run the solution the On 1. 2. On the the On 2. 3. message: display the following window to Wait for the Console

f

MCT USE ONLY. STUDENT USE PROHIBITED

, and , and . File

project, project, General Application , and then click , and then dialog box, do the the do box, dialog Configuration pane, click pane, Open

projects and then provide provide then and projects pane, click WCF folder, and then double-click folder, and then double-click WCF WCF folder, and then double-click folder, and then double-click WCF project. AppointmentServiceSelfHost Categories Application Templates AppointmentServiceSelfHost menu, point to point to menu, Item.

e Settings by Using External Using External by e Settings File ClinicAdminClient project. : New file. file. and Add configuration file to the . AppointmentServiceSelfHost , on the

al configuration files. al iguration file to the iguration file to the dialog box, go to either of the following: the following: of either to go box, dialog project. project. File

.

pane, click Templates , and then click , Add ConnectedWCF.sln ConnectedWCF.sln Add New Item - Item New Add Open Project Open Configuration then in the then in If you are using Visual Basic, in the Visual Basic, in the If you are using If you are using Visual C#, in the Visual C#, in the If you are using the If you are using Visual Basic, go to the to Visual Basic, go If you are using E:\Labfiles\Starter\VB\Ex3\Connected the the to C#, go Visual If you are using E:\Labfiles\Starter\CS\Ex3\Connected Visual Studio 2008 Visual Studio

following, and then click • Project/Solution AppointmentServiceSelfHost ClinicAdminClient • point to point to • • 1. In 1. Task 1: Add an external AppointmentServiceSelfHost project Exercise 3: Defining Servic 3: Defining Exercise the F programmatic WC remove the you will In this exercise, from configuration AppointmentServiceSelfHost exercise are as follows: for this The main tasks 1. conf an external Add Configuration extern the configuration in 2. 2. the from configuration endpoint programmatic the Remove 3. the from configuration endpoint programmatic the Remove 4. In the In 4. 2. In the In 2. 4. the solution. Build and run 3. 3. the right-click Explorer, In Solution

f L2-34 Module 2: Configuring and Hosting WCF Services MCT USE ONLY. STUDENT USE PROHIBITED

35 -

and

constructor. constructor. folder, and then project, right-click right-click project, project, right-click right-click project, file (for Visual C#), and (for Visual C#), file ServiceHost class (for Visual C#), and class (for Visual Endpoints Lab: Configure andHost a WCF Service L2 anges to the existing code: existing code: the anges to App.config . Program object. baseAddress itor, in the left pane, right-click the the left pane, right-click itor, in ppointmentServiceImplementation ppointmentServiceImplementation endpoint configuration from the . dpoint with the following information: the following information: dpoint with

box, type box, type New Service New parameter from the from parameter

. AppointmentServiceSelfHost AppointmentServiceSelfHost host:8002/Contoso/AppointmentService Name Name . string. Endpoint

folder, right-click the Services folder, baseAddress Code

file (for Visual Basic) or the the Basic) or file (for Visual http://local wsHttpBinding class (for Visual Basic) or class (for Visual method, make the following ch make method, APService_WsHTTP Service

node, and then click and then node, Main New relativeAddress Name: Binding: Address: Contract: com.contoso.AppointmentService.AppointmentServiceContract Module1 app.config

c. and object contractType defines the that code Remove the the • then click View a. defines the that code Remove the the Configuration WCF Edit then click Services the b. Remove folder under the the folder under click • • then press ENTER. ENTER. then press com.contoso.AppointmentService.A com.contoso.AppointmentService.A • Configuration Editor. 9. 9. en pane, define a new right In the 2. In the In 2. 6. 6. Ed Configuration Service In Microsoft AppointmentServiceSelfHost project Task 2: Remove the programmatic 1. in the Explorer, In Solution 8. 8. pane, expand the In the left 5. in the Explorer, In Solution 7. pane, in the right In the 10. 10. Service Microsoft close the then and File menu, click Save, On the 11. All. click Yes to dialog box, Visual Studio Microsoft In the

f

MCT USE ONLY. STUDENT USE PROHIBITED

host semble the following. semble object. object. "running. Press to quit."); Console.ReadLine(); host.Close(); } } ... AppointmentServiceImplementation); ServiceHost host = new ServiceHost(instanceType); using (host) { host.Open(); Console.WriteLine("Appointment service " + [Visual C#] ... static void Main(string[]args) { Type instanceType = typeof(com.contoso.AppointmentService. & "running. Press to quit.") Console.ReadLine() host.Close() End Using End Sub ... 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 " _ [Visual Basic] ... Your code should re d. d. to the endpoint service a new adds that line of code the Remove

L2-36 Module 2: Configuring and Hosting WCF Services MCT USE ONLY. STUDENT USE PROHIBITED

37 , - Client

object. object. . . ppointmentServiceContract ppointmentServiceContract project, right-click the the right-click project, project, right-click the the right-click project, file (for Visual C#), and file (for then Lab: Configure andHost a WCF Service L2 method, and then do the following: do the then and method, View Code New Client Endpoint Client New endpoint configurationendpoint from the endpoint with the following information: information: following endpoint with the App.config ion Editor, in the left pane, expand the left pane, expand ion Editor, in

. AppointmentServiceContractClient

, and then close the Microsoft Service Microsoft close the , and then ClinicAdminClient ClinicAdminClient host:8002/Contoso/AppointmentService Save , and then click click , and then class, and then click then class, and AppointmentServiceReference.A http://local wsHttpBinding menu, click menu, APService_WsHTTP file (for Visual Basic) or file (for Visual Basic) GetAppointmentServiceProxy Endpoints returnAppointmentServiceContractClient(); new File Edit WCF Configuration Edit WCF Name: Binding: Address: Private Function GetAppointmentServiceProxy() As_ AppointmentServiceContract Return New AppointmentServiceContractClient() End Function ... [Visual C#] ... private AppointmentServiceContract GetAppointmentServiceProxy() { } ... [Visual Basic] ... Contract:

• • • right-click Configuration Editor. • ClinicAdminForm a. code. body method existing the Remove b. new a return to code Add app.config click 3. 3. client define a new pane, right In the 4. On the the On 4. 5. in the Explorer, In Solution 6. Locate the the Locate 6. 2. 2. Service Configurat Microsoft In the ClinicAdminClient project project ClinicAdminClient Task 3: Remove the programmatic 1. in the Explorer, In Solution

f

MCT USE ONLY. STUDENT USE PROHIBITED

tab, . Appointment

Debugging

Stop projects in external . available appointments. . defined the WCF configuration for the defined the WCF configuration form, on the Create Debugging Solution

ClinicAdminClient Start and Build . You should see the list of list see the . You should menu, click menu, menu, click Slots

Build Debug Clinic Administration Client Administration Clinic After this exercise, you should have After this exercise, you Find click In the Appointment service running. Press to quit. to running. Appointment service Press Results: AppontmentServiceSelfHost configuration files. 4. Studio In Visual menu, click 2008,on the Debug 2. On the the On 2. 3. message: display the following to window for the Console Wait Task 4: Build and run the solution the On 1.

f L2-38 Module 2: Configuring and Hosting WCF Services MCT USE ONLY. STUDENT USE PROHIBITED

39 - . and the application. . Administrative application. . . application. Application

Continue Add Lab: Configure andHost a WCF Service L2 Internet Information Services (IIS) (IIS) Services Information Internet , and, then expand Sites Web . AppointmentServiceIISHost (IIS) Manager window, in the left pane, in the left Manager window, (IIS) System Maintenance AppointmentServiceIISHost rent Hosting Options for a Options rent Hosting ClinicAdminClient , and then click , and then AppointmentServiceIISHost solution startup projects. projects. startup solution oints to both the oints to projects. projects. menu, click Default Web Site . LON-DEV (LON-DEV\Student) LON-DEV Start ConnectedWCF User Account Control dialog click box, User Account

. expand Manager Tools 6. In the Internet Information Services 4. 4. window, Tools In click the Administrative the In 5. 7. Right-click 6. Set the the Set 6. 7. the solution. Build and run 5. 5. for the TCP binding Configure a 3. click Maintenance window, and Panel\System In the Control 4. 4. for the endpoint TCP Configure a 2. Panel click window, In the Control Task 1: Add a new Application directory to IIS the On 1. Exercise 4: Employing Diffe 4: Employing Exercise you use WAS, To with WAS. service the appointment you will host In this exercise, endp will add additional Service ClinicAdminClient exercise are as follows: for this The main tasks 1. IIS. to directory Application a new Add 2. configuration. WAS the to binding Add the net.tcp 3. for the support Enable TCP

f

MCT USE ONLY. STUDENT USE PROHIBITED

. Edit Run as Run as file, and then . . . folder, right-click folder, the , right-click the , right-click Edit Continue Continue file, and then click file, and then click ctedWCF\AppointmentServiceIISH ctedWCF\AppointmentServiceIISH

E:\Labfile\Starter\ E:\Labfile\Starter\ file, and then click E:\Labfiles\Starter\ . . dialog box, add a new application with the following the following application with new box, add a dialog OK AppointmentServiceIISHostTcpSupport.cmd AddTcpBindingToWas.cmd . AppointmentServiceIISHost . If you are using Visual C#, go to . If you are . Add Application Add User Account Control dialog click box, User Account User Account Control dialog click box, User Account Run as administrator ost E:\Labfiles\Starter\CS\Ex4\Conne ost Physical path: If you are using Visual Basic, go to Visual Basic, go If you are using Physical path: E:\Labfiles\Starter\VB\Ex4\Conne Alias:

and then press ENTER. and then press ENTER. click and then press ENTER. and then press ENTER. administrator AppointmentServiceIISHostTcpSupport.cmd • details, and then click details, and • AddTcpBindingToWas.cmd 5. 5. successfully, executed the command ensure Prompt window, In the Command 6. Explorer. Close Windows 4. In the In 4. 5. 5. successfully, executed the command ensure Prompt window, In the Command 4. In the In 4. 2. 2. Notepad. close then and command, Examine the the Right-click 3. Task 3: Enable TCP support for the AppointmentServiceIISHost application 1. the in Explorer, In Windows 9. 9. Manager window. (IIS) Services Information Internet Close the Task 2: Add net.tcpthe binding to the WASconfiguration 1. to go Explorer, In Windows 2. 2. Notepad. close then and command, Examine the the Right-click 3. the In 8.

f f L2-40 Module 2: Configuring and Hosting WCF Services MCT USE ONLY. STUDENT USE PROHIBITED

41 - , .

. . project, right-click right-click project, , and then click click , and then New Client Endpoint Client New folder, and then double- then folder, and folder, and then double- then folder, and Open Endpoint

project, right-click the the right-click project, file (for Visual C#), and file (for then Lab: Configure andHost a WCF Service L2 Service

ppointmentServiceImplementation New n Editor, in the left pane, under the the pane, under the left n Editor, in App.config for the AppointmentServiceIISHost , and then click , and then Edit WCF Configuration Edit WCF or the ClinicAdminClient application ClinicAdminClient or the menu, point to menu, file. file. File . ice endpoint with the following details: ice endpoint with the following details: , and then close the WCF Configuration Editor. Configuration WCF close the , and then

ClinicAdminClient AppointmentServiceIISHost

Endpoints Save , expand , expand Services , on the , and then click , and then

dialog box, go to either of the following: the following: of either to go box, dialog . file, and then click netTcpBinding ConnectedWCF.sln ConnectedWCF.sln APService_TCP menu, click menu, file (for Visual Basic) or file (for Visual Basic) Endpoints File Open Project Open folder, right-click folder, Edit WCF Configuration Edit WCF Name:

Address: net.tcp://localhost:9090/AppointmentServiceIISHost/AppointmentSer viceIISHost.svc If you are using Visual Basic, go to the to Visual Basic, go If you are using E:\Labfiles\Starter\VB\Ex4\ConnectedWCF click the Binding: If you are using Visual C#, go to the to Visual C#, go If you are using E:\Labfiles\Starter\CS\Ex4\ConnectedWCF click the Contract: com.contoso.AppointmentService.AppointmentServiceContract Web.config Visual Studio 2008 Visual Studio

Client • app.config click Project/Solution • right-click • com.contoso.AppointmentService.A • • the • Task5:Configure a TCP bindingf 1. in the Explorer, In Solution 2. Service Configuratio Microsoft In the 5. 5. define a serv right-pane, In the Task4:ConfigureTCP endpoint a In 1. application 2. In the In 2. 4. 4. pane, under In the left 3. 3. in the Explorer, In Solution 6. On the the On 6.

f f

MCT USE ONLY. STUDENT USE PROHIBITED

View ) ); constructor. constructor. , and then click , class, locate the locate the class, "APService_TCP" "APService_TCP" ppointmentServiceContract ppointmentServiceContract endpoint with the following information: with the following endpoint ClinicAdminForm ClinicAdminForm method, and then pass the string pass the and then method, , and then close the Microsoft Service Microsoft the close , and then

Save AppointmentServiceContractClient

to the to the AppointmentServiceReference.A netTcpBinding netTcpBinding menu, click menu, APService_TCP File . Name: Address: net.tcp://localhost:9090/AppointmentServiceIISHost/AppointmentSer viceIISHost.svc Binding: Contract:

• ... [Visual C#] ... private AppointmentServiceContract GetAppointmentServiceProxy() { return new AppointmentServiceContractClient( } [Visual Basic] ... Private Function GetAppointmentServiceProxy() As_ AppointmentServiceContract Return New AppointmentServiceContractClient( End Function ... Code • • • APService_TCP APService_TCP Configuration Editor. Configuration Editor. GetAppointmentServiceProxy 3. client a new pane, define right In the 6. 6. for the window, Editor In the Code 4. On the the On 4. 5. the right-click Explorer, In Solution L2-42 Module 2: Configuring and Hosting WCF Services MCT USE ONLY. STUDENT USE PROHIBITED

43 -

, and tab, . OK Single . Appointment

Debugging

dialog box, click box, dialog dialog box, click box, dialog Stop Solution 'ConnectedWCF' Solution Lab: Configure andHost a WCF Service L2 . available appointments. . hosted the appointment service in IIS form, on the Create Debugging Solution

. Start Build Projects

. You should see the list of see the . You should . menu, click menu, Startup

menu, click Slots

project

Build Debug Solution 'ConnectedWCF' Property Pages 'ConnectedWCF' Solution Solution 'ConnectedWCF' Property Pages 'ConnectedWCF' Solution Clinic Administration Client Administration Clinic After this exercise, you should have Find startup click then click Set Results: WAS. using 3. In the In 3. 4. In Visual Studio 2008, menu, click onthe Debug 2. In the In 2. 1. On the the On 1. Task 7: Build and run the solution the On 2. the In 3. Task 6: Set the ConnectedWCF solution startup projects projects startup solution ConnectedWCF the 6: Set Task 1. right-click window, Explorer In the Solution

f f

MCT USE ONLY. STUDENT USE PROHIBITED

45 - interoperate with an existing ASP.NET interoperate with Lab: Changing Service Endpoints and Behaviors L3 ment with exposing a metadata endpoint, endpoint, a metadata ment with exposing

6461-LON-DEV-03 Student Virtual Machine: Virtual Machine: User Name: Password: Pa$$w0rd Password:

Estimated time: 60 minutes Logon Information: • • Scenario Your product team. Management Clinic Ltd Contoso, on the developer You are a manager has asked you to look at exposing the Appointment service to both the a little by removing down security lock and to clients and intranet Internet also experi must You metadata endpoint. to service Letter Patient and configuring the Module 3: Endpoints and Behaviors and Behaviors 3: Endpoints Module Endpoints Service Changing Lab: and Behaviors legacy Web service. •

MCT USE ONLY. STUDENT USE PROHIBITED

. 2008,

6461-LON- Studio

Pa$$w0rd wsHttpBinding netTcpBinding Run as Run as . Visual , and then click ,

and a Open Continue Microsoft endpoint to the Appointment Appointment the to endpoint using the password using the , click wsHttpBinding 2008, and then click machine and log on as Student. as Student. on and log machine and FPAdminClient client applications. FPAdminClient client applications. and by Using Different Bindings Different Bindings by Using

You will then manually generate a service generate a service manually will then You menu, point to Student ool. You will then add the necessary WCF necessary the will then add ool. You Control Client and double-click Control minClient project and configure a configure and minClient project as Programs wsHttpBiniding Studio

All and a and a Visual

. binding. binding. . u will configure both a u will configure menu, click Microsoft 6461-LON-DEV-03 Start User Account Control dialog click box, User Account netTcpBinding netTcpBinding binding. service. DEV-03. right-click Project/Solution administrator 7. 7. projects. startup solution ConnectedWCF Set the 8. the solution. Build and run 6. 6. the ClinicAd to proxy the Add 2. 2. solution. ConnectedWCF existing Open the a Add 3. Task 2: Open the existing ConnectedWCF solution the On 1. 4. 4. using Svcutil.exe. by a service proxy Generate 5. a configure and project FPAdminClient the to proxy the Add 1. Server Remote Virtual Open the endpoint for the Appointment service. for the Appointment endpoint exercise are as follows: for this The main tasks 1. Start the 6461-LON-DEV-03 virtual Task 1: Start the 6461-LON-DEV-03 virtual machine and log on as Student proxy class by using the Svcutil.exe t using the Svcutil.exe proxy class by to the ClinicAdminClient configuration Exercise 1: Exposing Services 1: Exposing Exercise yo In this exercise, to on Log 2.

3. In Visual Studio 2008,on the File 2. In the In 2.

f f L3-46 L3-46 Behaviors and Endpoints 3: Module MCT USE ONLY. STUDENT USE PROHIBITED

47 -

, .

New Service Service New Configuration . , and then click , and then Edit WCF Configuration Edit WCF WCF folder, and then double-click folder, and WCF WCF folder, and then double-click folder, WCF

sic® development system, go to the go to the system, sic® development AppointmentServiceContract AppointmentServiceContract Lab: Changing Service Endpoints and Behaviors L3 Endpoints ppointmentServiceImplementation New Service Endpoint Service New

iguration Editor window, in the iguration Editor window, in

file. file.

file, and then click file, and pane, define a service endpoint with the following with the following pane, define a service endpoint with the service endpoint define a second pane, , and then click , and then pane, right-click right-click pane, dialog box, go to either of the following: following: the of either to go box, dialog App.config InternetAppointmentService IntranetAppointmentService IntranetAppointmentService netTcpBinding wsHttpBinding APService_TCP APService_wsHTTP Endpoints . ConnectedWCF.sln ConnectedWCF.sln Service Endpoint Service Endpoint Open Project Open Configuration Address: Name: Name: the the go to tool, Visual C#® development Microsoft If you are using E:\Labfiles\Starter\CS\Ex1\Connected If you are using Microsoft® Visual Ba Microsoft® using If you are E:\Labfiles\Starter\VB\Ex1\Connected the Binding: Address: Contract: com.contoso.AppointmentService.AppointmentServiceContract Binding: Contract: com.contoso.AppointmentService.

• Endpoint information: • following information: • right-click right-click the right-click the • pane, expand com.contoso.AppointmentService.A • • • • • • 3. In the In 3. the In 5. 4. In the In 4. 2. 2. Service Conf Microsoft In the 1. 1. project, AppointmentServiceSelfHost in the Explorer window, In the Solution Task 3: Add a netTcpBinding and a wsHttpBiniding endpoint to the the to endpoint a wsHttpBiniding and netTcpBinding 3: Add a Task Appointment service the In 4.

f

MCT USE ONLY. STUDENT USE PROHIBITED

menu, click menu, , and then click , and then , and then click , and then File , and then click , and then click box, type type box, . box, type type address box, .

. OK AppointmentServiceSelfHost Continue Base address Base Base . . GenerateVbProxy.cmd GenerateVbProxy.cmd . GenerateCsProxy.cmd GenerateCsProxy.cmd New New Host and then click and then click OK and then iguration Editor window, on the iguration Editor window, . Configuration Editor window. Configuration Editor dialog box, in the dialog box, dialog box, in the in dialog box, proxy by using Svcutil.exe Build . . pane, click pane, st:8002/Contoso Base Address Editor Address Base section, click section, click BaseAddresses section, click BaseAddresses Editor Address Base Configuration User Account Control dialog click box, User Account . . . If you are using Visual C#, right-click If you are using Visual C#, right-click Edit http://localho net.tcp://localhost/Contoso click and then project, Edit Save If you are using Visual C#, right-click If you are using Visual C#, right-click Run as administrator Run as Run as administrator Run as successfully, and then press ENTER. successfully, and then press 1. 1. folder. E:\Labfiles\Starter\Proxy the to go Explorer, In Windows 2. Basic, right-click Visual If you are using Task 4: Generate a service 8. In the In 8. the In 6. the In 7. 9. In the In 9. the In 10. 11. 11. Conf Service Microsoft In the 12. 12. Service Microsoft Close the 13. In the Solution Explorer window, right-click the window, right-click Explorer 13. In the Solution 3. 3. Notepad. close then and command, Examine the 4. Basic, right-click Visual If you are using 6. 6. executed command that the ensure Prompt window, In the Command 5. In the In 5.

f L3-48 L3-48 Behaviors and Endpoints 3: Module MCT USE ONLY. STUDENT USE PROHIBITED

49

-

menu, click menu, project, and project, point File Configuration New Client Client New file. file. : FPAdminClient FPAdminClient app.config App.config

dialog box, go to the following file, following the to go box, dialog , and then click , and then Lab: Changing Service Endpoints and Behaviors L3 the FPAdminClient project, right-click the right-click project, FPAdminClient the to E:\Labfiles\Starter\Proxy\ go to E:\Labfiles\Starter\Proxy\

Item.

iguration Editor window, on the iguration Editor window, iguration Editor window, in the iguration Editor window, in

Edit WCF Configuration Edit WCF Configuration Editor window. host:8002/Contoso/InternetAppointmentService pane, define a new client endpoint with the following client endpoint with the following new pane, define a Existing , right-click Endpoints , right-click : . Add AppointmentServiceContract Client http://local wsHttpBinding APService_wsHTTP . , and then click then , and Add Existing Item - FPAdminClient Add Client Endpoint Client . Address: Name: Binding: Contract: If you are using Visual Basic, If you are using contoso.com.services.AppointmentService.cs. contoso.com.services.AppointmentService.vb. contoso.com.services.AppointmentService.vb. Visual C#, go If you are using If you are using Visual Basic, right-click the Basic, right-click the Visual If you are using If you are using Visual C#, right-click the If you are using Visual C#, right-click

• information: • • Endpoint • and then click • • • Save following file, and then click • pane, expand then click Build to Add 6. In the In 6. 3. In the In 3. 7. 7. Service Conf Microsoft In the 8. 8. Service Microsoft Close the 5. 5. Service Conf Microsoft In the 9. the right-click window, Explorer In the Solution 4. 4. in window, Explorer In the Solution Task 5: Add proxy tothe the FPAdminClient project and configure a wsHttpBinding binding 1. 2008. to Visual Studio Switch 2. the right-click window, Explorer In the Solution

f

MCT USE ONLY. STUDENT USE PROHIBITED

project, project, project, project, menu, click menu, File Configuration project, right-click project, New Client Client New file. : file. ClinicAdminClient ClinicAdminClient app.config dialog box, go to the following the to go box, dialog App.config

, and then click , and then . Item

the ClinicAdminClient the ClinicAdminClient to E:\Labfiles\Starter\Proxy\ go to E:\Labfiles\Starter\Proxy\ Edit WCF Configuration Edit WCF iguration Editor window, on the iguration Editor window, iguration Editor window, in the iguration Editor window, in

Existing Configuration Editor window.

pane, define a new client endpoint with the following client endpoint with the following new pane, define a : , right-click Endpoints , right-click . Add Build AppointmentServiceContract Client net.tcp://localhost/Contoso/IntranetAppointmentService netTcpBinding , and then click , APService_TCP . Add Add Existing Item - ClinicAdminClient Existing Item - Add Client Endpoint Client . Name: Address: If you are using Visual Basic, right-click the Basic, right-click the Visual If you are using If you are using Visual C#, right-click the If you are using Visual C#, right-click Binding: Contract: contoso.com.services.AppointmentService.cs. contoso.com.services.AppointmentService.cs. If you are using Visual Basic, If you are using contoso.com.services.AppointmentService.vb. Visual C#, go If you are using

information: • • Endpoint • • • Save and then click point to point to click file, and then and then click the following file, pane, expand • • • 5. In the In 5. 6. 6. Service Conf Microsoft In the 7. 7. Service Microsoft Close the 4. 4. Service Conf Microsoft In the 8. the right-click window, Explorer In the Solution 3. 3. in window, Explorer In the Solution Task 6: Add the proxy to the ClinicAdminClient projectand configure binding netTcpBinding a 1. the right-click window, Explorer In the Solution the In 2.

f L3-50 L3-50 Behaviors and Endpoints 3: Module MCT USE ONLY. STUDENT USE PROHIBITED

51 -

. tab, Find Multiple OK . solution, and None. tab, click tab, . FPAdminClient Appointment

Debugging

Appointment service service Appointment for the for , and , and dialog box, click box, dialog click box, dialog Stop Unblock ConnectedWCF Create t of available appointment t of available appointment t of available appointment t of available appointment Action Appointment .

. exposed the Appointment service over Lab: Changing Service Endpoints and Behaviors L3 Create Debugging list, set the the list, set Solution

for the remaining projects to projects remaining the for dialog box, click dialog box, ClinicAdminClient . , Start Build dow to display the message display the dow to Projects

endpoint. wsHttpBinding . . Set the Action the . Set box is populated with a lis populated Slots box is box is populated with a lis populated Slots box is . menu, click menu, and Startup

menu, click Start Slots

projects

Build Debug Solution 'ConnectedWCF' Property Pages 'ConnectedWCF' Solution Solution 'ConnectedWCF' Property Pages 'ConnectedWCF' Solution Multiple startup projects Windows Security Alert Windows After this exercise, you should have Find . startup AppointmentServiceSelfHost projects to then click Set then click running. Ensure that the the that Ensure times. times. Slots the that Ensure click netTcpBinding Results: a 3. In the In 3. 2. In the In 2. 4. In the In 4. Task 8: Build and run the solution the On 1. 2. On the the On 2. the In 3. Task 7: Set the ConnectedWCF solution startup projects projects startup solution ConnectedWCF the 7: Set Task 1. the right-click window, Explorer In the Solution

5, 5, the on Client form, Admin FP In the 4. win Wait for the Console 7. In Visual Studio 2008, menu, click onthe Debug 6, on the form, Client In the Clinic Administration

f f

MCT USE ONLY. STUDENT USE PROHIBITED

. New

Configuration endpoint to the to endpoint , and then click , , and then click and then , Open endpoints to the Appointment Appointment the to endpoints Edit WCF Configuration Edit WCF WCF folder, and then double-click folder, and then double-click WCF WCF folder, and then double-click folder, and then double-click WCF mexTcpBinding menu, point to . TCP and HTTP. You will then use the Add TCP and HTTP. You will then iguration Editor window, in the iguration Editor window, in file. file. the ClinicAdminClient project. file, and then click file, and the FPAdminClient project. the IMetadataExchange , right-click Service Behaviors endpoint and a dialog box, go to either of the following: the following: of either to go box, dialog . App.config Advanced ConnectedWCF.sln ConnectedWCF.sln Open Project Open mexHttpBinding If you are using Visual Basic, go to the to Visual Basic, go If you are using E:\Labfiles\Starter\VB\Ex2\Connected the the to C#, go Visual If you are using E:\Labfiles\Starter\CS\Ex2\Connected the

Appointment service. Appointment Service Behavior Configuration Service Behavior pane, expand right-click the right-click the Project/Solution • • service to expose metadata over both metadata expose to service the from object a proxy generate to 2008 Studio in Visual tool Reference Service metadata. exercise are as follows: for this The main tasks a Add 1. 4. to reference a service Add 5. projects. startup solution ConnectedWCF Set the 6. the solution. Build and run 2. 2. projects. startup solution ConnectedWCF Set the 3. to reference a service Add 4. 4. Service Conf Microsoft In the 3. 3. project, AppointmentServiceSelfHost in the window, Explorer In the Solution Task 1: Add a mexHttpBinding endpoint and a mexTcpBinding endpoint to the Appointment service 1. In Visual Studio 2008,onthe File ExerciseAdding 2: Metadata Exchange to a Service Scenario you will add In this exercise,

2. In the In 2.

f L3-52 L3-52 Behaviors and Endpoints 3: Module MCT USE ONLY. STUDENT USE PROHIBITED

53 - . , . menu, click menu, New Service Service New . File . Add property to True dialog box, click click box, dialog box, type box, type , and then click , and then section, click section, click Name , click Lab: Changing Service Endpoints and Behaviors L3 Endpoints ppointmentServiceImplementation New Service Endpoint Service New HttpGetEnabled . Add

pane, in the in the pane,

.

iguration Editor window, on the iguration Editor window, pane, define a service endpoint with the following with the following pane, define a service endpoint pane, define a service endpoint with the following with the following pane, define a service endpoint pane, set the the set pane, , and then click , and then pane, right-click right-click pane, pane, under Services pane, , click under AppointmentServiceBehavior pane, pane, expand pane, , and then click then , and . IMetadataExchange IMetadataExchange IMetadataExchange IMetadataExchange mexTcpBinding mexHttpBinding BehaviorConfiguration property to APService_mexTcp APService_mexHttp Endpoints . Service Endpoint Behavior: NewBehavior Behavior: serviceMetadata Behavior element extension position extension element Behavior Extension Sections Behavior Element Adding Service: Service Endpoint Configuration Configuration Configuration Configuration . Name: Binding: Contract: Name: Binding: Contract:

Endpoint information: • Save AppointmentServiceBehavior • pointmentServiceImplementation com.contoso.AppointmentService.Ap serviceMetadata serviceMetadata the pane, set AppointmentServiceBehavior com.contoso.AppointmentService.A • information: • • pointmentServiceImplementation com.contoso.AppointmentService.Ap right-click • 15. In the In 15. 16. 16. Conf Service Microsoft In the 14. In the In 14. the In 5. 10. In the In 10. 9. In the In 9. 6. In the In 6. the In 7. the In 8. the In 11. 13. In the In 13. 12. In the In 12.

MCT USE ONLY. STUDENT USE PROHIBITED

. . OK Single solution, and element. element. file. file. file. . . . class. class. app.config dialog box, click box, dialog dialog box, click box, dialog Unblock OK AppointmentServiceSelfHost ConnectedWCF App.config system.serviceModel console running. running. console AppointmentServiceSelfHost

: the FPAdminClient project, right-click the right-click project, FPAdminClient the the FPAdminClient project, double-click double-click project, FPAdminClient the dialog box, click dialog box, dialog box, click dialog box, . Delete e to the FPAdminClient project . list, click . Configuration Editor window. Editor window. Configuration Start Without Debugging Without Start Close Build Projects

project project . menu, click menu, Startup

startup

menu, click menu, project

Debug File Solution 'ConnectedWCF' Property Pages 'ConnectedWCF' Solution Single Solution 'ConnectedWCF' Property Pages 'ConnectedWCF' Solution Windows Security Alert Windows Microsoft Visual Studio Visual Microsoft If you are using Visual C#, double-click the If you are using If you are using Visual Basic, double-click the Basic, double-click the Visual If you are using If you are using Visual Basic, right-click the Basic, right-click the Visual If you are using contoso.com.services.AppointmentService.vb If you are using Visual C#, right-click the If you are using Visual C#, right-click contoso.com.services.AppointmentService.cs

Leave the AppointmentServiceSelfHost Leave the startup project, and then click then and project, then click Set • the following file: the following file: • following class, and then click following class, and then • • 4. In the In 4. the In 6. 5. On the the On 5. 3. In the In 3. 2. In the In 2. 5. On the the On 5. 4. 4. the remove window, Editor In the Code 2. In the In 2. Task 3: Add a service referenc 1. in window, Explorer In the Solution 3. in window, Explorer In the Solution Task 2: Set the ConnectedWCF solution startup projects projects startup solution ConnectedWCF the 2: Set Task 1. the right-click window, Explorer In the Solution 17. Service Microsoft the Close 18. the right-click window, Explorer Solution In the

f f L3-54 L3-54 Behaviors and Endpoints 3: Module MCT USE ONLY. STUDENT USE PROHIBITED

55 - ) and project, and constructor. constructor. "APService_wsHTTP" . class, add code to bring the bring the class, add code to Yes FPAdminClient namespace into scope. scope. into namespace . AppointmentServiceReference Code method, and then pass the string the then pass and method,

. Lab: Changing Service Endpoints and Behaviors L3 OK View the FPAdminClient project, right-click the right-click FPAdminClient project, the FPAdminForm . dialog box, click box, dialog AppointmentServiceContractClient box, type box, type Namespace Reference and then click click and then http://localhost:8002/Contoso Address box, type http://localhost:8002/Contoso . class, and then click class, and then Service

Go GetAppointmentServiceProxy dialog box, define a service reference with the the with reference define a service dialog box, Reference Service Add Microsoft Visual Studio Visual Microsoft then click Address: In the Namespace: In the the Namespace: In

FPAdminClient.AppointmentServiceReference AppointmentServiceContract Return New AppointmentServiceContractClient( End Function ... [Visual Basic] ... Private Function GetAppointmentServiceProxy() As_ ... [Visual C#] ... using FPAdminClient.AppointmentServiceReference; ... [Visual Basic] ... Imports FPAdminClient.AppointmentServiceReference APService_wsHTTP in the APService_wsHTTP FPAdminForm following information, then click Add then click • • 11. Locate the the Locate 11. 9. 9. in window, Explorer In the Solution the In 6. 7. the right-click window, Explorer In the Solution the In 8. 10. for the window Editor In the Code

MCT USE ONLY. STUDENT USE PROHIBITED

); project, project, project, project, and element. element. file. project, right-click project, file. file. "APService_wsHTTP" . . class. class. app.config OK Yes ClinicAdminClient FPAdminClient App.config : system.serviceModel . the ClinicAdminClient the ClinicAdminClient Delete lient project, double- lient project, ClinicAdminC in the to the ClinicAdminClientto the project dialog box, click dialog box, click dialog box, . Reference

Close Service

. Add menu, click menu, File Microsoft Visual Studio Visual Microsoft Studio Visual Microsoft If you are using Visual C#, double-click the Visual If you are using If you are using Visual Basic, double-click the Basic, double-click the Visual If you are using If you are using Visual Basic, right-click the Basic, right-click the Visual If you are using contoso.com.services.AppointmentService.vb If you are using Visual C#, right-click the If you are using Visual C#, right-click contoso.com.services.AppointmentService.cs

• click the following file: • ... [Visual C#] ... private AppointmentServiceContract GetAppointmentServiceProxy() { return new AppointmentServiceContractClient( } then click Build and then click • the following class, and then click class, and then click the following • 6. In the In 6. 4. 4. the remove window, Editor In the Code 2. In the In 2. 3. window, Explorer In the Solution the On 5. 7. the right-click window, Explorer In the Solution Task 4: Add a service reference 1. in window, Explorer In the Solution 12. In the Solution Explorer window, right-click the window, right-click Explorer 12. In the Solution

f L3-56 L3-56 Behaviors and Endpoints 3: Module MCT USE ONLY. STUDENT USE PROHIBITED

57 - ); ) and then project, project, constructor. constructor. project, right-click project, namespace into scope. scope. namespace into . class, add code to bring to add code class, "APService_TCP" "APService_TCP" Code

ClinicAdminClient AppointmentServiceReference View method, and then pass the string the then pass and method, . Lab: Changing Service Endpoints and Behaviors L3 OK the ClinicAdminClient the ClinicAdminClient ClinicAdminForm box, type box, type Namespace AppointmentServiceContractClient class, and then click class, and then and then click and then . net.tcp://localhost/Contoso Address box, type net.tcp://localhost/Contoso in the Build . GetAppointmentServiceProxy Go dialog box, define a service reference with the the with reference define a service dialog box, Reference Service Add click the Namespace: In Address: In the Address: ClinicAdminForm ClinicAdminClient.AppointmentServiceReference

• ... [Visual C#] ... private AppointmentServiceContract GetAppointmentServiceProxy() { return new AppointmentServiceContractClient( } [Visual Basic] ... Private Function GetAppointmentServiceProxy() As_ AppointmentServiceContract Return New AppointmentServiceContractClient( End Function ...... using ClinicAdminClient.AppointmentServiceReference; ... [Visual Basic] ... Imports ClinicAdminClient.AppointmentServiceReference ... [Visual C#] and then click APService_TCP APService_TCP the following information, following • the 12. 12. the right-click window, Explorer In the Solution 11. Locate the the Locate 11. 9. 9. in window, Explorer In the Solution the In 8. 10. 10. for the window Editor In the Code

MCT USE ONLY. STUDENT USE PROHIBITED

.

tab, Find Multiple OK . solution, and None. tab, click tab, . FPAdminClient Appointment

Debugging

Appointment service service Appointment for the for , and , and IMetadataExchange dialog box, click box, dialog click box, dialog Stop Unblock ConnectedWCF Create t of available appointment t of available appointment t of available appointment t of available appointment , and then used the Add Service , and then Action Appointment .

console, and close the console console close the and console,

. Create Debugging list, set the the list, set Solution

for the remaining projects to projects remaining the for dialog box, click dialog box, ClinicAdminClient . , wsHttpBinding Start Build dow to display the message display the dow to and Projects

. . Set the Action the . Set box is populated with a lis populated Slots box is box is populated with a lis populated Slots box is . menu, click menu, Startup

menu, click Start Slots netTcpBinding

projects

Build Debug Solution 'ConnectedWCF' Property Pages 'ConnectedWCF' Solution Solution 'ConnectedWCF' Property Pages 'ConnectedWCF' Solution Multiple startup projects Windows Security Alert Windows After this exercise, you should have exposed an Find . startup AppointmentServiceSelfHost projects to then click Set then click window. running. Ensure that the the that Ensure times. times. Slots the that Ensure click Results: endpoint for a proxy object. Studio to generate Reference function in Visual 3. In the In 3. 2. In the In 2. 4. In the In 4. 2. On the the On 2. 3. On the the On 3. the In 4. Task 6: Build and run the solution 1. AppointmentServiceSelfHost Switch to the Task 5: Set the ConnectedWCF solution startup projects projects startup solution ConnectedWCF the 5: Set Task 1. the right-click window, Explorer In the Solution 5. win Wait for the Console 6, 6, the on Client form, Admin FP In the 8. In Visual Studio 2008, menu, click onthe Debug 7, on the form, Client In the Clinic Administration

f f L3-58 L3-58 Behaviors and Endpoints 3: Module MCT USE ONLY. STUDENT USE PROHIBITED

59 -

. . . Administrative nfiguration to the . Internet Information Information Internet Application

Continue Add , and, then expand Sites Web vices\PatientInformationService . Lab: Changing Service Endpoints and Behaviors L3 (IIS) Manager window, in the left pane, in the left Manager window, (IIS) ry code and WCF co ry code and WCF System and Maintenance and System the PatientLetterService project. project. PatientLetterService the Clients and Services That That Services and Clients for the PatientLetterService project. project. PatientLetterService the for , and then click , and then . Control Panel tientLetterService project. project. tientLetterService . dialog box, add a new application with the following the following new application with a dialog box, add OK menu, click basicHttpBinding Default Web Site PatientInformationService LON-DEV (LON-DEV\Student) LON-DEV Start Add Application Add User Account Control dialog click box, User Account . Physical path: path: Physical E:\Labfiles\Starter\LegacyWebSer Alias:

• details, and then click • expand Tools Services (IIS) Manager Services (IIS) 8. In the In 8. 4. 4. window, double-click Tools In the Administrative 6. In the Internet Information Services 5. In the In 5. 7. Right-click 3. click Maintenance window, and Panel\System In the Control 9. 9. Manager window. (IIS) Services Information Internet Close the 2. Panel click window, In the Control existing Patient Letter WCF service to interoperate with a legacy Web service. a legacy Web with interoperate to service WCF Patient Letter existing exercise are as follows: for this The main tasks 1. (IIS). Services Information Internet Web service in Host a legacy 2. Pa for the Create a proxy 3. project. PatientLetterService the to proxy Add the a Configure 4. Task 1: Host a legacy Web service in IIS the On 1. Exercise 3: Creating WCF 3: Creating Exercise Scenario will add the necessa In this exercise, you Services Web with Non-WCF Interoperate 6. the solution. Build and run 5. 5. in the methods call to code Add

f

MCT USE ONLY. STUDENT USE PROHIBITED

. . : and then press and then . Description

: GenerateLegacyVbProxy.cmd Continue . . Service GenerateLegacyCsProxy.cmd Run as administrator Run as Edit . . GenerateLegacyVbProxy.cmd GenerateLegacyCsProxy.cmd splay the Web Services Description Services splay the Web Close Close Explorer

ce correctly, you will see the default correctly, you will see the default ce rmationService/Service.asmx page. Internet dialog box, click dialog box, dialog box, click dialog box, g file, and then click g file, and then click bar, type bar, type menu, click Start click page, PatientInformationService Address Address Information Bar Information User Account Control dialog click box, User Account Information Bar Information If you are using Visual Basic, right-click If you are using If you are using Visual Basic, right-click the Basic, right-click the Visual If you are using file. file. the If you are using Visual C#, right-click If you are using Visual C#, right-click If you are using Visual C#, right-click

• Language (WSDL) document for the Web service. Web for the document Language (WSDL) Windows® Internet Explorer® will now di Explorer® will Windows® Internet • • • successfully, and then press ENTER. successfully, and then press PatientInformationService ENTER. ENTER. servi the Web If you have hosted http://localhost/PatientInfo 14. In the In 14. 15. 15. Explorer. Close Internet 6. 6. executed command that the ensure Prompt window, the Command In 5. In the In 5. 3. 3. Notepad. close then and command, Examine the 4. Right-click the followin 1. 1. folder. E:\Labfiles\Starter\LegacyWebServices the to go Explorer, In Windows 2. Right-click the followin Task 2: Create a for the PatientLetterServiceproxy project 12. In the In 12. the On 13. the On 10. the In 11.

f L3-60 L3-60 Behaviors and Endpoints 3: Module MCT USE ONLY. STUDENT USE PROHIBITED

61 -

. project, project, project, project,

Client

Configuration New , and then click and then , Open PatientLetterService dialog box, go to the the to go box, dialog Edit WCF Configuration Edit WCF WCF folder, and then double-click folder, WCF WCF folder, and then double-click folder, WCF , and then click , and then . ces\LegacyPatientInformationService ces\LegacyPatientInformationService Lab: Changing Service Endpoints and Behaviors L3 Item

ng for the PatientLetterService menu, point to menu, point . iguration Editor window, in the iguration Editor window, in Add Existing file. file. file, and then click then click file, and , right-click Endpoints , right-click dialog box, go to either of the following: the following: of either to go box, dialog . App.config Client , and then click , . Add ConnectedWCF.sln ConnectedWCF.sln Add Existing Item - PatientLetterService Item Existing Add Open Project Open If you are using Visual Basic, go to Visual Basic, go If you are using E:\Labfiles\Starter\LegacyWebServi Proxy.vb. to C#, go Visual If you are using E:\Labfiles\Starter\LegacyWebServi Proxy.cs. the If you are using Visual Basic, go to the to Visual Basic, go If you are using E:\Labfiles\Starter\VB\Ex3\Connected the the to Visual C#, go If you are using E:\Labfiles\Starter\CS\Ex3\Connected

Endpoint • following file, and then click • right-click the right-click the pane, expand point to point to Project/Solution • • 2. 2. Service Conf Microsoft In the 4. In the In 4. project Task 4: Configure a basicHttpBindi 1. AppointmentServiceSelfHost in the window, Explorer In the Solution 3. 3. the right-click window, Explorer In the Solution Task 3: Add tothe proxy the PatientLetterService project 1. In Visual Studio 2008,on the File

2. In the In 2.

f f

MCT USE ONLY. STUDENT USE PROHIBITED

. menu, click menu, namespace into into namespace File project, right-click right-click project,

comment, and add code to

rmationService/Service.asmx rmationService/Service.asmx class, and then click View Code and then class, TODO 1 TODO

iguration Editor window, on the iguration Editor window, Configuration Editor window. Configuration Editor pane, define a client endpoint with the following with the following client endpoint a pane, define PatientInformationServiceSoap PatientInformationServiceSoap http://localhost/PatientInfo basicHttpBinding PatientInformationServiceSoap contoso.com.ClinicManagementSystem._2004._07 contoso.com.ClinicManagementSystem._2004._07 Client Endpoint Client . Name: Address: Binding: Contract: PatientLetterServiceImplementation PatientLetterServiceImplementation

scope. bring the information: information: • the //TODO 1 using contoso.com.ClinicManagementSystem._2004._07; ... 'TODO 1 Imports ... [Visual C#] ... [Visual Basic] ... • Save • • 2. 2. locate the window, Editor In the Code Task 5: Add code to call the methods in the PatientLetterService project 1. PatientLetterService in the window, Explorer In the Solution 4. 4. Service Conf Microsoft In the the In 3. 5. 5. Service Microsoft Close the

f L3-62 L3-62 Behaviors and Endpoints 3: Module MCT USE ONLY. STUDENT USE PROHIBITED

63 - class class , and then then , and details variable as a comment, and add and comment, class called patientId TODO 2 method in the GetPatientDetails Lab: Changing Service Endpoints and Behaviors L3 . Pass the string . Pass the to the constructor. constructor. to the PatientInformationServiceSoapClient PatientDetails PatientDetails object. Pass the Pass object. method, locate the locate the method, return value of the of the value return PopulateTemplate Create a new instance of the the of instance Create a new PatientInformationServiceSoap called patientInformationService Create a new instance of the the of Create a new instance initialize it to the patientInformationService parameter in the method call. parameter in the method

code to do the following: code to do • PatientDetails patientDetails = patientInformationService.GetPatientDetails(patientId); ... [Visual C#] ... //TODO 2 PatientInformationServiceSoapClient patientInformationService = new PatientInformationServiceSoapClient( "PatientInformationServiceSoap"); 'TODO 2 Dim patientInformationService As New _ PatientInformationServiceSoapClient( _ "PatientInformationServiceSoap") Dim patientDetails As PatientDetails_ = patientInformationService.GetPatientDetails(patientId) ... [Visual Basic] ... • the In 3.

MCT USE ONLY. STUDENT USE PROHIBITED tab,

. . Appointment

file. Appointment service service Appointment Create . Unblock Create OK . messages are displayed. displayed. messages are . ice to interoperate with a legacy .asmx NH991199Z.txt and then click provides details of the appointment. Debugging SendLetter Solution

dialog box, click dialog box, click box, dialog Start Build Exited dow to display the message dow to NH991199Z Created

and . menu, click menu, box, box, type menu, click Slots

SendLetter

Build Debug Patient Appointment Windows Security Alert Windows After this exercise, you should have added the necessary code and WCF code and the necessary After this exercise, you should have added Find and patient letter service running. Press to quit. to Press service running. letter and patient The file contains a basic letter that click Entered Web service. Results: WCF serv the Patient Letter configuration to 2. On the the On 2. the In 3. Task 6: Build and run the solution the On 1. the In 6. the In 7. 4. win for the Console Wait 5, on the Client form, the Clinic Administration In 8. 8. the that window, and verify console AppointmentServiceSelfHost Switch to the 9. 9. folder. E:\Labfiles\Starter\Letters the to go and Explorer, Open the double-click folder, In the Letters

f L3-64 L3-64 Behaviors and Endpoints 3: Module MCT USE ONLY. STUDENT USE PROHIBITED

65 - Lab: Message Logging and Activity Tracing Tracing and Activity Logging Message Lab: L4

iguration to the service to log messages iguration to the service e appointment service and your manager your and service appointment e

6461A-LON-DEV-04 Student

User Name: Virtual Machine: Virtual Machine: Password: Pa$$w0rd Password:

sent to and from the clients and to monitor the activities the clients and service clients and service the activities the monitor and to clients from the and sent to performs. • Estimated time: 40 minutes Logon Information: Logon Information: • Scenario have You team. product Management Clinic Contoso on the developer You are a of th development been involved in the additional conf add to you has now asked Module 4: Debugging and Diagnostics Diagnostics and 4: Debugging Module and Activity Logging Message Lab: Tracing

MCT USE ONLY. STUDENT USE PROHIBITED

. Studio

. 6461-LON- Run as Visual

Pa$$w0rd Student . , and then click , and then , the , the to log messages. You will messages. to log and the . Open Continue , and then click 2008, and then

using the password using the e Microsoft Service Trace Viewer tool. Viewer tool. Trace Service Microsoft e Studio solution. menu, point to point to menu,

ing Information for a Service for ing Information AppointmentService Student , point to Microsoft , point Programs Control Client and double-click Control ClinicAdminClient AppointmentService

File as virtual machine and log on as on and log virtual machine All . Visual

, and the ClinicAdminClient , on the WCFConnected . . menu, point to menu, point to you will configure the you will configure 6461-LON-DEV-04 6461-LON-DEV-04 Start User Account Control dialog click box, User Account Visual Studio 2008 Visual Studio Project/Solution 2008, right-click Microsoft administrator

PatientManagementService DEV-04. 3. In 3. 2. In the In 2. Task 2: Open the existing WCFConnected solution the On 1. Task 1: Start the 6461-LON-DEV-04 virtual machine and log on as Student 1. Server Remote Virtual Open the ExerciseGenerating 1: Logg In this exercise, to on Log 2. 4. the for logging Enable message 5. solution. the Build and run 6. logs. View the message PatientManagementService exercise are as follows: for this The main tasks the Start 1. 2. existing Open the then analyze these messages by using th messages then analyze these 3. the for logging Enable message

f f L4-66 Module 4: Debugging and Diagnostics MCT USE ONLY. STUDENT USE PROHIBITED

67 -

. OK menu, click menu, Message File pane, in the the pane, in Configuration file (for Visual C#), and file (for Visual C#), box, type . project, right-click project, the , and then click then , and file

. WCF folder, and then double-click folder, and WCF WCF folder, and then double-click folder, WCF , and then click , and then Log Lab: Message Logging and Activity Tracing Tracing and Activity Logging Message Lab: L4 sic® development system, go to the go to the system, sic® development True App.config to Sources Diagnostics . . . . . ServiceSelfHost True iguration Editor window, on the iguration Editor window, iguration Editor window, in the iguration Editor window, in file. file. to pane, do the following: dialog box, in the in the dialog box, . pane, expand pane, pane, expand pane, Information dialog box, go either of the following: of the either go box, dialog pane, do the following: the following: pane, do Logging

list, click Diagnostics file (for Visual Basic) or the or the file (for Visual Basic) Edit WCF Configuration WCF Edit Enable Log Auto Flush Log Auto Enable Enable MessageLogging ServiceModelMessageLoggingListener . ConnectedWCF.sln ConnectedWCF.sln LogEntireMessage LogMessagesAtServiceLevel level Trace Source: System.ServiceModel.MessageLogging Source: Trace Open Project Open Listener Settings Listener Configuration Message Configuration Diagnostics

. Set Set Click the the go to tool, Visual C#® development Microsoft If you are using E:\Labfiles\Starter\CS\Ex1\Connected If you are using Microsoft® Visual Ba Microsoft® using If you are E:\Labfiles\Starter\VB\Ex1\Connected the Click Click

Trace Save • • . System.ServiceModel.MessageLogging • Logging

app.config then click • pane, click • • • click then and E:\Labfiles\Starter\Logs\service_messages.svclog 9. 9. Service Conf Microsoft In the 7. In the In 7. 8. In the In 8. 6. In the In 6. 5. In the In 5. 1. 1. the within Explorer, In Solution Task 3: Enable message logging for the AppointmentService and the PatientManagementService the In 3. the In 4. 2. Service Conf Microsoft In the 4. In the In 4.

f

MCT USE ONLY. STUDENT USE PROHIBITED

. OK menu, click menu, . Message File pane, in the the pane, in Configuration Unblock project, right-click the right-click project, and then click and file (for Visual C#), and file (for Visual C#), box, type . , and then click then , and file

. , and then click , and then . Log . True App.config to Sources Diagnostics . . . . . Debugging ClinicAdminClient Solution

dialog box appears, click True ng for the ClinicAdminClient ClinicAdminClient ng for the iguration Editor window, on the iguration Editor window, iguration Editor window, in the the in iguration Editor window, Configuration Editor window. Editor window. Configuration Start to Build pane, do the following: dialog box, in the in the dialog box, . pane, expand pane, pane, expand pane, Information pane, do the following: pane, do Logging

menu, click menu, menu, click list, click Diagnostics file (for Visual Basic) or the or the file (for Visual Basic) Edit WCF Configuration WCF Edit Enable Log Auto Flush Enable Enable MessageLogging ServiceModelMessageLoggingListener . LogEntireMessage LogMessagesAtServiceLevel Build Debug level Trace Source: System.ServiceModel.MessageLogging Source: Trace Listener Settings Listener Configuration Message Diagnostics Configuration

Windows Security Alert Windows . Set Set Click Click Click

Trace Save • • . System.ServiceModel.MessageLogging • Logging

app.config then click pane, click • • E:\Labfiles\Starter\Logs\client_messages.svclog 9. 9. Service Conf Microsoft In the 10. 10. window. Editor Configuration Service Microsoft Close the 7. In the In 7. 8. In the In 8. 6. In the In 6. 1. On the the On 1. Task 5: Build and run the solution the On 2. the If 3. 3. In the In 3. Task 4: Enable message loggi 1. the within Explorer, In Solution 10. Service Microsoft the Close 2. Service Conf Microsoft In the 5. In the In 5. 4. In the In 4.

f f L4-68 Module 4: Debugging and Diagnostics MCT USE ONLY. STUDENT USE PROHIBITED

69 -

tab, Message . . method call. . Appointment

, select both the the , select both ClinicAdminClient endpoint. endpoint. Debugging files, and then click files, and then click

Service running Service Stop . menu, click Open , and the , and the available appointment times. available appointment entry. File Lab: Message Logging and Activity Tracing Tracing and Activity Logging Message Lab: L4 transport level message on the client the transport level message on Service Trace Viewer ve enabled message logging for the form, on the Create method call and includes the available the call and includes method . Microsoft Windows SDK Windows to Microsoft , point Programs ListAvailableAppointmentTimes

All E:\Labfiles\Starter\Logs 000000000000

service_messages.svclog All dow to display the message display the message dow to Close and , and then click then , and PatientManagementService column, click the first message, and then click the message, and column, click the first column, click the fifth message. column, click the fifth , :8002/Contoso/AppointmentService . Tools pane, click the menu, point to dialog box, go to to go box, dialog menu, click menu, box is populated with a list of a list Slots box is populated with Slots

File Start Activity Open Description Description Clinic Administration Client Administration Clinic , point to to , point After this exercise, you should ha Find On the On the tab. level, which service at the request message is a client message The first for the parameters contains the appointment times as appointment times value. the return level. transport the message at equivalent response is the message The sixth The fifth message is the service's response to the to the response is the service's The fifth message ListAvailableAppointmentTimes The second message is the equivalent equivalent is the message The second which is addressed to the http://localhost Open. Ensure the the Ensure

v6.0A client_messages.svclog click Results: AppointmentService application.

7 5. In the In 5. 6. In the In 6. 4. In the In 4. 2. 2. In Viewer, on the Service Trace the Microsoft Task 6: View the message logs the On 1. 4. win Console Wait for the the In 3. 6. Studio In Visual menu, click 2008,on the Debug 5, In the In 5,

f

MCT USE ONLY. STUDENT USE PROHIBITED

Configuration solution runs. , and then click , and then , the , the to log information on information to log file (for Visual C#), and Open project, right-click the right-click project, the ConnectedWCF WCF folder, and then double-click folder, and then double-click WCF WCF folder, and then double-click folder, and then double-click WCF and the . App.config . solution. menu, point to point to menu, AppointmentService -End Tracing for a Service a Service for Tracing -End ServiceSelfHost File iguration Editor window, in the iguration Editor window, in . file. file. , and the ClinicAdminClient . , on the AppointmentService ClinicAdminClient dialog box, go to either of the following: the following: of either to go box, dialog WCFConnected . you will configure the you will configure Diagnostics file (for Visual Basic) or the or the file (for Visual Basic) Edit WCF Configuration WCF Edit ConnectedWCF.sln ConnectedWCF.sln Open Project Open the If you are using Visual Basic, go to the to Visual Basic, go If you are using E:\Labfiles\Starter\VB\Ex2\Connected the the to C#, go Visual If you are using E:\Labfiles\Starter\CS\Ex2\Connected Visual Studio 2008 Visual Studio

app.config then click pane, click

Project/Solution PatientManagementService • • 2. 2. Service Conf Microsoft In the Task 2: Enable tracing for the AppointmentService and the PatientManagementService 1. the within Explorer, In Solution Task 1: Open the existing WCFConnected solution In 1. Exercise 2: Enabling End-to 2: Enabling Exercise In this exercise,

3. Enable the tracing for 4. solution. the Build and run 5. logs. View the trace PatientManagementService the various activities that they perform when the the when perform that they activities various the 2. In the In 2. ing the Microsoft Service Trace Viewer Trace the Microsoft Service by using logs analyze the trace You will then tool. exercise are as follows: for this The main tasks 1. existing Open the 2. Enable the tracing for

f f L4-70 Module 4: Debugging and Diagnostics MCT USE ONLY. STUDENT USE PROHIBITED

71 -

. . list, click list, click OK menu, click menu, OK level level

File Configuration Sources, and then Sources, and then Trace Trace project, right-click the the right-click project, and then click then and file (for Visual C#), and box, type box, type and then click and then , expand , expand , expand , expand file file

pane, in the in the pane, pane, in the in the pane, Log Log Lab: Message Logging and Activity Tracing Tracing and Activity Logging Message Lab: L4 App.config . . Diagnostics Diagnostics . . . CinicAdminClient iguration Editor window, in the iguration Editor window, in iguration Editor window, on the iguration Editor window, Configuration Editor window. . . . \service_tracelog.svclog . \client_tracelog.svclog dialog box, in the the in dialog box, in the dialog box, . pane, expand pane, pane, expand pane, pane, do the following: pane, do the following: pane, do . . Diagnostics file (for Visual Basic) or the or the file (for Visual Basic) Edit WCF Configuration WCF Edit Enable Log Auto Flush Enable Flush Log Auto Enable Enable Tracing ServiceModelTraceListener Enable Tracing ServiceModelTraceListener Trace Source: System.ServiceModel Source: Trace Listener Settings Listener Settings Listener Trace Source: System.ServiceModel Source: Trace Diagnostics Diagnostics Configuration Configuration System.ServiceModel System.ServiceModel . Click Click Click Click Click Click

• • Information

app.config then click pane, click • • E:\Labfiles\Starter\Logs • • E:\Labfiles\Starter\Logs Information click Save click Task 3: Enable tracing for the ClinicAdminClient 1. the within Explorer, In Solution 3. In the In 3. the In 3. 2. Service Conf Microsoft In the 5. In the In 5. 7. 7. Service Conf Microsoft In the 6. In the In 6. 8. 8. Service Microsoft Close the 4. In the In 4. the In 4. the In 5. 6. In the In 6.

f

MCT USE ONLY. STUDENT USE PROHIBITED

.

Open tab,

menu, , and the the , and . menu, click click menu, . Debug NH991199Z File Delete . Make a note of Make a note . Appointment

Unblock , select both the the , select both Service running. Service Create files, and then click click files, and then box, type . menu, click Open. . available appointment times. available appointment OK File OK . . Patient No cal list of activities associated with associated with cal list of activities and then click form, on the Create box, click box, , the PatientManagementService Debugging Solution

dialog box appears, click dialog box appears, E:\Labfiles\Starter\Logs tab, in the the tab, in iguration Editor window, on the Editor window, iguration click dialog box, Configuration Editor window. Editor window. Configuration service_tracelog.svclog Start . Build dow to display the message dow to NH991199Z and . Created oft Service Trace Viewer. Trace oft Service

, and the calling of the methods. . Get Details menu, click menu, box, box, type menu, click box, type your appointment ID, and then click then and ID, appointment type your box, AppointmentService dialog box, go to to go box, dialog box is populated with a list of Slots box is populated with a list Slots Debugging

Build Debug Cancel Appointment Cancel Open Appointment Cancellation Appointment Appointment Patient Clinic Administration Client Administration Clinic Windows Security Alert Windows Stop Find . Appt ID

click client_tracelog.svclog chronologi contains a pane The activity creating the Ensure the the Ensure Save ClinicAdminClient the appointment ID. the appointment and then click click 11. 11. on the system, development 2008 Studio® Visual In Microsoft 1. Micros Switch to the 2. In Viewer, on the Service Trace the Microsoft Task 5: View the trace logs Task 4: Build and run the solution the On 1. the On 2. the If 3. 7. Conf Service Microsoft In the the In 3. 8. 8. Service Microsoft Close the 10. In the In 10. 9. The 9. 7. In the In 7. 4. win for the Console Wait 6. In the In 6. 8. On the the On 8. 5, In the In 5,

f f L4-72 Module 4: Debugging and Diagnostics MCT USE ONLY. STUDENT USE PROHIBITED 73 -

method in the the method in ties associated with building Lab: Message Logging and Activity Tracing Tracing and Activity Logging Message Lab: L4 process of building an instance of the of the an instance of building process pointmentServiceImplementation' iceReference.AppointmentServiceCon e client to communicate with the with the communicate to e client method. tab. AppointmentServiceContract AppointmentServiceContract Construct ServiceHost ServiceHost Construct Contract types: ChannelFactory. Construct Execute Execute 000000000000 activity. . Graph instances, and instances, and PatientManagementService , the column contains activities associated with the activities associated with the contains column activity. column contains the activi . ListAvailableAppointmentTimes pane, click the pane, click the pane, click pane, click the Activity Activity Activity pane, examine some of the other activities. activities. other of the some Activity pane, examine Activity pane, click the activity. activity. ServiceSelfHost ClinicAdminClient AppointmentService AppointmentService AppointmentService

PatientManagementService 'com.contoso.AppointmentService.Ap activity. of the an instance building host service the represents This activity such activity, of the the details contains pane right The . AppointmentService thread ID. l, process name, and name, trace leve as the activity the similar represents activity next The 'ClinicAdminClient.AppointmentServ This activity represents the building of the channel stack for the for the channel stack of the building the This activity represents ClinicAdminClient tract' 'com.contoso.AppointmentService.AppointmentServiceContract.ListAvaila bleAppointmentTimes' the of invoking process the This activity represents ListAvailableAppointmentTimes The graph view enables you to view the correlation between the different different the between correlation view the to enables you view graph The activities. The b. for the client Opening the the endpoints. configured over the starting listening for requests The c. Calling the c. Calling d. d. for the client Opening the following processes: a. channel stack for th Building the 5. In the In 5. the In 4. 6. In the In 6. 7. In the In 7. the In 8. 9. pane, click the In the left

MCT USE ONLY. STUDENT USE PROHIBITED

ClinicAdminClient AppointmentService AppointmentService PatientManagementService , and the , and the e client to communicate with the with the communicate to e client method in the method method in the method method in the the in method .

PatientManagementServiceContract AppointmentServiceContract All

Close PatientManagementService , GetPatientDetails CancelAppointment CreateAppointment menu, click menu, File After this exercise, you should have enabled tracing for the should have enabled tracing for the After this exercise, you PatientManagementService g. for the client Opening the h. Calling the h. Calling i. the Opening the client for the j. Calling f. for th channel stack Building the

e. Calling the the e. Calling Results: AppointmentService application. 10. On the the On 10.

L4-74 Module 4: Debugging and Diagnostics MCT USE ONLY. STUDENT USE PROHIBITED

75 - Lab: Contracts Services for and Data L5

6461A-LON-DEV-05 Student

Virtual Machine: Virtual Machine: User Name: Password: Pa$$w0rd Password:

Estimated time: 60 minutes Logon Information: Logon Information: • Module 5: Designing and Defining Contracts Contracts and Defining 5: Designing Module and for Services Contracts Lab: Data • •

MCT USE ONLY. STUDENT USE PROHIBITED

. . 6461-LON- Pa$$w0rd Student This will improve the This will improve the using the password using the rsion of the Contoso Clinic Management rsion of the Contoso ke the letter sending operation one-way one-way operation ke the letter sending Student read of execution. Control Client and double-click Control as virtual machine and log on as on and log virtual machine d implementing a one-way a d implementing 6461-LON-DEV-05 6461-LON-DEV-05

DEV-05. Task 1: Start the 6461-LON-DEV-06 virtual machine and log on as Student 1. Server Remote Virtual Open the operation contract operation create an like to would user the than it takes longer that System has highlighted that a has identified process creation appointment the analysis of An appointment. the generate to system for the waiting time is spent of the significant percentage system of desired level the reach to up be speeded to needs This patient letter. performance. will add code to ma In this exercise, you th the client from and so decouple it Exercise 1: Defining an 1: Defining Exercise Scenario for a preliminary ve Initial user feedback to on Log 2.

2. 2. service. patient letter the clinic admin client to Add a call from the 3. service. patient letter to the output diagnostic Add a delay and 4. notification. and creation Verify the letter 5. one-way. be to contract letter patient Change the 6. client and service. of decoupling Verify the perceived response time of the system. time response perceived exercise are as follows: for this The main tasks the Start 1.

f L5-76 Module 5: Designing and Defining Contracts MCT USE ONLY. STUDENT USE PROHIBITED

77 -

Open

Open Open Studio .

Run as proxy with the Visual

. method and add method and the and then double-click project, right-click the right-click project, . Project/Solution

Continue Lab: Contracts Services for and Data L5 , and then click 2008, and then

View Code Basic® development system in the system in the Basic® development . MakeAppointment Studio admin client to patient the letter

ClinicAdminClient

, click Microsoft Programs

All Visual Open, and then click

PatientLetterServiceContractClient . . PLService_TCP comment in the in the comment file, and then click

menu, point to menu, dialog box, go to the folder folder the to go box, dialog folder the to go box, dialog menu, point to TODO 1 TODO File Start User Account Control dialog click box, User Account If you are using Microsoft® Visual Microsoft® If you are using Project \OneWay\ConnectedWCF E:\Labfiles\Starter\VB ConnectedWCF.sln in the tool, Visual C#® development Microsoft If you are using Project and then double-click E:\Labfiles\Starter\CS\OneWay\ConnectedWCF ConnectedWCF.sln

following code to create a name client endpoint • • 2008, right-click Microsoft administrator letterProxy.SendLetter(LetterType.ConsultationBooked, patientId, _ doctorId, slot) slot); [Visual Basic] ' TODO 1 Dim letterProxyAs PatientLetterServiceContract _ = New PatientLetterServiceContractClient("PLService_TCP") [Visual C#] // TODO 1 PatientLetterServiceContract letterProxy = new PatientLetterServiceContractClient("PLService_TCP"); letterProxy.SendLetter(LetterType.ConsultationBooked, patientId, doctorId,

ClinicAdminForm 3. On the the On 3. 2. In the In 2. 5. Locate the the Locate 5. 4. 4. the expand Explorer, In Solution Task 2: Add Task 2: Add the clinic a call from the On 1. service

f

MCT USE ONLY. STUDENT USE PROHIBITED

. View Code project, right-click the right-click project, method and replace the three the three and replace method SendLetter PatientLetterService comment in the in the comment block with the following statements. with the following statements. block try TODO 2 TODO lines of code in the the lines of code in Console.WriteLine("{0}: Exited 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) DateTime.Now.ToLongTimeString()); [Visual Basic] ' TODO 2 Console.WriteLine("{0}: Entered SendLetter", _ DateTime.Now.ToLongTimeString()) doctorId, date); SendTheLetter(letterToSend, patientId); Thread.Sleep(5000); Console.WriteLine("{0}: Exited SendLetter", [Visual C#] // TODO 2 Console.WriteLine("{0}: EnteredSendLetter", DateTime.Now.ToLongTimeString()); string templateGetLetterTemplate(type); = string letterToSend= PopulateTemplate(template, patientId,

file, and then click file, and then PatientLetterServiceImplementation 2. Locate the the Locate 2. Task 3: Add a delay and diagnostic output to the patient letter service 1. the expand Explorer, In Solution

f L5-78 Module 5: Designing and Defining Contracts MCT USE ONLY. STUDENT USE PROHIBITED

79 - tab. , and then , and , right-click , right-click the . ic Administration . project, right-click the right-click project, method appear before appear before method Create Appointment View Code window. Unblock : Lab: Contracts Services for and Data L5 window, make a note of the make a note window, E:\Labfiles\letters to open the file in Notepad. file in Notepad. the open to SendLetter Create . e window and the Clin e window and the form, click the form, Open OK PatientLetterService , point to Accessories , point Programs

dialog box, click dialog box, file, and then click file, and (this selects the first slot shown) the first slot shown) (this selects All . Start Debugging . Stop Debugging

u can see both windows. can see both u . ta, and then click click then ta, and Find Slots menu, click menu, menu, click menu, Gastro_Jones Today's date NH991199Z menu, point to menu, point to Debug Debug Start Clinic Administration Client Administration Clinic Windows Security Alert Security Windows Clinic Admin: Created Admin: Appointment Clinic Windows Explorer Doctor: Doctor: Date: Slot: Click Patient: Patient: , and then click and then NH991199Z.txt,

Enter the following da PatientLetterServiceContract • • • Client window so that yo Client window so that • you see Created the Appointment Clinic Admin: appointment time, and then click and then time, appointment click file Task 5: Change the patient letter contract to be one-way 1. system. development 2008 Visual Studio® Microsoft Switch to 2. the expand Explorer, In Solution Task 4: Verify the letter creation and notification the On 1.

4. In the In 4. 2. In the In 2. 3. 3. consol services Contoso the Position 5. 5. the from messages of the Verify that both 7. On the the On 7. 6. In the In 6. 8. On the the On 8. 9. 9. folder to the move Explorer, In Windows 10. 10. selected. one you is the letter time in the appointment Verify that the Notepad. Close 11.

f f

MCT USE ONLY. STUDENT USE PROHIBITED

, and then attribute of attribute , and then click . project, expand the expand project, . solution, and then click console window and press and press window console Unblock Allow OperationContract ConnectedWCF\ContosoServicesSelf ConnectedWCF\ContosoServicesSelf as a one-way operation. operation. as a one-way PatientLetterServiceReference ConnectedWCF ClinicAdminClient d then go to the following folder: following the d then go to . . . dialog box, click dialog box, . comment and change the change and comment folder, right-click ContosoServicesSelfHostExtConfig.exe . identify operation to it ContosoServicesSelfHostExtConfig TODO 3 TODO User Account Control dialog click box, User Account Security Alert Service Reference Update If you are using Visual Basic, go to the folder the folder to Basic, go Visual If you are using E:\Labfiles\Starter\VB\OneWay\ HostExtConfig\bin\Debug HostExtConfig\bin\Debug If you are using Visual C#, go to the folder the folder to Visual C#, go If you are using E:\Labfiles\Starter\CS\OneWay\ SendLetter

the _ ByValdoctorId As String, ByVal [date] As DateTime) DateTime date); [Visual Basic] ' TODO 3 _ Sub SendLetter(ByVal type AsLetterType, ByVal patientId As String, [Visual C#] // TODO 3 [OperationContract(IsOneWay=true)] void SendLetter(LetterType type, string patientId, string doctorId, • Rebuild Solution Rebuild Run as administrator Run as • click host. service to close the ENTER Service References 5. 5. an Explorer, Windows Switch to 4. 4. the right-click Explorer, In Solution the Locate 3. 6. Right-click the file the In 8. 11. Switch to the 7. In the In 7. 9. 2008. Switch to Visual Studio 10. the expand Explorer, In Solution L5-80 Module 5: Designing and Defining Contracts MCT USE ONLY. STUDENT USE PROHIBITED

81 - tab. ic Administration method.This window appears before Create Appointment : Lab: Contracts Services for and Data L5

window, make a note of the a note window, make SendLetter Create , right-click the file E:\Labfiles\letters to open the file in Notepad. file in open the to . e window and the Clin e window and the form, click the form, OK Open . (this selects the first slot shown) the first slot shown) (this selects ion into a one-way operation. . Stop Debugging . Start Debugging

u can see both windows. can see both u ta, and then click click then ta, and Find Slots Clinic Admin Appointment Created Admin Clinic menu, click menu, menu, click menu, Gastro_Jones Today's date NH991199Z Windows Explorer Windows Debug Debug Clinic Administration Client Administration Clinic Clinic Admin Clinic Appointment Created After completing this exercise, you have seen how to After completing this exercise, you have turn a Doctor: Doctor: Date: Slot: Click Patient: Patient:

Enter the following da • • • Client window so that yo Client window so that appointment time, and then click and then time, appointment you see the both of the messages from the from the the messages both of the you see •

, and then click and then NH991199Z.txt, demonstrates that the execution of the operation in the service is now now service is in the operation the of execution that the demonstrates client. decoupled from the Results: request/responseservice operat 4. In the In 4. 7. On the the On 7. 3. 3. consol services Contoso the Position Task 6: Verify the decoupling of client the decoupling Task 6: Verify and service 1. 2008. Visual Studio Switch to the On 2.

10. 10. selected. one you is the letter time in the appointment Verify that the Notepad. Close 11. 8. Switch to 8. Switch 6. In the In 6. 5. 5. Verify that the 9. 9. the folder to go Explorer, In Windows

f

MCT USE ONLY. STUDENT USE PROHIBITED

, and then , and , and then , and . project, right-click the right-click project, dialog box, go to the the to go box, dialog dialog box, go to the the to go dialog box, . Project/Solution n, you need to list today's today's to list n, you need . class. class. Open Project t the patient, doctor, and time. To do To time. doctor, and patient, the t Open Project . . Appointments 2008. data with a data contract data with

AppointmentService View Code Studio Open, and then click

Appointment class as a return value in the appointment service appointment service in the value as a return class nistration Client applicatio nistration Visual

ent service to list ent service ConnectedWCF.sln ConnectedWCF.sln file, and then click click file, and then menu, point to E:\Labfiles\Starter\CS\ComplexData\ConnectedWCF E:\Labfiles\Starter\VB\ComplexData\ConnectedWCF Microsoft Appointment File double-click double-click double-click double-click If you are using Visual Basic, in the Visual Basic, in the If you are using If you are using Visual C#, in the Visual C#, in the If you are using folder folder

contract. contract. • Appointment • 1. Switch to 1. Switch Task 1: Add a data contract to the Appointment class 3. Call the appointm Exercise 2: Passing complex 2: Passing complex Exercise Scenario Clinic Admi the As part of

4. 4. listing. appointment verify the to client Run the appointments including information abou including information appointments the To keep appointments. today's data for of a set retrieve to need this, you decided have you technology, underlying from its decoupled appointment service Service Web maps to the that types of complex as a collection data to pass this definition. (WDSL) service Language Description class that Framework will define a data contract for a .NET In this exercise, you back of these classes You will then pass a collection appointment. represents an client. to the appointment service from the exercise are as follows: for this The main tasks 1. the to a data contract Add the Use 2. the On 2. 3. 3. the expand Explorer, In Solution

f L5-82 Module 5: Designing and Defining Contracts MCT USE ONLY. STUDENT USE PROHIBITED

83 -

DataContract Lab: Contracts Services for and Data L5 class. comment, and then add the following the following add and then comment, Appointment TODO 4 TODO _ Public ClassAppointment "http://contoso.com/ClinicManagementSystem/2007/10")] public classAppointment [Visual Basic] 'TODO 4 [Visual C#] // TODO 4 [DataContract(Namespace =

attribute to the the Locate 4.

MCT USE ONLY. STUDENT USE PROHIBITED

, and Time PatientId , DoctorId , Id class, as shown in the following code. the following in class, as shown attribute to the the to attribute Appointment DataMember set { doctorId = value; } } [DataMember] public stringDoctorId { get { return doctorId; } { return patientId; } set { patientId = value; } } } } [DataMember] public stringPatientId { get { get { return id; } set { id = value; [Visual C#] [DataMember] public stringId

properties of properties the a Add 5. L5-84 Module 5: Designing and Defining Contracts MCT USE ONLY. STUDENT USE PROHIBITED

85 - Lab: Contracts Services for and Data L5 End Set End Property _ Public Property DoctorId()StringAs Get Return m_doctorId End Get Set(ByVal value As String) m_doctorId = value Get Return m_patientId End Get Set(ByVal value As String) m_patientId = value End Set End Property End Get Set(ByVal value As String) m_id = value End Set End Property _ Public Property PatientId() As String [Visual Basic] _ Public PropertyAs Id()String Get Return m_id { return time; } set { time = value; } } (Code continued) (Code continued) [DataMember] public DateTimeTime { get

MCT USE ONLY. STUDENT USE PROHIBITED

file, . project, right-click the right-click project, View Code AppointmentServiceImplementation AppointmentService interface. interface. file, and then click then click file, and . comment, and then add the following operation to the the to operation the following add and then comment, View Code TODO 5 TODO AppointmentServiceContract [Visual Basic] 'TODO 5 _ Function ListTodaysAppointments() As List(Of Appointment) [Visual C#] // TODO 5 [OperationContract] List ListTodaysAppointments(); Set(ByVal value As DateTime) m_time = value End Set End Property _ Public Property Time()DateTimeAs Get Return m_time End Get

AppointmentServiceContract and then click (Code continued) (Code continued) 3. 3. the right-click Explorer, In Solution 2. Locate the the Locate 2. Task 2: Use the Appointment class as a return value in the appointment contract service 1. the expand Explorer, In Solution

f L5-86 Module 5: Designing and Defining Contracts MCT USE ONLY. STUDENT USE PROHIBITED

87 - , and then click . . solution, and then click Unblock Allow Lab: Contracts Services for and Data L5 ta\ConnectedWCF\ContosoServic ta\ConnectedWCF\ContosoService . class. and then add the following the following add then class. and . ConnectedWCF d then go to the following folder: following the d then go to dialog box, click dialog box, service to list Appointments . . comment at the end of the end at the comment ContosoServicesSelfHostExtConfig.exe . TODO 6 TODO Visual Studio 2008 Visual Studio User Account Control dialog click box, User Account Security Alert Windows If you are using Visual Basic, go to the folder the folder to Basic, go Visual If you are using E:\Labfiles\Starter\VB\ComplexDa esSelfHostExtConfig\bin\Debug If you are using Visual C#, go to the folder the folder to Visual C#, go If you are using E:\Labfiles\Starter\CS\ComplexDa sSelfHostExtConfig\bin\Debug

method. AppointmentServiceImplementation Public Function ListTodaysAppointments()List(OfAs Appointment) Implements AppointmentServiceContract.ListTodaysAppointments Dim helper As New AppointmentHelperClass() Return helper.ListTodaysAppointments() End Function public ListListTodaysAppointments() { return new AppointmentHelper().ListTodaysAppointments(); } [Visual Basic] 'TODO 6 [Visual C#] // TODO 6 • Rebuild Solution Rebuild Run as administrator Run as • 5. 5. the right-click Explorer, In Solution Task 3: Call the appointment 1. an Explorer, Windows Switch to the Locate 4. 4. In the In 4. 3. In the In 3. 2. Right-click the file 5. Switch to 5. Switch

f

MCT USE ONLY. STUDENT USE PROHIBITED

tab. method, . file, and then click file, project, expand the expand project, Create Appointment console window and press and press window console Unblock : , andAppointmentServiceReference . RefreshAppointmentList_Click form, click the form, ClinicAdminForm Create ClinicAdminClient dialog box, click dialog box, (this selects the first slot shown) first slot shown) the (this selects . Start Debugging

folder, right-click folder, right-click comment in the in the comment Find Slots menu, click menu, ContosoServicesSelfHostExtConfig Gastro_Jones Today's date NH991199Z . TODO 7 TODO Debug Windows Security Alert Windows Clinic Administration Client Administration Clinic Doctor: Doctor: Date: Slot: Click Patient: Patient:

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

Service References Service References Update Service Reference Service Update then click ENTER to close the service host. host. service to close the ENTER View Code • Enter the following data and click • • • Task 4: Run the client to the appointment verify listing the On 1. 6. the expand Explorer, In Solution 7. 7. to the Switch 8. 2008. to Visual Studio Switch 9. the right-click Explorer, In Solution the Locate 10. 2. In the In 2. 3. In the In 3.

f L5-88 Module 5: Designing and Defining Contracts MCT USE ONLY. STUDENT USE PROHIBITED

89 - . . OK Refresh Lab: Contracts Services for and Data L5 window, click click window, have defined a data contract and used and contract have defined a data a Windows Communication Foundation Foundation a Windows Communication tab, and then click then tab, and . Stop Debugging menu, click menu, Today's Appointments Debug Clinic Admin Created Appointment Clinic After completing this exercise, you After completing this

patient ID, and time. If you created appointments in the previous exercise, you you exercise, previous the in appointments created time. If you patient ID, and appointments. should see multiple (WCF) service and a client. Results: between data complex type to pass this 5. Click the 5. Click 6. ID, doctor an ID, with listed appointment one see at least Verify that you the On 7. the In 4.

MCT USE ONLY. STUDENT USE PROHIBITED

. , and then then , and , and then , and then k message when the k message when the will then add code to will then dialog box, go to the the to go box, dialog dialog box, go to the the to go dialog box, Project/Solution Open Project the clinic admin client application to clinic admin client application the clinic admin client and register with the client and admin clinic Open Project the clinic management service that it is the clinic management . . gement service. You gement service. You em that the consultant is ready for the clinic admin client and the consultant clinic admin client 2008.

stered clinic management clients. ion will receive a callbac ion plementing a callback contract a callback plementing Studio Open, and then click

for callbacks with the service. for Visual

ConnectedWCF.sln ConnectedWCF.sln menu, point to E:\Labfiles\Starter\VB\Callback\ConnectedWCF E:\Labfiles\Starter\CS\Callback\ConnectedWCF Microsoft File If you are using Visual Basic, in the Visual Basic, in the If you are using double-click double-click folder If you are using Visual C#, in the Visual C#, in the If you are using folder double-click double-click

service. • • the consultant client application to notify the consultant client next patient. will add code to enable In this exercise, you mana with the clinic callbacks register for to service clinic management the code add patient and next the ready for propagate any notifications to any regi to 1. Switch 4. 4. in the contract callback Implement the Task 1: Define a callback contract consultant client application tells the syst tells the consultant client application exercise are as follows: for this The main tasks 1. Define a callback contract. 2. contract. a service to callback contract Add the 3. to register Enable clients 5. 5. method. triggering Implement the 6. client. consultant from the method Call the triggering 7. admin client. to the clinic Verify that callbacks are delivered client. The clinic admin client applicat client. The clinic admin Exercise 3: Defining and im 3: Defining Exercise Scenario the that System is Management Clinic Contoso the of requirements the of One their next see ready to is a consultant when are informed clinic administrators contract a callback to implement decided have you this, patient. To achieve the applications, between the two client

2. On the the On 2.

f L5-90 Module 5: Designing and Defining Contracts MCT USE ONLY. STUDENT USE PROHIBITED

91 - project, right- project, file, and then click and then click file, Lab: Contracts Services for and Data L5 ClinicManagementService comment and add the following service contract. contract. following service the add and comment . TODO 8 TODO ClinicManagementServiceCallbackContract

Public InterfaceClinicManagementServiceCallbackContract _ Sub NextPatientDueInToSeeConsultant(ByVal doctorId As String) End Interface void NextPatientDueInToSeeConsultant(string doctorId); } [Visual Basic] ' TODO 8 _ // TODO 8 [ServiceContract(Namespace = "http://contoso.com/ClinicManagementSystem/2007/10")] public interfaceClinicManagementServiceCallbackContract { [OperationContract(IsOneWay=true)] [Visual C#]

click the View Code 3. the expand Explorer, In Solution 4. Locate the the Locate 4.

MCT USE ONLY. STUDENT USE PROHIBITED

. View Code file, and then click file, and then comment and define a service contract as follows. as contract a service define and comment TODO 9 TODO

_ Sub RegisterForEvents() End Interface [Visual Basic] 'TODO 9 _ Public InterfaceClinicManagementServiceEventsContract allbackContract))] public interfaceClinicManagementServiceEventsContract { [OperationContract(IsOneWay = true)] void RegisterForEvents(); } [Visual C#] // TODO 9 [ServiceContract(Namespace = "http://contoso.com/ClinicManagementSystem/2007/10", CallbackContract = typeof(com.contoso.ClinicManagementService.ClinicManagementServiceC

ClinicManagementServiceEventsContract Task 2: Add the callback contract to a service contract 1. the right-click Explorer, In Solution the Locate 2.

f L5-92 Module 5: Designing and Defining Contracts MCT USE ONLY. STUDENT USE PROHIBITED

93 - . View Code Lab: Contracts Services for and Data L5 file, and then click file, and then er for callbacks with the service comment, and then add the following code. following the add and then comment, TODO 10 TODO End Sub Private eventClients As List( _ Of ClinicManagementServiceCallbackContract) = Nothing PublicNew() Sub eventClients = New List( _ Of ClinicManagementServiceCallbackContract)() eventClients = new List(); } [Visual Basic] 'TODO 10 [Visual C#] // TODO 10 private List eventClients = null; public ClinicManagementServiceImplementation() {

ClinicManagementServiceImplementation 2. Locate the the Locate 2. Task 3: Enable clients toTask 3: Enable regist 1. the right-click Explorer, In Solution

f

MCT USE ONLY. STUDENT USE PROHIBITED

, method and make the and method method. Implement Interface class, as follows. class, as follows. , point to to , point TER after you type the interface name to name the interface after you type TER RegisterForEvents . RegisterForEvents ClinicManagementServiceEventsContract comment and change the definition of the definition of the the and change comment Implement Interface Implement TODO 11 TODO Add the following code to the Delete the following statements: ClinicManagementServiceCallbackContract client =

eventClients.Add(client); } #endregion #region AppointmentServiceClinicEventsContract Members public void RegisterForEvents() { OperationContext.Current.GetCallbackChannel(); [Visual C#] throw new NotImplementedException(); • > _ Public ClassClinicManagementServiceImplementation Implements ClinicManagementServiceContract Implements ClinicManagementServiceEventsContract ClinicManagementServiceContract, [Visual Basic] 'TODO 11

95 - . . , and then click . admin client and Go project, right-click the right-click project, solution, and then click click then and solution, . Unblock text box, enter enter box, text Address Allow Lab: Contracts Services for and Data L5 Add Service Reference Add Service , and then click , ct in the clinic ConnectedWCF\ContosoServicesSelf ConnectedWCF\ContosoServicesSelf Connected WCF Connected ClinicAdminClient d then go to the following folder: following the d then go to . . dialog box, click dialog box, , andClinicManagementServiceReference the . folder, and then click and then folder, t:9003/Contoso/mex ContosoServicesSelfHostExtConfig.exe box, enter box, enter . . dialog box, in the dialog box, Reference Service Add User Account Control dialog click box, User Account Security Alert Windows Namespace OK If you are using Visual Basic, go to the folder the folder to Basic, go Visual If you are using E:\Labfiles\Starter\VB\Callback\ HostExtConfig\bin\Debug If you are using Visual C#, go to the folder the folder to Visual C#, go If you are using E:\Labfiles\Starter\CS\Callback\ HostExtConfig\bin\Debug

Rebuild Solution Rebuild _ Of ClinicManagementServiceCallbackContract)() eventClients.Add(client) End Sub [Visual Basic] PublicRegisterForEvents() Sub _ Implements ClinicManagementServiceEventsContract.RegisterForEvents Dim client As ClinicManagementServiceCallbackContract _ = OperationContext.Current.GetCallbackChannel( • Run as administrator Run as • net.tcp://localhos Service References click register with the service 1. 1. an Explorer, Windows Switch to 6. 6. the right-click Explorer, In Solution Task 4: Implement the callback contra

4. In the In 4. 3. In the In 3. 2. Right-click the file 5. 2008. Switch to Visual Studio 6. the expand Explorer, In Solution the In 7. 8. In the In 8.

f

MCT USE ONLY. STUDENT USE PROHIBITED

Implement Implement namespace, and namespace, file, and then click file, , point to point , console window and press and press window console , . class, and make the following class, and ClinicAdminClient TER after you type the interface name to name the interface after you type TER NextPatientDueInToSeeConsultant ClinicAdminForm ClinicAdminForm comment and change the definition of the definition of the the change and comment comment above the above the comment class, as follows. ContosoServicesSelfHostExtConfig . TODO 13 TODO TODO 12 TODO Implement Interface click Implement then , and changes to the generated code: Interface of the end method at the [Visual Basic] 'TODO 13 Partial Public Class ClinicAdminForm Inherits Form Implements ClinicManagementServiceEventsContractCallback [Visual C#] // TODO 13 public partial class ClinicAdminForm : Form ClinicManagementServiceEventsContractCallback [Visual Basic] 'TODO 12 Imports ClinicAdminClient.ClinicManagementServiceReference [Visual C#] // TODO 12 using ClinicAdminClient.ClinicManagementServiceReference; generate the method stubs. If you are using Visual C#, right-click right-click using Visual C#, you are If method stubs. the generate ClinicManagementServiceEventsContractCallback ClinicAdminForm ENTER to close the service host. service to close the ENTER View Code add the following statement. statement. following add the 15. 15. Visual C#, locate the If you are using 14. EN Visual Basic, press If you are using 13. Locate the the Locate 13. 9. Switch to the 10. 2008. to Visual Studio Switch 11. the right-click Explorer, In Solution the Locate 12. L5-96 Module 5: Designing and Defining Contracts MCT USE ONLY. STUDENT USE PROHIBITED

97 - Lab: Contracts Services for and Data L5

Add the following code to the method. Add the following Delete the following statements. following statements. Delete the

MessageBoxButtons.OK) MessageBoxButtons.OK); [Visual Basic] Dim messageString As = [String].Format(_ "Please send in the next patientfor {0}", doctorId) MessageBox.Show(message, "Clinic Admin: Next Patient", _ • [Visual C#] string message = String.Format("Please send in the next patient for {0}", doctorId); MessageBox.Show(message, "Clinic Admin: Next Patient", [Visual C#] throw new NotImplementedException();

MCT USE ONLY. STUDENT USE PROHIBITED

constructor, and ClinicAdminForm comment in the in the comment TODO 14 TODO

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

then add the following code. code. the following then add the Locate 16. L5-98 Module 5: Designing and Defining Contracts MCT USE ONLY. STUDENT USE PROHIBITED

99 - . View Code project, right-click the right-click project, Lab: Contracts Services for and Data L5 file, and then click method, and then SendInNextPatient ClinicManagementService comment in the in the comment TODO 15 TODO add the following code. following add the ClinicManagementServiceImplementation Thread.Sleep(2000) End Try retryCount += 1 End While Dim registered As Boolean = False Dim retryCount As Integer = 0 While Not registered AndAlsoretryCount < 3 Try clinicManagementServiceEvents.RegisterForEvents() registered = True Catch ex As Exception erviceEvents") Dim clinicManagementServiceEvents_ As ClinicManagementServiceEventsContract = DuplexChannelFactory( _ Of ClinicManagementServiceEventsContract).CreateChannel( _ context, binding, address) [Visual Basic] 'TODO 14 Dim contextNew InstanceContext(Me) As Dim bindingNew NetTcpBinding() As Dim addressNew As EndpointAddress("net.tcp://localhost:9003/Contoso/ClinicManagementS

2: Locate the the Locate 2: 1. 1. in the Explorer, In Solution Task 5: Implement the triggering method

f

MCT USE ONLY. STUDENT USE PROHIBITED

eventClients.Remove(client) Next Catch cex As CommunicationException problemClients.Add(client) End Try Next ' Assume that the client is no longer there and remove it clientFor Each As ClinicManagementServiceCallbackContract_ In problemClients 'TODO 15 Dim problemClientsList( As New_ Of ClinicManagementServiceCallbackContract)() clientFor Each As ClinicManagementServiceCallbackContract_ In eventClients Try client.NextPatientDueInToSeeConsultant(doctorId) problemClients) { eventClients.Remove(client); } [Visual Basic] { problemClients.Add(client); } } // Assume that the client is no longer there andremove it foreach (ClinicManagementServiceCallbackContractclient in foreach (ClinicManagementServiceCallbackContract client in eventClients) { try { client.NextPatientDueInToSeeConsultant(doctorId); } catch (CommunicationException cex) [Visual C#] // TODO 15 List problemClients= new List();

L5-100 Module 5: Designing and Defining Contracts MCT USE ONLY. STUDENT USE PROHIBITED

101 - View namespace and namespace , and then click file, and then click click file, and then . project, expand the the project, expand console window and press and press window console . Allow Lab: Contracts Services for and Data L5 ConsultantClient ClinicManagementServiceReference ConnectedWCF\ContosoServicesSelf ConnectedWCF\ContosoServicesSelf ConsultantForm ConsultantClient d then go to the following folder: the following to d then go . . . comment above the above the comment Update Service Reference Service Update folder, right-click the ContosoServicesSelfHostExtConfig.exe ContosoServicesSelfHostExtConfig TODO 16 TODO User Account Control dialog click box, User Account . If you are using Visual Basic, go to the folder the folder to go Visual Basic, using If you are E:\Labfiles\Starter\VB\Callback\ HostExtConfig\bin\Debug If you are using Visual C#, go to the folder the folder to Visual C#, go If you are using E:\Labfiles\Starter\CS\Callback\ HostExtConfig\bin\Debug

[Visual Basic] 'TODO 16 Imports ConsultantClient.ClinicManagementServiceReference [Visual C#] // TODO 16 using ConsultantClient.ClinicManagementServiceReference;

• • Run as administrator Run as Service References Code node, and then click then and node, host. service the to close ENTER add the following statement. statement. following add the Task 6: Call the triggering method the consultantfrom client 1. an Explorer, Windows Switch to

2. the file Right-click 4. 2008. Switch to Visual Studio 5. the expand Explorer, In Solution 3. In the In 3. 6. 6. Switch to the 7. 2008. Switch to Visual Studio 8. the right-click Explorer, In Solution 9. Locate the the Locate 9.

f

MCT USE ONLY. STUDENT USE PROHIBITED

, and then application.

. , and then , and then Debug tab, select tab, select method and addthe . , point to , point Next Patient Next , pointto Debug ClinicAdminClient for each clinic administration client, each clinic administration for is ready for the next patient. Click Appointment Admin nextPatient_Click livered to the clinic admin client ClinicAdminClient ConsultantClient Gastro_Jones list box, and then click list box, and then Start Without Debugging Without Start . . comment in the in the comment My ID menu, click menu, in the TODO 17 TODO Debug Start new instance Start new Start new instance Start new to close each message box. This demonstrates that the call to the operation call to the the that This demonstrates box. message each to close Dim clinicManagementService As ClinicManagementServiceContract_ = New ClinicManagementServiceContractClient() clinicManagementService.SendInNextPatient(doctorId.Text) new ClinicManagementServiceContractClient(); clinicManagementService.SendInNextPatient(doctorId.Text); [Visual Basic] 'TODO 17 [Visual C#] // TODO 17 ClinicManagementServiceContract clinicManagementService = click

following code. following Verify that two message boxes appear, one one appear, boxes message Verify that two doctor that that inform you OK client. the is now decoupled from Gastro_Jones click 3. the of instance to start a second 2 Repeat step 2. 2. right-click Explorer, In Solution Task 7: Verify that callbacksare de the On 1. the Locate 10. 5. the Client window, click In Consultant 4. 4. right-click Explorer, In Solution

f L5-102 Module 5: Designing and Defining Contracts MCT USE ONLY. STUDENT USE PROHIBITED 103 - tab, select tab, select . to close the message box. message the to close Next Patient Next OK Lab: Contracts Services for and Data L5 Appointment Admin Appointment have defined a callback contract and contract have defined a callback ppears that informs you that doctor that informs you that ppears tween two different service clients. . Stop Debugging list box, and then click list box, and My ID menu, click menu, is ready for the next patient. Click Click patient. is ready for the next in the Debug After completing this exercise, you After completing this

ENT_Davies Verify that only one message box a box message one Verify that only ENT_Davies Results: an event be used this to communicate 6. Client windows. of the Clinic Administration Close one 7. click the Client window, In the Consultant the On 8.

MCT USE ONLY. STUDENT USE PROHIBITED

105 - Lab: Handling ErrorsLab: Handling L6

6461A-LON-DEV-06 Student Virtual Machine: Virtual Machine: User Name: Password: Pa$$w0rd Password:

Estimated time: 40 minutes Logon Information: Logon Information: • Module 6: Handling Errors 6: Handling Module Errors Handling Lab: Exercise 1: • •

MCT USE ONLY. STUDENT USE PROHIBITED

.

Run as Visual

. 6461-LON- Pa$$w0rd Student Microsoft . the applications that use the applications that 2008, and then click , point to

Continue Studio

using the password using the Programs

h errors in the client application and h errors in the client at might occur in your services, so the first the first so your services, occur in might at All Visual

Student Control Client and double-click Control e service and examine the effects. the examine service and e admin client runs without errors as virtual machine and log on as on and log virtual machine , point to licy for your services and licy for your Start block to the client and report the exception to the user. the user. to exception the the client and report to block . try 6461-LON-DEV-06 6461-LON-DEV-06 2008, right-click Microsoft

User Account Control dialog click box, User Account DEV-06. administrator Studio them. It is difficult to predict all errors th them. It is difficult generate. might service the errors that any to handle do is thing to will add code to catc In this exercise, you client. to the errors the about information pass more to behavior service change the exercise are as follows: for this The main tasks the Start 1. 5. 5. client. to service Pass exception detail from 2. without errors. runs client that the clinic admin Confirm 3. outer error in th unexpected Force an an Add 4. Task 2: Confirm that the clinic 1. , click On the Task 1: Start the 6461-LON-DEV-06 virtual machine and log on as Student 1. Server Remote Virtual Open the Exercise 1: Handle Unexpected Errors in a WCF Service a WCF in Errors Unexpected Handle 1: Exercise Scenario define and implement to need stage, you prototyping the into moves project As the po a consistent error handling to on Log 2.

2. In the In 2.

f f L6-106 Module 6: Handling Errors MCT USE ONLY. STUDENT USE PROHIBITED

107 - tab. Open Open . , and then then , and , and then then , and . . OK . Lab: Handling ErrorsLab: Handling L6 project, right-click the right-click project, Refresh method and change the Create Appointment . constructor as follows: Project/Solution Unblock : window, click window, click View Code Create tment you have just added. You will use you have tment Basic® development system, in the in the system, Basic® development . . GetConnection form, click the form, in the service and examinethe service and the in SqlConnection xpectedErrors\ConnectedWCF xpectedErrors\ConnectedWCF AppointmentService tab, and then click then tab, and dialog box, click dialog box,

, and then click Open, and then . Start Debugging . Stop Debugging 5 (this selects the first slot shown) first the (this selects

ta, and then click click then ta, and file, and then click comment in the in the comment dialog box, go to the folder the folder to go box, dialog .\\Dummy ConnectedWCF.sln ConnectedWCF.sln ’s Appointments menu, click menu, menu, click menu, Gastro_Jones NH991199Z dialog box, go to the folder folder the to go box, dialog menu, point to TODO 1 TODO Today File Debug Debug Windows Security Alert Windows Clinic Administration Client Administration Clinic Clinic Admin Clinic Appointment Created Data Source: Data Source: Connection Timeout: Connection Timeout: If you are using Microsoft® Visual Microsoft® using If you are double-click Open Project E:\Labfiles\Starter\VB\Une Project E:\Labfiles\Starter\CS\Une double-click If you are using #® development tool, in the tool, Visual C#® development Microsoft If you are using Doctor: Doctor: Date: Today’s date Date: Today’s Slots Slot: Click Find Patient:

• • connection string passed into the the passed into string connection • AppointmentHelper • Enter the following da • this listing function as the basis of the rest of the exercises. exercises. of the rest of the basis this listing function as the On this tab, you should see the appoin should see tab, you On this • • • effects effects 1. the expand Explorer, In Solution the Locate 2. Task 3: Force an unexpectedForce an error 3: Task the On 3. 4. On the the On 4. 5. In the In 5. 6. In the In 6. 9. On the the On 9. 8. Click the 8. Click 7. In the In 7.

f

MCT USE ONLY. STUDENT USE PROHIBITED

tab, dialog box appear in s Appointments ’ ;" + Today Dummy dialog box appear in the client- in dialog box appear ) with the title "SQLException was title "SQLException ) with the . e service-side exception appearing and e service-side exception appearing alog box titles "TimeoutException was alog box titles "TimeoutException Visual Studio Exception Studio Visual ) with the title "FaultException was unhandled". ) with the title "FaultException was unhandled". . Stop Debugging . Start Debugging Continue . AppointmentHelper Visual Studio Exception Refresh menu, click menu, menu, click menu, menu, click menu, ClinicAdminForm Debug Debug Debug If you leave it too long between th If you leave it too long the service-side code ( the service-side "Connection Timeout=5"); [Visual C#] // TODO 1 returnSqlConnection("Data new Source=.\\ "Initial Catalog=Appointments;" + "Integrated Security=SSPI;" + [Visual Basic] ' TODO 1 ReturnSqlConnection("Data New Source=.\Dummy;" _ & "Initial Catalog=Appointments;"&_ "Integrated Security=SSPI;" & _ "Connection Timeout=5") and then click the you will see 5 seconds, After the see You will now side code ( unhandled by user code". This is the original exception inside the service service inside the exception original the is This code". user unhandled by string. connection value in the data source SQL the invalid caused by setting unhandled". In this case, restart the debugging session and perform the preceding restart the debugging this case, unhandled". In above more rapidly. Note: might see a di you continuing to debug, 6. On the the On 6. 3. On the the On 3.

5. On the the On 5. 4. the form, click Client In the Clinic Administration L6-108 Module 6: Handling Errors MCT USE ONLY. STUDENT USE PROHIBITED

109 - method, . OK Lab: Handling ErrorsLab: Handling L6 check box for check project, right-click the right-click project, . , and then click , and then User-unhandled . View Code RefreshAppointmentList_Click ClinicAdminClient Exceptions . Start Debugging comment in the in the comment file, and then click menu, click menu, menu, click menu, TODO 2 TODO Debug Debug dialog box, clear the clear dialog box, Exceptions

and then change the code in this method, as shown here. here. as shown this method, in code the change and then appointmentsToday.DataSource = proxy.ListTodaysAppointments(); } catch (Exception unknown) { MessageBox.Show(unknown.Message, "Clinic Admin: Error", MessageBoxButtons.OK); } [Visual C#] // TODO 2 try { AppointmentServiceContract proxy = GetAppointmentServiceProxy(); GetAppointmentServiceProxy() appointmentsToday.DataSource = proxy.ListTodaysAppointments() Catch unknown As Exception MessageBox.Show(unknown.Message, _ "Clinic Admin: Error", _ MessageBoxButtons.OK) End Try [Visual Basic] ' TODO 2 Try Dim proxy As AppointmentServiceContract = _ ClinicAdminForm ClinicAdminForm Common Language Runtime Exceptions Runtime Common Language 2. Locate the the Locate 2. 3. On the the On 3. Task 4: Add an outer try block to the client and report the exception to the user 1. the expand Explorer, In Solution

4. In the In 4. 5. On the the On 5.

f

MCT USE ONLY. STUDENT USE PROHIBITED

tab, project, project, behavior Service Service . . Add s Appointments ’ dialog box, click box, dialog message box. Verify that Verify box. message : . Today folder, expand the the expand folder, OK True Sections on the server in order to send the the send to in order the server on .

Save AppointmentServiceBehavior Advanced nt, or turn on tracing as per the the as per on tracing or turn nt, . . ContosoServicesSelfHostExtConfig property to property Clinic Admin: Error Admin: Clinic Add il from service to client . Stop Debugging . Start Debugging menu, click nfiguration Editor nfiguration window. File . Edit WCF click Edit , and then Configuration serviceDebug pane on the right side, set the value of the value of the the side, set right on the pane Refresh menu, click menu, menu, click menu, and then click click and then app.config Debug Debug pane, click click pane, AppointmentServiceBehavior Behavior: serviceDebug Adding Behavior Element Extension Element Behavior Adding "The server was unable to process the request due to an internal error. For error. internal an due to request the process to unable was "The server on turn either error, the about more information or from ServiceBehaviorAttribute (either from IncludeExceptionDetailInFaults configuration behavior) the server the inspect and documentation SDK 3.0 Framework .NET Microsoft trace logs." it displays the following message, and then click and then following message, the it displays clie to the information back exception serviceDebug click then and node, node. node. AppointmentServiceBehavior click the and then Behaviors folder, and then click and then the see seconds, you will 5 After IncludeExceptionDetailInFaults right-click Editorthe window, on 7. On the the On 7. 3. In the In 3. 6. In the In 6. 4. In the In 4. 5. the expand pane, In the Configuration 2. 2. the expand pane, In the Configuration Task 5: Pass exception deta 1. the expand Explorer, In Solution 6. the Client form, click Administration In the Clinic 8. 8. Co Service WCF Close the the On 9. 7. 7. Configuration (WCF) Service Foundation Communication In the Windows

f L6-110 Module 6: Handling Errors MCT USE ONLY. STUDENT USE PROHIBITED

111 - tab, Lab: Handling ErrorsLab: Handling L6 message box. Verify that Verify box. message : Today's Appointments Today's OK ng a connection to the server. When server. the to a connection ng ss more detail from service to client. Clinic Admin: Error Admin: Clinic . Stop Debugging . Refresh menu, click menu, Debug After completing this exercise, you have seen how to After completing this exercise, you have handle service connecting to SQL Server 2005, this failure may be caused by the fact that fact that by the may be caused this failure SQL Server 2005, to connecting connections. allow remote not does Server settings SQL default the under Server/Instance Locating Error - 26 error: Interfaces, Network SQL (provider: Specified)" "An error has occurred while establishi "An error has it displays the following message, and then click and then following message, the it displays and then click and then the see seconds, you will 5 After Results: client and how to pa exceptions on the 11. On the the On 11. 12. 12. system. development Visual Studio® 2008 Close Microsoft 10. the click Client form, Clinic Administration In the

MCT USE ONLY. STUDENT USE PROHIBITED

Run as Run as Visual

, andthen , andthen . Templates Microsoft project, point to point project, . nt and change the dialog box, go to the the to go box, dialog dialog box, go to the the to go dialog box, 2008, and then click , point to

Project/Solution Continue dialog box, in the dialog box, Studio

behavior so that the fault is the only fault is the the that so behavior Open Project Programs

Open Project . . h errors on the clie AppointmentService All istent error handling policy for your your policy for istent error handling Visual

, and then click then and , UnexpectedServiceFault ng to a WCF Service and the the Service and to a WCF ng to . Open, and then click , point to Name Start New Item New ConnectedWCF.sln ConnectedWCF.sln . menu, point to , set the Class, set E:\Labfiles\Starter\CS\ServiceErrors\ConnectedWCF E:\Labfiles\Starter\VB\ServiceErrors\ConnectedWCF File 2008, right-click Microsoft

Add New Item - AppointmentService New Add User Account Control dialog click box, User Account , and then click then , and . double-click double-click If you are using Visual Basic, in the Visual Basic, in the If you are using double-click double-click If you are using Visual C#, in the Visual C#, in the If you are using folder folder

mechanism for passing error information to the client. mechanism for passing error information • Studio administrator • Add pane, click Add Task 1: Define a fault contract 1. taskbar, click On the 3. 3. side. server on the the exception handle Catch and 4. service fault. the with to work code client Adjust the Service Contract Service what under and generate services your errors which specify you should services, part of the error definitions form These errors. these generate conditions they use them. that applications and the services the between contract will add code to catc In this exercise, you ExerciseAdd Fault 2: Handli Scenario cons a implement When you define and

service behavior to pass more information about the errors to the client. client. the to errors about the information pass more to behavior service exercise are as follows: for this The main tasks 1. a fault contract. Define 2. and run-time contract service the Adjust 3. On the the On 3. 2. In the In 2. 4. 4. the right-click Explorer, In Solution 5. In the In 5.

f L6-112 Module 6: Handling Errors MCT USE ONLY. STUDENT USE PROHIBITED

113 - Lab: Handling ErrorsLab: Handling L6 project, right-click project, right-click . containing the class to be to class the containing System.Runtime.Serialization View Code namespace AppointmentService

s tos thegenerated code: , and then click then , and look like the following. like the following. look If you are using Visual C#, delete the following statements. C#, delete the following statements. If you are using Visual Add a statement to bring the namespace namespace the to bring Add a statement into scope. Visual C#, set the If you are using . com.contoso

• { } } [Visual C#] using System; using System.Runtime.Serialization; namespace com.contoso { class UnexpectedServiceFault [Visual Basic] Imports System.Runtime.Serialization Class UnexpectedServiceFault End Class • [Visual C#] using System.Collections.Generic; using System.Linq; using System.Text; • Your code should now UnexpectedServiceFault 7. change Make the following 6. the expand Explorer, In Solution

MCT USE ONLY. STUDENT USE PROHIBITED

class. class as follows. class UnexpectedServiceFault UnexpectedServiceFault

Return _errorCode End Get Set _errorCode = value End Set End Property End Set End Property Private _errorCode As Integer = -1 _ Public Property ErrorCode() As Integer Get Private_endUserMessage String As = "UNDEFINED" _ Public Property EndUserMessage()As String Get Return _endUserMessage End Get Set _endUserMessage = value public classUnexpectedServiceFault { } [Visual Basic] End Class [Visual C#] [DataContract(Namespace="http://contoso.com/ClinicManagementSystem/ 2007/10")] [Visual Basic] _ Public ClassUnexpectedServiceFault 9. Add the following code to the 8. the of definition the Modify L6-114 Module 6: Handling Errors MCT USE ONLY. STUDENT USE PROHIBITED

115 - method . Lab: Handling ErrorsLab: Handling L6 project, right-click the right-click project, View Code ListTodaysAppointments ing error information to the client ing error information to the client to the to the method. AppointmentService file, and then click then click file, and FaultContract comment above the above the comment TODO 3 TODO and add the following _ Function ListTodaysAppointments() As List(Of Appointment) [Visual Basic] ' TODO 3 _ { return _errorCode; } set { _errorCode = value; } } private int _errorCode =-1; [DataMember] publicErrorCode int { get { return _endUserMessage; } set { _endUserMessage value;= } } [Visual C#] private string _endUserMessage = "UNDEFINED"; [DataMember] public stringEndUserMessage { get AppointmentServiceContract Task 2: Adjust the service contract and run-timebehavior so that the fault is the only mechanism for pass 1. the expand Explorer, In Solution 2. Locate the the Locate 2.

f

MCT USE ONLY. STUDENT USE PROHIBITED

project, project, . Service Service with a method and . menu, click click menu, node,and then View Code File . block (for Visual C#) that block folder, expand the the expand folder, False try/catch Advanced file, and then click click file, and then ListTodaysAppointments ContosoServicesSelfHostExtConfig property to property AppointmentServiceBehavior project, right-click the the right-click AppointmentService project, nfiguration Editor nfiguration window. , as shown in the following code. in the following , as shown Exception Edit WCF Edit click Configuration , and then pane on the right side, set the value of the value of the the side, set right on the pane comment in the in the comment . TODO 4 TODO block (for Visual Basic) or a Visual (for block app.config serviceDebug serviceDebug . will catch any form of surround the call to AppointmentHelper.ListTodaysAppointments surround the Try/Catch click IncludeExceptionDetailInFaults folder, expand the the expand Behaviors folder, Save AppointmentServiceImplementation AppointmentServiceImplementation Try Return New AppointmentHelper().ListTodaysAppointments() Catch unexpected As Exception End Try [Visual Basic] ' TODO 4 [Visual C#] // TODO 3 [OperationContract] [FaultContract(typeof(com.contoso.UnexpectedServiceFault))] List ListTodaysAppointments(); right-click 5. In the In 5. 7. 7. Co Service WCF Close the 2. Locate the the Locate 2. 6. on the Editorwindow, Service Configuration In the WCF 4. 4. the expand pane, In the Configuration side server on the the exception handle and 3: Catch Task 1. in the Explorer, In Solution 3. 3. the expand Explorer, In Solution

f L6-116 Module 6: Handling Errors MCT USE ONLY. STUDENT USE PROHIBITED

117 - Lab: Handling ErrorsLab: Handling L6 block, add the following code. block, add the following catch return new AppointmentHelper().ListTodaysAppointments(); LogException(unexpected,"ListTodaysAppointments"); "try this operation again." + " If it still does not work then " + "please contact your support department."; fault.ErrorCode = 101; throw new FaultException(fault, "An unexpected error occurred inside the service."); } [Visual C#] catch (Exception unexpected) { UnexpectedServiceFault fault = new UnexpectedServiceFault(); fault.EndUserMessage = "There was an unexpected error " + "on the server. You may beable to " + "please contact your support department." fault.ErrorCode = 101 Throw New FaultException(Of UnexpectedServiceFault)(fault, _ "An unexpected error occurred inside theservice.") End Try [Visual Basic] Catch unexpected As Exception LogException(unexpected,"ListTodaysAppointments") Dim fault As New UnexpectedServiceFault() fault.EndUserMessage = "There was an unexpected error " & _ "on the server. You may beable to " & _ "try this operation again." & _ " If it still does not work then " & _ catch (Exception unexpected) { } [Visual C#] // TODO 4 try { } 3. In the In 3.

MCT USE ONLY. STUDENT USE PROHIBITED

. View Code. folder, right-click folder, right-click , and then click ClinicAdminClient . .exe . solution, and then click solution, console window and press and press window console , point to, and Accessories Unblock Update Service Reference Service Update Allow file, and then click and file, rs\ConnectedWCF\ContosoService Service References References Service ors\ConnectedWCF\ContosoService Programs

ConnectedWCF All , and then click , and then dialog box, click dialog box, to work with the service fault In Solution Explorer, expand the the expand Explorer, In Solution . . In Solution Explorer, in the in the Explorer, . In Solution , point to to the following folder: the following folder: to . Start project, expand the the expand project, ContosoServicesSelfHostExtConfig . ContosoServicesSelfHostExtConfig User Account Control dialog click box, User Account Security Alert Windows If you are using Visual Basic, go to Visual Basic, go If you are using E:\Labfiles\Starter\VB\ServiceErr sSelfHostExtConfig\bin\Debug sSelfHostExtConfig\bin\Debug If you are using Visual C#, go to to Visual C#, go If you are using E:\Labfiles\Starter\CS\ServiceErro

• Windows Explorer then click Windows Rebuild Solution Rebuild • Run as Administrator ENTER to close the service host. service the to close ENTER ClinicAdminClient AppointmentServiceReference project, right-click the ClinicAdminForm right-click project, 2. 2. go Explorer, In Windows 1. 1. taskbar, click On the Task 4: Adjust the client code 4. the right-click Explorer, In Solution 5. In the In 5. 4. In the In 4. 7. 7. Switch to the 8. 2008 Switch to Visual Studio 6. 2008. Switch to Visual Studio 3. Right-click the file

f L6-118 Module 6: Handling Errors MCT USE ONLY. STUDENT USE PROHIBITED

119 - method block (for block . Lab: Handling ErrorsLab: Handling L6 try/catch ) . , _ , Unblock RefreshAppointmentList_Click RefreshAppointmentList_Click dialog box, click dialog box, Start Without Debugging Without Start block (for Visual Basic) or a (for Visual block ex.Detail.EndUserMessage ex.Detail.EndUserMessage comment in the in the comment Try/Catch menu, click menu, TODO 2 TODO

FaultException ex Debug ex As FaultException(Of UnexpectedServiceFault) Windows Security Alert Windows Visual C#) as shown in the following code. following as the Visual C#) shown in and change the and change "Clinic Admin: Error", MessageBoxButtons.OK); } AppointmentServiceContract proxy = GetAppointmentServiceProxy(); appointmentsToday.DataSource = proxy.ListTodaysAppointments(); } catch ( { MessageBox.Show( MessageBoxButtons.OK) End Try [Visual C#] // TODO 2 try { Try Dim proxy As AppointmentServiceContract = _ GetAppointmentServiceProxy() appointmentsToday.DataSource = proxy.ListTodaysAppointments() Catch MessageBox.Show( "Clinic Admin: Error", _ [Visual Basic] ' TODO 2 11. In the In 11. 10. On the the On 10. the Locate 9.

MCT USE ONLY. STUDENT USE PROHIBITED tab, s Appointments ’ message box. Verify that Verify box. message Today ve defined a fault contract and used and ve defined a fault contract server. You may be able to try this this be able to try You may server. rk then please contact your support then please contact your support rk Clinic Admin: Error Admin: Clinic . Refresh After completing this exercise, you ha After completing this it displays the following message: following message: the it displays the on error unexpected was an "There it still does not wo operation again. If department" and then click and then the see seconds, you will 5 After this to pass error detail between a WCF service and a client. between a WCF service and a client. this to pass error detail Results: 13. 13. 2008. Studio Close Visual 12. the click Client form, Clinic Administration In the L6-120 Module 6: Handling Errors MCT USE ONLY. STUDENT USE PROHIBITED

121 - Lab: Improving Service Quality L7

6461A-LON-DEV-07 Student Virtual Machine: Virtual Machine: User Name: Password: Pa$$w0rd Password:

• Estimated time: 80 minutes Module 7: Improving WCF Service Quality Service Quality WCF 7: Improving Module Quality Service Improving Lab: Logon Information: • •

MCT USE ONLY. STUDENT USE PROHIBITED

.

Studio

. Run as Visual

Pa$$w0rd Student .

Continue , and then click 2008, and then

using the password using the ion is divided on whether to have a to have on whether ion is divided ementation with one based on an in- ementation with nager and some of the more technically technically more the nager and some of e the appointment data between clients. data between appointment e the to show how problems such as lost or problems such as lost to show how intment service implementation with one with intment service implementation ces. You have been asked to demonstrate demonstrate asked to been have ces. You t. You will then set the state management set the state management t. You will then ntrol Client and double-click 6461-LON- Client and ntrol Studio service implementation with one

Student , point to Microsoft , point Programs

as virtual machine and log on as on and log virtual machine All Visual

emory linked list . menu, point to menu, point to 6461-LON-DEV-07 6461-LON-DEV-07 Start User Account Control dialog click box, User Account DEV-07. 2008, right-click Microsoft administrator memory linked list. 2. Log on to to on Log 2. 2. In the In 2. 3. 3. shar context mode to instance Set the Task 2: Replace the appointment based on an in-m the On 1. 1. 1. Co Server Remote Virtual Open the style so that multiple clients can "see" the appointments and then load the service the load and then appointments clients can "see" the multiple style so that issues. concurrency until it clearly demonstrates exercise are as follows: for this The main tasks the Start 1. 2. service impl appointment Replace the Task 1: Start the 6461-LON-DEV-07 virtual machine and log on as Student single service instance or multiple instan single service instance is selected. option the wrong if might occur data corrupt will replace the appo In this exercise, you on a linked lis that stores appointments Exercise 1: Managing WCF Service Instances WCF Service Managing 1: Exercise Scenario for the approach and threading instance management best the determine You must Opin System. Contoso Clinic Management ma development to the issues of the some need you To do this, aware stakeholders.

f f L7-122 Module 7: Improving WCF Service Quality MCT USE ONLY. STUDENT USE PROHIBITED

123 - that

project, project, View method. method. file, and . Open Open : Main passed in as passed in View Code project, right-click the right-click project, List ) file, and then click file, Lab: Improving Service Quality L7 Project/Solution comment in the in the comment LinkedListAppointmentHelper steps through the linked list to find linked list to find the through steps . . Basic® development system, in the in the system, Basic® development LinkedListAppointmentHelper TODO 1 TODO LinkedListAppointmentHelper method walks through the linked list and through the linked list method walks , and , and nceManagement\ConnectedWCF , and , and nceManagement\ConnectedWCF methods ListTodaysAppointments ContosoServicesSelfHostExtConfig AppointmentService for the appointment service to service to appointment for the method wrapsthe Appointment and , and then click Open, and then ConnectedWCF.sln ConnectedWCF.sln . Examine the code in this file to see how: code in this file to Examine the . dialog box, go to the folder the folder to go box, dialog . file, and then click then file, and ContosoServicesHost dialog box, go to the folder folder the to go box, dialog menu, point to ListTodaysAppointments CreateAppointment CreateAppointment File window, locate the View Code window, locate . Examine the code in this file to see how: how: file to see this in code Examine the . the end, and appends the wrapped appointment to the list. the to appointment wrapped the appends and the end, The into a today occur that places any appointments the parameter in a linked-list wrapper, in the parameter it returns. The If you are using Microsoft® Visual Microsoft® using If you are Project E:\Labfiles\Starter\CS\Insta then double-click instance. Open Project E:\Labfiles\Starter\VB\Insta then double-click in the tool, Visual C#® development Microsoft If you are using The constructor creates an instance of the the of an instance creates constructor The class. The functionality to the delegate their

Change the service instance type instance service Change the com.contoso.AppointmentService.AppointmentServiceLinkedList com.contoso.AppointmentService.AppointmentServiceLinkedList Implementation ' TODO 1 Dim appointmentInstanceType _ As Type = GetType(com.contoso.AppointmentService. _ AppointmentServiceLinkedListImplementation [Visual Basic] • then click View Code • • • right-click the right-click the AppointmentServiceLinkedListImplementation AppointmentServiceLinkedListImplementation • Code • the On 3. 6. 6. the expand Explorer, In Solution 7. In the In 7. 4. 4. the expand Explorer, In Solution 5. the right-click Explorer, In Solution

MCT USE ONLY. STUDENT USE PROHIBITED

. In . In tab. menu, click , click and then Edit WCF File . ); Create Appointment Unblock window. , and then click window, on the the window, on ppointmentServiceImplementation form, click the form, the appointment service is running service is running the appointment Solution 'Connected WCF' 'Connected Solution app.config dialog box, click dialog box, value to . Start Debugging . Stop Debugging Name folder, and then click and then folder, . . , and then verify that a list of available slots is displayed. This displayed. slots is , and then verify that a list of available . menu, click menu, menu, click menu, Services WCF Service Configuration Editor Configuration Service WCF Debug Debug Windows Security Alert Windows WCF Service Configuration Editor Configuration WCF Service Clinic Administration Client Administration Clinic Find Slots . Rebuild Solution Rebuild Save Configuration [Visual C#] // TODO 1 Type appointmentInstanceType = typeof(com.contoso.AppointmentService. AppointmentServiceLinkedListImplementation com.contoso.AppointmentService.AppointmentServiceLinkedList com.contoso.AppointmentService.AppointmentServiceLinkedList Implementation the right pane, set the set the pane, the right com.contoso.AppointmentService.A confirms that the linked list form of linked list the confirms that correctly. 13. On the the On 13. 11. Close the the Close 11. 12. 12. right-click Explorer, In Solution 14. In the In 14. 8. 8. right-click Explorer, In Solution 9. Expand the the Expand 9. the In 10.

16. Click 16. 17. On the the On 17. 15. In the In 15. L7-124 Module 7: Improving WCF Service Quality MCT USE ONLY. STUDENT USE PROHIBITED 125

-

. . This form OK Multiple project, project, None. View Code solution, and then click for the for Lab: Improving Service Quality L7 dialog box, click box, dialog dialog box, click box, dialog Action , so each client thread gets its own its gets thread client so each , st value reported by the service if it by the st value reported HighSpeedAppointmentMaker window, increase the number of the number window, increase currently reported by the service, the service, by reported currently file, and then click file, . and ConnectedWCF reads, you would expect 80 (4 x 20) 80 (4 expect would you reads, of which makes calls to the appointment of which makes calls Go HighSpeedAppointmentMaker list, set the the list, set method that each thread calls. This method calls. This method each thread that method for the remaining projects to projects remaining the for . Start Debugging . Stop Debugging operation 20 times. This method reports its progress by by its progress reports method times. This 20 operation . . . Set the Action the . Set menu, click menu, menu, click menu, HighSpeedMainForm HighSpeedMainForm AddAppointments Projects Start projects

Debug Debug Solution 'ConnectedWCF' Property Pages Property 'ConnectedWCF' Solution Solution 'ConnectedWCF' Property Pages Property 'ConnectedWCF' Solution Multiple startup projects High Speed Appointment Maker Appointment High Speed Startup

startup ContosoServicesSelfHostExtConfig projects to client threads to 4, and then click 4, and then to client threads service. Examine the calls the and then service appointment for the creates a proxy CreateAppointment far. so has added this thread appointments of the number with together th with 4 If you run this application asking the appointment service for a list of the current appointments and appointments service for a list of the current asking the appointment of appointments number displaying the starts multiple client threads, each starts multiple client the service. on made be to appointments Set Each row shows the results from one thread. Verify that each thread reports reports each thread Verify that thread. from one results the row shows Each reports service the that number the that but 20 appointments that it has added service by the values reported of the one At least only 20. in each case is la the be would because that 80 should be had received all 80 appointment requests. The problem is that the default is that the problem The requests. 80 appointment all had received is PerSession instance management mode made by appointments the see service and cannot appointment instance of the threads. client other the right-click the right-click the 5. In the In 5. 4. In the In 4. 6. On the the On 6. 2. 2. the right-click Explorer, In Solution 3. In the In 3. 7. In the In 7. 8. On the the On 8. Task 3: Set the instance management style to share the appointment data between clients 1. the expand Explorer, In Solution

f

MCT USE ONLY. STUDENT USE PROHIBITED

View property property set project, right-click the right-click project, file, and then click and file, class definition, and then then class definition, and ve seen how to change the instance InstanceContextMode window, increase the number of the number window, increase . Go AppointmentService . All client threads will now interact with the will now interact with . All client threads with its . Start Debugging . Stop Debugging comment above the above the comment menu, click menu, menu, click menu, TODO 2 TODO Debug Debug High Speed Appointment Maker Appointment High Speed After completing this exercise, you ha . InstanceContextMode.Single same instance of the appointment service. service. appointment same instance of the to // TODO 2 [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class AppointmentServiceLinkedListImplementation : AppointmentServiceContract ... InstanceContextMode.[Single])> _ Public Class AppointmentServiceLinkedListImplementation Implements AppointmentServiceContract ... [Visual C#] [Visual Basic] ' TODO 2

127 - Studio

, andthen , andthen : Run as . Visual

. project, right-click the right-click project, dialog box, go to the the to go box, dialog ading and instance ading and instance View Code dialog box, go to the the to go dialog box, Lab: Improving Service Quality L7 Project/Solution Continue , and then click 2008, and then

Open Project Open Project . . problems that might occur from longer- occur might that problems can access the service without corruption. corruption. without service can access the Studio mbination of thre

AppointmentService file, and then click , point to Microsoft , point Programs

All Visual Open and then click

ntionally create a threading problem in the linked-list problem in ntionally create a threading ConnectedWCF.sln ConnectedWCF.sln . menu, point to menu, point to menu, point to E:\Labfiles\Starter\VB\Concurrency\ConnectedWCF E:\Labfiles\Starter\CS\Concurrency\ConnectedWCF File Start User Account Control dialog click box, User Account If you are using Visual Basic, in the Visual Basic, in the If you are using double-click double-click folder double-click double-click If you are using Visual C#, in the Visual C#, in the If you are using folder

• 2008, right-click Microsoft administrator multi-threading. LinkedListAppointmentHelper • 3. On the the On 3. 2. In the In 2. Task 1:DemonstrateTask threadingthedefaults that to a safe service mode the On 1. running methods and resource contention. To do this, you need to show how how to show need you this, do To contention. resource and running methods co wrong occur if the might corruption exercise are as follows: for this The main tasks 1. mode. threading defaults to a safe service the that Demonstrate 2. due to corruption can lead to service up the to speed attempts that Show Exercise 2: Managing Concurrency Issues Issues Concurrency 2: Managing Exercise Scenario the demonstrate asked to been You have will then modify the You implementation. appointment service version of the that multiple clients threading mode so management is selected. will inte In this exercise, you 4. 4. the expand Explorer, In Solution

f

MCT USE ONLY. STUDENT USE PROHIBITED

. method, and then method, Unblock t and so the service should gradually service should and so the t CreateAppointment dialog box, click dialog box, . Start Debugging comment in the in the comment should allow any other thread running in the service to service to the in running thread other allow any should menu, click menu, Sleep TODO 3 TODO Debug Windows Security Alert Windows add the following code. following add the Console.WriteLine(String.Format("{0}: woken up", DateTime.Now.ToLongTimeString())); The call to ", id is {3} : about to sleep", DateTime.Now.ToLongTimeString(), appointment.DoctorId, appointment.PatientId, appointment.Id)); Thread.Sleep(500); "lose" appointments. Console.WriteLine([String].Format("{0}: woken_ up", DateTime.Now.ToLongTimeString())) [Visual C#] // TODO 3 Console.WriteLine(String.Format("{0}: called with {1}& {2}" + lis obtain a duplicate place in the linked ", id is {3} : aboutto sleep", _ DateTime.Now.ToLongTimeString(), _ appointment.DoctorId, _ appointment.PatientId, _ appointment.Id)) Thread.Sleep(500) [Visual Basic] ' TODO 3 Console.WriteLine([String].Format("{0}: called with {1} & {2}" & _ 6. On the the On 6. the Locate 5. 7. In the In 7. L7-128 Module 7: Improving WCF Service Quality MCT USE ONLY. STUDENT USE PROHIBITED

129 - View call you Sleep call project, right-click the right-click project, )> _ _ )> )] file, and then click and then click file, Lab: Improving Service Quality L7 class definition, and then then class definition, and read from accessing the service read from accessing because the default threading mode is threading default because the window, increase the number of the number increase window, sleeping in the service. However, the service. However, in the sleeping , as shown in the following code. following the , as shown in . has added 20 appointments and that at that and 20 appointments has added Go , you might expect that the the that expect you might , AppointmentService speed up the can lead to up the service speed Stop Debugging. Single . Start Debugging comment above the above the comment menu, click menu, menu, click menu, ServiceBehaviorAttribute TODO 2 TODO Debug Debug High Speed Appointment Maker Appointment High Speed ; this prevents any other calling th ; this prevents any . ConcurrencyMode=ConcurrencyMode.Multiple ConcurrencyMode:=ConcurrencyMode.Multiple client threads to 4, and then click then 4, and to client threads ... [Visual C#] // TODO 2 [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, public class AppointmentServiceLinkedListImplementation : AppointmentServiceContract ' TODO 2

f

MCT USE ONLY. STUDENT USE PROHIBITED

w 80. As you can see, in an effort to to effort in an see, can you As w 80. ve seen how to control the threading window, increase the number of the number increase window, . Go . Stop Debugging menu, click menu, Debug High Speed Appointment Maker Appointment High Speed After completing this exercise, you ha After completing this client threads to 4, and then click then 4, and to client threads Verify that each thread reports that it has added 20 appointments but that the the that but 20 appointments has added that it reports thread each Verify that are well belo by the service values reported improve performance, this has opened up potential for corruption due to due for corruption potential up opened has this performance, improve list). linked the is resource the case, (in this contention resource Results: mode of a service. 5. On the the On 5. the In 4. 6. 6. 2008. Close Visual Studio L7-130 Module 7: Improving WCF Service Quality MCT USE ONLY. STUDENT USE PROHIBITED

131 - Studio

. This . project, project, , and then then , and , and then then , and Run as Visual

a week. However, . View Code dialog box, go to the the to go box, dialog dialog box, go to the the to go dialog box, Lab: Improving Service Quality L7 rottling setting affects the rottling setting Project/Solution Continue , and then click 2008, and then

on of the calls made by each client calls made by each of the on Open Project e over the course of the service. Also, the level of load from of load from level the Also, service. the deploy the system on a limited amount deploy the system Open Project . . file, and then click file, s overall impact on response times and response on impact overall s ey will not appreciate the system running the system ey will not appreciate ands at the administrator's desk in the ands Clinic Management System will vary over vary will System Clinic Management Studio

HighSpeedAppointmentMaker , point to Microsoft , point Programs

All Visual Open, and then click

Access to a WCF Service Access asure of the response times with an overall average. e of the response times. of the response e ConnectedWCF.sln ConnectedWCF.sln . HighSpeedMainForm HighSpeedMainForm menu, point to menu, point to menu, point to E:\Labfiles\Starter\CS\Throttling\ConnectedWCF E:\Labfiles\Starter\VB\Throttling\ConnectedWCF File Start User Account Control dialog click box, User Account double-click double-click double-click double-click If you are using Visual Basic, in the Visual Basic, in the If you are using If you are using Visual C#, in the Visual C#, in the If you are using folder folder

version of the application times the durati version of the thread and provides you • 2008, right-click Microsoft administrator right-click the right-click the • 3. On the the On 3. 2. In the In 2. 4. 4. the expand Explorer, In Solution Task 1: Take an initial me the On 1. the family practitioners will be unpredictabl will the family practitioners Exercise 3: Throttling Throttling 3: Exercise Scenario Contoso on the placed of load The level up to family practitioners sign time as more practice waiting for their appointment, th practice waiting for will probably initiallyslowly. Because you clients will of throttling the number must explore how effective of hardware, you performance. maintaining service be in terms of the service th will investigate how In this exercise, you one thing is for certain: when a patient st one thing is for certain: callers and it for successful time response throughput. exercise are as follows: for this The main tasks 1. Take an initial measur 2. times. response overall on effect of throttling the Determine 3. times. caller response on successful effect of throttling the Determine

f

MCT USE ONLY. STUDENT USE PROHIBITED

. . OK project, project, behavior property property . menu, click folder, and then then folder, and File . method, and then then and method, dialog box, select select box, dialog operations, operations, and then it Unblock window. MaxConcurrentCalls

window, on the window, on Service Behaviors window, increase the number of the number window, increase if it is blocked waiting for a service if it is blocked waiting kes a before the calls timestamp to the behavior. In the rightpane, click Add . HttpMexAndExceptionDetail erage timing across the 20 pairs of calls. of 20 pairs timing across the erage . . AddAppointments rottling on overall response times Go Add ContosoServicesSelfHostExtConfig dialog box, click dialog box, . Start Debugging Start Debugging. Start Debugging. . Stop Debugging ListTodaysAppointments folder, expandthe Edit WCF click Edit , and then Configuration serviceThrottling and comment in the in the comment , and then click then and , menu, click menu, menu, click menu, menu, click menu, Advanced TODO 4 TODO app.config WCF Service Configuration Editor Configuration Service WCF HttpMexAndExceptionDetail Debug Debug Debug Adding Behavior Element Extension Sections Behavior Element Adding WCF Service Configuration Editor Configuration WCF Service Windows Security Alert Windows High Speed Appointment Maker Appointment High Speed . . Because these timings are taken on the they client side, will include any Save uses this information to calculate an av information to calculate uses this examine the code below it. This code ta code below it. examine the CreateAppointment to 3 right-click client threads to 10, and then click to client threads click the node, and then click then and node, After all the threads finish, make a note of the average value for the call call value for the of the average make a note finish, threads After all the click then and dialog box, in the reported threads 10 the across duration serviceThrottling Note: waiting time encountered such as by the call, instance. 7. Close the the Close 7. 8. On the the On 8. 6. In the In 6. 2. Expand the the Expand 2. Task 2: Determine the effect of th 1. the expand Explorer, In Solution 6. On the the On 6. 5. set the value of In the serviceThrottling pane, the Locate 5. the In 7. 8. In the In 8. 3. In the In 3. 4. the expand pane, In the Configuration 9. On the the On 9.

f L7-132 Module 7: Improving WCF Service Quality MCT USE ONLY. STUDENT USE PROHIBITED

133 - . project, project, method.

method. variable. variable. View Code method, and then and then method, variable. ccessful caller response Lab: Improving Service Quality L7 startTimestamp variable. endTimestamp millisThisCall window, increase the number of the number increase window, will see a dialog box that contains an contains box that dialog will see a e time taken per-call when measured e time taken per-call CreateAppointment ListTodaysAppointments . file, and then click and then click file, AddAppointments leave a service instance so that the so that a service instance leave calling threads are now having to block now having to calling threads are Go HighSpeedAppointmentMaker . Stop Debugging . fect of throttling on su OK comment in the in the comment menu, click menu, HighSpeedMainForm HighSpeedMainForm TODO 4 TODO Debug High Speed Appointment Maker Appointment High Speed Delete the statement that calls the that statement Delete the Delete the statement that calls the that statement Delete the the creates that statement Delete the the creates that statement Delete the Delete the statement that creates the creates that statement Delete the

• • • • perform the following steps: the perform • client threads to 10, and then click 10, to client threads callTime += appointmentService.TimedListTodaysAppointments() Dim millisThisCall As IntegercallTime.Milliseconds= [Visual Basic] ' TODO 4 Dim callTime As TimeSpan = _ appointmentService.TimedCreateAppointment(myPatient, myDoctor, _ start.AddMinutes(i * 30)) Add the following code: from the client side. This is because This is from the client side. to calling thread waiting for another 3. drops below calls of concurrent number right-click the Verify that this value is more than that reported earlier. earlier. reported than that more value is Verify that this of the number value of less than a throttling setting that find You should increased the averag calling threads has average value for the call duration across the 10 threads. Make a note of this a note Make 10 threads. the across duration call for the value average then click value, and After all the threads finish running, you threads finish running, After all the 2. Locate the the Locate 2. 10. On the the On 10. 1. 1. the expand Explorer, In Solution Task 3: Determine the ef times the In 9.

f

MCT USE ONLY. STUDENT USE PROHIBITED

. project, project, . menu, click File folder, expand the expand the folder, serviceThrottling

window.

ed in Task 2. Verify that this new new Verify that this Task 2. in ed

window, on the the window, on a note of the average value for the the value for average of the note a window, increase the number of the number window, increase recording the duration of calls on the calls on the of duration the recording . Go 20. ContosoServicesSelfHostExtConfig behavior, and then click then and behavior, Start Debugging. . Stop Debugging Start Debugging. Start Debugging. property property to Edit WCF click Edit , and then Configuration menu, click menu, menu, click menu, menu, click menu, app.config WCF Service Configuration Editor Configuration Service WCF Advanced folder,Advanced expandthe Behaviors Service Debug Debug Debug High Speed Appointment Maker Appointment High Speed WCF Service Configuration Editor Configuration WCF Service . . int millisThisCallcallTime.Milliseconds; = [Visual C#] // TODO 4 TimeSpan callTime = appointmentService.TimedCreateAppointment(myPatient, myDoctor, start.AddMinutes(i * 30)); callTime += appointmentService.TimedListTodaysAppointments(); client threads to 10, and then click 10, and then to client threads After all the threads finish running, make finish running, threads After all the click then and dialog box, in the reported threads 10 the call duration across OK record with the ones you value Compare this value is significantly lower because it is value is significantly lower because it any include calls. This does not concurrent only 3 are there when service side wait time. HttpMexAndExceptionDetail Save right-click MaxConcurrentCalls 3. On the the On 3.

4. In the In 4. 5. On the the On 5. 10. Close the the Close 10. 7. Expand Expand 7. the On 11. 8. 8. value of the side, set right the on pane In the serviceThrottling 6. 6. the expand Explorer, In Solution 9. In the In 9. L7-134 Module 7: Improving WCF Service Quality MCT USE ONLY. STUDENT USE PROHIBITED

135 - Lab: Improving Service Quality L7 sources at the same time. This will This will time. sources at the same a note of the average value for the the average value for of the note a window, increase the number of the number increase window, e time taken per-call when measured e time taken per-call have seen how to use throttling and . than the value you recorded earlier in the than Go service-side re r service-side higher call time will be seen. higher . Stop Debugging menu, click menu, Debug High Speed Appointment Maker Appointment High Speed After completing this exercise, you . client threads to 10, and then click 10, to client threads After all the threads finish running, make finish running, threads After all the click then and dialog box, in the reported threads 10 the across call duration OK higher value is slightly Verify that this 10 concurrent potentially are now because there This is side. service from the fo calling threads contending down and so a slow things this task. Has removing throttling increased or decreased this overall service- this decreased or increased removing throttling this task. Has side time? of number than the value to more throttling the setting that find You should increased the averag calling threads has Results: how it affects the callers to a service. the In 12. the On 13. 14. 14. 2008. Close Visual Studio

MCT USE ONLY. STUDENT USE PROHIBITED

Studio

Run as Visual

. Continue , and then click 2008, and then

of MRI scan and X-ray images. These files X-ray images. scan and of MRI ss as a standard parameter, so they will parameter, so ss as a standard e as a byte array to a WCF service. a e as a byte array to ry data across a WCF service interface WCF interface service data across a ry Studio

, point to Microsoft , point Programs

All Visual

to call the new operation. to call the new . menu, point to menu, point to Start User Account Control dialog click box, User Account

2008, right-click Microsoft administrator 2. In the In 2. 1. On the the On 1. Task 1: Add an operation to return an image as a byte array to a WCF service will be far larger than is reasonable to pa will be far larger than handling. of special form need some will pass large bina In this exercise, you and streaming. MTOM using both exercise are as follows: for this The main tasks 1. imag an return to operation an Add Exercise 4: Passing Bulk Data Between a WCF Client and WCF Client a Between Data Bulk Passing 4: Exercise Service Scenario to will need access System Management Clinic consultants using the Contoso The in the form data of patient large amounts 9. use streaming. client to Configure the 10. streamed messages. View the raw 2. encoding. MTOM uses that endpoint Add a service 3. operation. the new call client to the to code Add 4. Configure client the to use MTOM encoding. 5. MTOM messages. View the raw 6. Add a streamed method to the contract. 7. streaming. support to endpoint service-side Change the 8. Change the client code

f L7-136 Module 7: Improving WCF Service Quality MCT USE ONLY. STUDENT USE PROHIBITED

137 - View class. . , and then then , and , and then then , and project, right- project, right- project, file, and then click click then and file, file, and then click file, and dialog box, go to the the to go box, dialog dialog box, go to the the to go dialog box, Lab: Improving Service Quality L7 Project/Solution interface. Open Project Open Project . . PatientManagementService PatientManagementService , and then click Open, and then to the list of interfaces of list the to viceImageContract PatientManagementServiceImplementation PatientManagementServiceImplementation comment, and then add and then comment, comment, and then add the following code to the the to code the following add and then comment, ConnectedWCF.sln ConnectedWCF.sln menu, point to . TODO 6 TODO TODO 5 TODO \BulkData\ConnectedWCF E:\Labfiles\Starter\VB E:\Labfiles\Starter\CS\BulkData\ConnectedWCF PatientManagementServiceImplementation PatientManagementServiceImplementation PatientManagementServiceImageContract PatientManagementServiceImageContract File . Implements PatientManagementServiceImageContract If you are using Visual Basic, in the in the Visual Basic, using If you are double-click double-click folder double-click double-click If you are using Visual C#, in the Visual C#, in the If you are using folder

[Visual Basic] ' TODO 6 Public ClassPatientManagementServiceImplementation Implements PatientManagementServiceContract [Visual C#] // TODO 5 [OperationContract] byte[] GetXrayImage(string patientId, string type); [Visual Basic] ' TODO 5 _ Function GetXrayImage(ByVal patientId As String,_ ByVal type As String) As Byte() click the PatientManagementSer implemented by the • View Code click the • Code PatientManagementServiceImageContract 6. 6. the under Explorer, In Solution the On 3. 7. Locate the the Locate 7. 4. 4. the expand Explorer, In Solution 5. Locate the the Locate 5.

MCT USE ONLY. STUDENT USE PROHIBITED

, point , point project, project, , . . . , and then press ENTER., and then press are If you ce.PatientManagementServiceImple Implement Interface

New Service Endpoint Service New ContosoServicesSelfHostExtConfig PatientManagementServiceImageContract method and modify the code as shown in the the in shown code as modify the method and , and then click and then , , and then click , and then Edit WCF click Edit , and then Configuration folder,and then expand the Services Services node. Endpoints GetXrayImage app.config MemoryStream memoryStream = GetImageAsStream(type); Implement Interface Implement return memoryStream.ToArray(); } Return memoryStream.ToArray() End Function [Visual C#] public byte[]GetXrayImage(string patientId,string type) { [Visual Basic] Public Function GetXrayImage(ByValpatientId As String, _ ByVal type As String) As Byte() Implements _ PatientManagementServiceImageContract.GetXrayImage Dim memoryStream As MemoryStream = GetImageAsStream(type) [Visual C#] // TODO 6 public classPatientManagementServiceImplementation : PatientManagementServiceContract PatientManagementServiceImageContract mentation com.contoso.PatientManagementServi right-click following code. to using Visual C#, right-click using Visual C#, right-click PatientManagementServiceImageContract 2. Expand the the Expand 2. 9. Locate the the Locate 9. 1. 1. the expand Explorer, In Solution Task 2: Add an endpoint for the contract that uses MTOM encoding 8. you are using Visual Basic, click after If

3. Right-click

f L7-138 Module 7: Improving WCF Service Quality MCT USE ONLY. STUDENT USE PROHIBITED

139 - menu, click New Binding Binding New , and then click , and then , click and then File Lab: Improving Service Quality L7 , and then click then , and wsHttpBinding window.

window, on the the window, on property to . Solution 'Connected WCF' 'Connected Solution

click box, dialog

ure the binding as follows: ure the binding as Mtom .

. PatientManagementServiceImages wsHttpBinding BindingConfiguration PMIService_WS WebServiceMtomBindingConfig WCF Service Configuration Editor Configuration Service WCF WCF Service Configuration Editor Configuration WCF Service Create a New Binding a New Create . Name: Address: Binding: MessageEncoding: MessageEncoding: Name: Contract: com.contoso.PatientManagementService.PatientManagementServiceIm ageContract .

follows: • Rebuild Solution Rebuild Save • WebServiceMtomBindingConfig • • pane, set the pane, set OK • Configuration • 4. as endpoint the side, configure right the pane on Endpoint In the Service 10. Close the the Close 10. 11. 11. right-click Explorer, In Solution 9. In the In 9. 8. right the pane, click the PMIService_WS In In the Configuration endpoint. 7. 7. In pane, the right config 6. In the In 6. 5. Bindings right-click pane, the Configuration In

MCT USE ONLY. STUDENT USE PROHIBITED , method, and , and then , and , and then click . .exe . project, expand the the project, expand console window, and then and then window, console Unblock . Allow project, right-click the the right-click project, . ConnectedWCF\ContosoServicesSel ConnectedWCF\ContosoServicesSel PatientManagementServiceReference GetImageStreamFromBytes View Code ConsultantClient . . . Accessories to , point Programs

dialog box, click dialog box, All ConsultantClient . . folder, right-click comment in the in the comment ContosoServicesSelfHostExtConfig file, and then click Update Service Reference Service Update ContosoServicesSelfHostExtConfig menu, point to menu, TODO 7 TODO Start User Account Control dialog click box, User Account Security Alert Windows Windows Explorer Windows If you are using Visual C#, go to to Visual C#, go If you are using E:\Labfiles\Starter\CS\BulkData\ a throws that code line of existing Remove the NotImplementedException If you are using Visual Basic, go to Visual Basic, go If you are using E:\Labfiles\Starter\VB\BulkData\ fHostExtConfig\bin\Debug fHostExtConfig\bin\Debug

click • Right-click the file Run as Administrator to the code: then make the following changes • • ConsultantForm Service References and then click application. host service the to close ENTER press 4. In the In 4. Task 3: Add code to the client callto the new operation the On 1. the In 3. 2. location: following to the move Explorer, In Windows 5. 2008. Switch to Visual Studio 6. the expand Explorer, In Solution 10. Locate the the Locate 10. 7. 7. Switch to the 8. 2008. Switch to Visual Studio 9. in the Explorer, In Solution

f L7-140 Module 7: Improving WCF Service Quality MCT USE ONLY. STUDENT USE PROHIBITED

141 - method. Add the Lab: Improving Service Quality L7

GetImage_Click comment in the in the comment

TODO 8 TODO PatientManagementServiceImageContract Add the following code to this method. code to this Add the following

following line of code to the method. following line of code to the [Visual C#] // TODO 8 imageStream.Close(); [Visual Basic] ' TODO 8 imageStream.Close() typeOfXray); return new MemoryStream(imageBytes); } { // TODO 7 patientManagementServiceImages = new PatientManagementServiceImageContractClient(); byte[] imageBytes = patientManagementServiceImages.GetXrayImage(PatientId.Text, Return New MemoryStream(imageBytes) End Function [Visual C#] private MemoryStream GetImageStreamFromBytes(string typeOfXray) ' TODO 7 Dim patientManagementServiceImages As _ PatientManagementServiceImageContract = New _ PatientManagementServiceImageContractClient() Dim imageBytes As Byte()= _ patientManagementServiceImages.GetXrayImage(PatientId.Text, _ typeOfXray) [Visual Basic] Private FunctionGetImageStreamFromBytes(ByVal typeOfXray As String) _ As MemoryStream • 11. Locate the the Locate 11.

MCT USE ONLY. STUDENT USE PROHIBITED

, . to tab. tab. app.config tab. On the On the tab. . Microsoft Microsoft . . Service Trace Viewer Trace Service , point to Add folder, click the file Unblock property to 12000000 (12 ReaderQuotasProperties and verify that it is already set already and verify that it is folder, and then click then folder, and project, right-click right-click project, window. Patient Information Patient Patient Information Patient wsHttpBinding : PMIService_WS : PMIService_WS wsHttpBinding . All Programs All menu, click Bindings folder, and then click and then Endpoints folder, . , and then click then , and Get Image click Get , and then File . In the . In the E:\LabFiles\logs Open. Tools message box, click click message box, Chest MessageEncoding . ConsultantClient . Stop Debugging . Start Debugging window, click the click window, Save MaxReceivedMessageSize under MaxArrayLength under menu, point to to point menu, , point to , point PMIService_WS tab, click click tab, folder, expand the , and then click and verify that this endpoint already has a binding verify that this endpoint already and Edit WCF Configuration Edit WCF menu, click menu, menu, click menu, . dialog box, go to the the to go box, dialog Client menu, click menu, WCF Service Configuration Editor Configuration Service WCF Windows Start Windows Debug Debug File Open Windows Security Alert Windows Consultant Client to Mtom of the value Set the Examine the value of the the value of Examine the million). of the value Set the 12000000 (12 million).

PMIService_WS (wsHttpBinding) • pane, do the following: pane, do the following: • • messages.svclog configuration named configuration named PMIService_WS and then click and then Windows SDK v6.0A SDK Windows Verify that an X-ray image is displayed on the X-ray Verify that an Patient Information Patient 3. In the In 3. 3. 3. the expand pane, In the Configuration 2. on the Trace Viewer, the Service In 2. Expand the the Expand 2. Task 5: View the raw MTOM messages the On 1. Task 4: Configure and run the client 1. in the Explorer, In Solution

9. On the the On 9. 6. On the the On 6. 4. On the the On 4. the Close 5. 7. In the In 7. 8. In the In 8.

f f L7-142 Module 7: Improving WCF Service Quality MCT USE ONLY. STUDENT USE PROHIBITED

143 - View Content-Type tab to display a tab to display project, right- project, file, and then click then click file, and Message . Lab: Improving Service Quality L7 element. This is because the because This is element. . This confirms that it is using . This confirms that it is e following WCF operation. WCF operation. e following element contains a element , scrolling down the list if necessary. , scrolling down the tab, and then examine the SOAP tab, and then examine the HTTP listed twice. This is because the ementSystem/2007/10/PatientManagem ementSystem/2007/10/PatientManagem Message Message PatientManagementService WebHeaders GetXrayImageResult comment, and then add th add and then comment, TODO 5 TODO PatientManagementServiceImageContract PatientManagementServiceImageContract . You will see each message and response element contains an empty element contains MIME part. separate is in a content message. Scroll down to find the SOAP body and verify that its verify and body SOAP the find down to message. Scroll element that in turn contains a string that starts with that element that in turn contains a string multipart/related;type="application/xop+xml" request header. Verify that the the that Verify header. request encoding. MTOM http://contoso.com/ClinicManag Function StreamXrayImage(ByVal patientId As String, ByVal type As _ String) As Stream [Visual Basic] ' TODO 5 _ entServiceImageContract/GetXrayImageResponse entServiceImageContract/GetXrayImage click the list of messages passed between the client and the service. This tab lists the This tab lists service. the and client the passed between list of messages order. in time them and sorts values Action by their messages http://contoso.com/ClinicManag Code Note: at the message level and the log each message to service has been configured transport level. 7. of Click a message with an action 8. 8. click the pane, In the lower-right Task 6: Add a streamed method to the contract 1. the under Explorer, In Solution 6. 6. the click pane, In the lower-right 5. of Click a message with an action 4. the click left pane, in the Viewer, Trace In the Service 2. Locate the the Locate 2.

f

MCT USE ONLY. STUDENT USE PROHIBITED

, point , point . project, right- project, file, and then click click then and file, Implement Interface PatientManagementService method, and then make the following changes method, and then make the following PatientManagementServiceImageContract , and then click and then , comment and add the following statement. following statement. the and add comment comment. If you are using Visual Basic, click after using Visual are If you comment.

. StreamXrayImage TODO 9 TODO TODO 6 TODO PatientManagementServiceImplementation PatientManagementServiceImplementation string imagePath = @"..\..\DataFiles\xray_" + type + ".bmp"; Dim imagePath As String = "..\..\DataFiles\xray_" & type & Implement Interface Implement { return File.OpenRead(imagePath); } ".bmp" Return File.OpenRead(imagePath) End Function [Visual C#] public StreamStreamXrayImage(string patientId, string type) [Visual Basic] Public Function StreamXrayImage(ByValpatientId String, As _ ByVal type As String) As System.IO.Stream Implements _ PatientManagementServiceImageContract.StreamXrayImage [Visual C#] // TODO 9 using System.IO; [Visual Basic] ' TODO 9 Imports System.IO [Visual C#] // TODO 5 [OperationContract] Stream StreamXrayImage(string patientId, string type); to the code. code. to the click the to , and then press ENTER., and then press If you are PatientManagementServiceImageContract using Visual C#, right-click View Code 6. Locate the the Locate 6. 4. 4. the under Explorer, In Solution 3. Locate the the Locate 3.

5. Locate the the Locate 5. L7-144 Module 7: Improving WCF Service Quality MCT USE ONLY. STUDENT USE PROHIBITED

145 - project, project, . In the . menu, click New Binding Binding New , and then click , and then , click and then File endpoint. In theright Lab: Improving Service Quality L7 , and then click then , and netTcpBinding window.

window, on the the window, on New Service Endpoint Service New ce.PatientManagementServiceImple . NetTcpStreamingBindingConfig de, configure the endpoint as follows: configure the endpoint as follows: de, to ContosoServicesSelfHostExtConfig Solution 'Connected WCF' 'Connected Solution

click dialog box,

ure the binding as follows: ure the binding as , and then click the click the , and then Edit WCF click Edit Configuration , and then folder,and then expand the Streamed .

. PatientManagementServiceImages netTcpBinding BindingConfiguration Services Services node. PMIService_TCP NetTcpStreamingBindingConfig Endpoints app.config WCF Service Configuration Editor Configuration Service WCF WCF Service Configuration Editor Configuration WCF Service Create a New Binding a New Create . Name: Address: Binding: Name: TransferMode: Contract: com.contoso.PatientManagementService.PatientManagementServiceIm ageContract .

• Service Endpoint pane on the right si right pane on the Endpoint Service right-click right-click mentation • com.contoso.PatientManagementServi • Rebuild Solution Rebuild Save OK • • Configuration • pane, set the pane, set 2. Expand the the Expand 2. Task7:Changethe service-side endpoint to support streaming 1. the expand Explorer, In Solution

3. Right-click 9. Close the the Close 9. 10. 10. right-click Explorer, In Solution 6. 6. In pane, the right config 8. In the In 8. 7. pane, click the PMIService_TCP In the Configuration 5. In the In 5. 4. Bindings pane, right-click In the Configuration

f

MCT USE ONLY. STUDENT USE PROHIBITED , Run as , and click . method, and then method, and then .exe . . . project, expand the the project, expand console window, and then and then window, console Unblock . Allow project, right-click the the right-click project, . GetImageStream PatientManagementServiceReference View Code ConsultantClient dialog box, click dialog box, ConsultantClient comment in the in the comment folder, right-click ContosoServicesSelfHostExtConfig file, and then click .

Update Service Reference Service Update ContosoServicesSelfHostExtConfig TODO 10 TODO User Account Control dialog click box, User Account Security Alert Windows If you are using Visual C#, go to to Visual C#, go If you are using E:\Labfiles\Starter\CS\BulkData\ConnectedWCF\ ContosoServicesSelfHostExtConfig\bin\Debug If you are using Visual Basic, go to Visual Basic, go If you are using E:\Labfiles\Starter\VB\BulkData\ConnectedWCF\ ContosoServicesSelfHostExtConfig\bin\Debug

End Function ' TODO 10 Dim patientManagementServiceImages As _ PatientManagementServiceImageContract = _ New PatientManagementServiceImageContractClient("PMIService_TCP") Return _ patientManagementServiceImages. _ StreamXrayImage(PatientId.Text, typeOfXray) [Visual Basic] Private Function GetImageStream(ByVal typeOfXrayAs String) As Stream • Right-click the file Administrator • modify the method as shown in the following code. following in the as shown method modify the ConsultantForm Service References and then click host. service the to close ENTER press Task 8: Change the client code to call the new operation 1. Explorer. Windows Switch to 2. location: the following to go Explorer, In Windows

4. In the In 4. 3. In the In 3. 5. 5. the expand Explorer, In Solution the Locate 8. 6. 6. the to Return 7. 7. in the Explorer, In Solution

f L7-146 Module 7: Improving WCF Service Quality MCT USE ONLY. STUDENT USE PROHIBITED

147 - . . property to 12000000 (12 project, project, right-click Lab: Improving Service Quality L7 folder, and then click then folder, and and verify that it is already set to verify that it and GetImageStream folder, and then click Client then folder, and Bindings . In the netTcpBinding : PMIService_TCP ConsultantClient TransferMode with a call to Edit WCF Configuration MaxReceivedMessageSize folder under the comment, and then replace the call to replace the and then comment, . . Endpoints , and then click then , and TODO 11 TODO Examine the value of the value of the Examine the Streamed of the value Set the million). PatientManagementServiceImageContract

[Visual C#] // TODO 11 Stream imageStreamGetImageStream(typeOfXray); = [Visual Basic] ' TODO 11 Dim imageStream As Stream= GetImageStream(typeOfXray) new PatientManagementServiceImageContractClient("PMIService_TCP"); return patientManagementServiceImages. StreamXrayImage(PatientId.Text, typeOfXray); } [Visual C#] private Stream GetImageStream (string typeOfXray) { // TODO 10 patientManagementServiceImages = app.config PMIService_TCP (netTcpBinding) PMIService_TCP • GetImageStreamFromBytes pane, do the following: • 2. Expand the the Expand 2. Task 9: Configure and run the client 1. the under Explorer, In Solution 9. Locate the the Locate 9.

3. 3. the expand pane, In the Configuration

f

MCT USE ONLY. STUDENT USE PROHIBITED

tab. tab. tab. On the On the tab. . menu, click menu, click tab to display a tab to display File , scrolling down the Message . Open folder, click the file Patient Information Patient window. window. Patient Information Patient window, on the on window, listed twice. This is because the menu, click Get Image click Get , and then . File ementSystem/2007/10/PatientManagem E:\LabFiles\logs Open. Chest . Stop Debugging . Start Debugging window, click the window, tab, click click tab, , and then click menu, click menu, menu, click menu, Service Trace Viewer Service Trace dialog box, go to the the to go box, dialog WCF Service Configuration Editor Configuration Service WCF Debug Debug Open Consultant Client Consultant Client WCF Service Configuration Editor Configuration WCF Service . You will see each message and response You should see an X-ray image displayed on the X-ray image displayed You should see an Patient Information Patient Save entServiceImageContract/StreamXrayImageResponse list if necessary. messages.svclog This tab lists the service. and the client the passed between list of messages order. them in time values and sorts Action messages by their http://contoso.com/ClinicManag Note: level and the log each message at the message service has been configured to transport level. 8. On the the On 8. 5. Close the the Close 5. 6. On the the On 6. 7. In the In 7. Task 10: View the raw streamed messages 1. Switch to the 2. 2. on the Trace Viewer, In the Service 5. of Click a message with an action the In 4. the In 3. 4. click the in the left pane, Trace Viewer, In the Service

f L7-148 Module 7: Improving WCF Service Quality MCT USE ONLY. STUDENT USE PROHIBITED

149 - Lab: Improving Service Quality L7 tab,and then examine the SOAP Message

. …stream… After completing this exercise, you have seen how to pass bulk binary data data bulk binary to pass how you have seen exercise, After completing this element contains element contains message. Scroll down to find the SOAP body and verify that its verify and body SOAP the find to down Scroll message. Results: and service. between a WCF client 6. click the pane, In the lower-right

MCT USE ONLY. STUDENT USE PROHIBITED

151 - Lab: Protecting a Service a Service Protecting Lab: L8

6461A-LON-DEV-08 Student Virtual Machine: Virtual Machine: User Name: Password: Pa$$w0rd Password:

• Estimated time: 40 minutes Module 8: Implementing WCF Security Security WCF 8: Implementing Module a Service Protecting Lab: Logon Information: • •

MCT USE ONLY. STUDENT USE PROHIBITED

. Run as 6461- Visual

. Pa$$w0rd Student Microsoft You will then ensure You will then ensure . de by the clinic 2008, and then click , point to

Continue Studio

using the password using the linic network. You need to be sure that sure be to need You linic network. Programs

s of message-level encryption on the the on encryption of message-level s ers to access sensitive patient data, and patient sensitive to access ers All Visual ypt message contents.

Student om the client to the service. to the client om the rity for Internal Network Internal Network rity for as virtual machine and log on as on and log virtual machine , point to Start . 6461-LON-DEV-08 6461-LON-DEV-08 2008, right-click Microsoft

User Account Control dialog click box, User Account message contents. message contents. LON-DEV-08. administrator Studio 5. 5. in the service. Display caller credentials 6. fr credentials Windows Provide that only authorized users can access patient data. can users that only authorized exercise are as follows: for this The main tasks the Start 1. 2. to a service. encryption Apply message-level 3. to a client. encryption Apply message-level 4. effect the see to Use message logging Task 2: Apply message-level encryption to a service 1. taskbar, click On the Task 1: Start the 6461-LON-DEV-08 virtual machine and log on as Student 1. double-click Client, and then Control Server Remote Virtual Open the to on Log 2. administration client application. This requires you to apply message-level security to apply message-level you application. This requires administration client to sign and encr to a message exchange the system then passes that data across the c the data across passes that then the system at encrypted this data is data and that patient the can access only authorized users all times when in transit. ma will start to secure the connections In this exercise, you Exercise 1: Applying Secu Applying 1: Exercise Scenario us clinic management system allows The Communication 2. In the In 2.

f f L8-152 Module 8: Implementing WCF Security MCT USE ONLY. STUDENT USE PROHIBITED

153 - , Name project, project, Open Open binding . folder, and . file (for , and then then , and , and then then , and Bindings Lab: Protecting a Service a Service Protecting Lab: L8 App.config . netTcpBinding Project/Solution Windows. binding. . Leave the . Leave Basic128 generates a binding configuration with generates a binding configuration with . . Under MessageSecurityProperties . Under Basic® development system, in the in the system, Basic® development all messages will be encrypted by a 128- . . t it provides sufficient privacy for messagest it provides sufficient privacy for t Windows® operating system user name ContosoServicesSelfHostExtConfig ernalNetwork\ConnectedWCF ernalNetwork\ConnectedWCF dialog box, select the the select box, dialog ation Editor, right-click the , and then click Open, and then property property to NetTcpBinding Edit WCF Configuration WCF Edit NetTcpSecureMessageBindingConfig file (for Visual Basic) or the or the file (for Visual Basic) . OK tab. dialog box, go to the folder the folder to go dialog box, property to Message ConnectedWCF.sln ConnectedWCF.sln app.config Mode dialog box, go to the folder folder the to go box, dialog AlgorithmSuite menu, point to New Binding Configuration Binding New Security File Create a New Binding a New Create double-click double-click If you are using Microsoft® Visual Microsoft® using If you are Open Project E:\Labfiles\Starter\VB\Int double-click double-click Project E:\Labfiles\Starter\CS\Int If you are using Microsoft Visual C#® development tool, in the tool, Visual C#® development Microsoft If you are using These settings the binding to apply cause message-level security so that the

property of the binding to binding of the property change the to property set MessageClientCredentialType type, and then click click type, and then Editor Service Configuration The WCF the for default settings the • then click • right-click the right-click the Visual C#), and then click inside an organization. Note: Users will signed as defined by WS-Security. message contents will be encrypted and a valid Microsof provide be expected to and password for the credentials, and then which is relativelybit algorithm, quick, bu 9. Click the 9. Click the Change 10. 8. 8. the change Editor, Configuration Service WCF pane of the right In the 4. 4. Do one of following: the the On 3. 6. 6. Configur Service In the WCF 7. In the In 7. 5. 5. the expand Explorer, In Solution

MCT USE ONLY. STUDENT USE PROHIBITED

, tab.

Services folder, and , click and then . APService_TCP Bindings project, right-click the right-click project, Create Appointment file (for Visual C#), and Unblock property to property Windows.

. Leave the . Leave Basic128 App.config . Under MessageSecurityProperties . Under . form, click the form, . ClinicAdminClient Solution 'Connected WCF' 'Connected Solution dialog box, click dialog box, folder, and then click the folder, and binding configuration. configuration. binding rvice Configuration Editor, in the rvice Configuration . . . . l encryption to a client to a l encryption property property to Start Debugging. Start Debugging. BindingConfiguration Save Exit Save Exit Endpoints tab. property to Message . Ensure that the solution builds successfully before successfully builds that the solution Ensure . , and then make sure that a list of available slots displays. , and then make sure that a list of available slots menu, click menu, APService_TCP Mode menu, click menu, click menu, menu, click menu, click menu, AlgorithmSuite file (for Visual Basic) or the or the file (for Visual Basic) Edit WCF Configuration WCF Edit Security Debug Clinic Administration Client Administration Clinic File File File File Windows Security Alert Windows Find Slots folder, expand the folder, expand pointmentServiceImplementation com.contoso.AppointmentService.Ap the expand service, endpoint. endpoint. app.config NetTcpSecureMessageBindingConfig then click then click the then click the change the change the to property set MessageClientCredentialType Rebuild Solution Rebuild continuing. Task 4: Use message logging to see the effects of message-level encryption on the message contents the On 1. 12. 12. the pane, set right In the 2. In the In 2. Task 3: Apply message-leve 1. the expand Explorer, In Solution 11. Se WCF the pane of the left In 2. the expand Editor, Configuration Service In the WCF 4. Click 3. On the the On 3. 14. On the the On 14. 13. On the the On 13. 3. Click the 3. Click the Change 4. 6. On the the On 6. 7. right-click Explorer, In Solution 5. On the the On 5.

f f L8-154 Module 8: Implementing WCF Security MCT USE ONLY. STUDENT USE PROHIBITED

155 - . tab to display a to display tab Microsoft Microsoft , scrolling down the , scrolling down the . In the lower-right . . Lab: Protecting a Service a Service Protecting Lab: L8 Message Service Trace Viewer Trace Service Add Exit folder, click the file folder, click the file , point to tab, and then examine the SOAP listed twice. This is because the ort-level to the message-level. Scroll ort-level to the message-level. menu, click menu, click entSystem/2007/10/AppointmentServ entSystem/2007/10/AppointmentServ , and then click then , and en verify that it contains an verify en All Programs File File E:\LabFiles\logs Message Open. Tools . Stop Debugging , point to eAppointmentTimesResponse eAppointmentTimesResponse values and sorts them in time order. in time them and sorts values , point to , point Start Action element. element. , and then click menu, click menu, dialog box, go to the the to go box, dialog Debug Open You will see each message and response message that was passed from the transp was message that and th body, SOAP the to find down messages.svclog This tab lists the service. and the client the passed between list of messages messages by their http://contoso.com/ClinicManagem iceContract/ListAvailabl iceContract/ListAvailabl list if necessary. it verify that then body, and message SOAP pane, scroll down again to the times. of available appointment list contains an unencrypted http://contoso.com/ClinicManagem Windows SDK v6.0A SDK Windows Note: level and the log each message at the message service has been configured to transport level. 7. 7. on the Trace Viewer, In the Service 8. In the In 8. 10. 10. of with an action message recent Click the most 9. 9. click the in the left pane, Trace Viewer, In the Service 13. 13. on the Trace Viewer, In the Service 11. 11. click the pane, In the lower-right 12. of pane, click the penultimate message with an action In the left the On 5. 6. 6. click taskbar, On the

MCT USE ONLY. STUDENT USE PROHIBITED

. class View Code project, right-click the right-click project, class file, and then click class file, AppointmentServiceImplementation AppointmentService method shown in the following code example. This code example. in the following method shown comment, and then add the add the and then comment, edentials in the service TODO 1 method writes a message to the console to show the identity under which the the which under identity the to show the console a message to method writes operation is running. ShowSecurityInformation file, locate the ServiceSecurityContext.Current.WindowsIdentity.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, [Visual C#] // TODO 1 private static void ShowSecurityInformation(string methodName) { Console.WriteLine("{0} thread principal is {1}", methodName, Thread.CurrentPrincipal.Identity.Name); ServiceSecurityContext.Current.PrimaryIdentity.Name) Console.WriteLine("{0} security context windows identity is " _ & "{1}", methodName, _ ServiceSecurityContext.Current.WindowsIdentity.Name) End Sub ... ' TODO 1. Private Shared Sub ShowSecurityInformation(ByVal methodName As String) Console.WriteLine("{0} thread principal is {1}",methodName, _ Thread.CurrentPrincipal.Identity.Name) Console.WriteLine("{0} security context primary identity is " _ & "{1}", methodName, _ [Visual Basic] ... AppointmentServiceImplementation Task 5: Display callerTask 5: Display cr 1. the expand Explorer, In Solution 2. for the window Editor In the Code

f L8-156 Module 8: Implementing WCF Security MCT USE ONLY. STUDENT USE PROHIBITED

157 - tab.

. . . class file, locate the Lab: Protecting a Service a Service Protecting Lab: L8 project, right-click the right-click project, Create Appointment as the parameter. parameter. as the Stop Debugging ShowSecurityInformation

View Code primary identity, and the Windows and the Windows primary identity, method, and then change the type the change then and method, form, click the form, s from the client to the service ListAvailableAppointmentTimes ClinicAdminForm ClinicAdminClient rity information displayed shows LON- rity information ContosoServicesSelfHostExtConfig Start Debugging. Start Debugging. findSlots_Click AppointmentServiceContractClient comment in the in the comment class file, and then click then class file, and .

menu, click menu, for the thread principal, the variable to TODO 2 TODO comment in the in the comment Clinic Administration Client Administration Clinic Debug proxy Find Slots of the of the TODO 3 method, and then add a statement to call the call the to add a statement then method, and method, passing "ListAvailableAppointmentTimes" method, passing [Visual Basic] ' TODO 3. Dim proxyAppointmentServiceContractClient()New As ShowSecurityInformation("ListAvailableAppointmentTimes"); ' TODO 2. ShowSecurityInformation("ListAvailableAppointmentTimes") ... [Visual C#] // TODO 2 [Visual Basic] ... application, verify that the secu request. identity of the ClinicAdminForm DEV\Student 6. Click 8. In Visual Studio 2008, menu, click on Debug the Task 6: Provide Windows credential 1. the expand Explorer, In Solution 5. On the the On 5. 2. for the window Editor In the Code 4. On the the On 4. the Locate 3. 7. 7. the window for console In the

f

MCT USE ONLY. STUDENT USE PROHIBITED

tab.

. Create Appointment Stop Debugging

credentials. Verify that it contains that it contains Verify credentials. SecurityNegotiationException ice. In this case, this uses an this case, this ice. In form, click the form, Start Debugging. Start Debugging. comment, and then add code to explicitly set the explicitly code to add and then comment, , and then examine the menu, click menu, TODO 4 TODO Debug Client Administration Clinic Find Slots credentials used when calling the serv credentials used when intentionally fake user name to prove that authentication must take place take place must authentication that prove to name intentionally fake user correctly. // TODO 4 proxy.ClientCredentials.Windows.ClientCredential.UserName= "Fred"; proxy.ClientCredentials.Windows.ClientCredential.Password= "Secret"; proxy.ClientCredentials.Windows.ClientCredential.Domain = "TestDomain"; proxy.ClientCredentials.Windows.ClientCredential.UserName = "Fred" proxy.ClientCredentials.Windows.ClientCredential.Password = "Secret" proxy.ClientCredentials.Windows.ClientCredential.Domain = "TestDomain" [Visual C#] [Visual Basic] ' TODO 4. [Visual C#] // TODO 3 AppointmentServiceContractClient proxy = new AppointmentServiceContractClient(); exception that occurs because of the invalid of the because occurs that exception service." by the authenticated caller was not "The the message 7. In Visual Studio 2008, menu, click on Debug the 6. Click 4. On the the On 4. 5. On the the On 5. 3. Locate the the Locate 3.

L8-158 Module 8: Implementing WCF Security MCT USE ONLY. STUDENT USE PROHIBITED

159 - tab.

. class file, locate the class file, Lab: Protecting a Service a Service Protecting Lab: L8 Create Appointment Stop Debugging

form, click the form, ClinicAdminForm rity information displayed shows LON- rity information ContosoServicesSelfHostExtConfig menu, click Debug Start Debugging. Start Debugging. for the thread principal, the primary identity, and the the primary identity, and the principal, thread for the .

menu, click menu, comment, and then change the values for the Windows credentials to to Windows credentials values for the the change and then comment, Debug Client Administration Clinic Find Slots After completing this exercise, you have seen how to secure message TODO 4 when correctly works the authentication that to prove valid credentials programmatically. credentials specifying "Pa$$w0rd"; proxy.ClientCredentials.Windows.ClientCredential.Domain = "LON- DEV"; [Visual C#] // TODO 4 proxy.ClientCredentials.Windows.ClientCredential.UserName = "LocalAdmin"; proxy.ClientCredentials.Windows.ClientCredential.Password= ' TODO 4. proxy.ClientCredentials.Windows.ClientCredential.UserName = _ "LocalAdmin" proxy.ClientCredentials.Windows.ClientCredential.Password = "Pa$$w0rd" proxy.ClientCredentials.Windows.ClientCredential.Domain = "LON-DEV" [Visual Basic] application, verify that the secu DEV\LocalAdmin Windows identity of the request. request. of the Windows identity contents using message-level security and how to pass Windows credentials from a to pass contents using message-level how security and client to a service. Results: 11. Click 11. 9. On the the On 9. the On 10. 13. 13. on the 2008, In Visual Studio 8. the for window Editor In the Code 14. 14. 2008. Close Visual Studio 12. 12. the window for console In the

MCT USE ONLY. STUDENT USE PROHIBITED

Visual

flag to /? Internet Internet Visual

Microsoft . . created the certificate certificate the created the family practitioner the family practitioner , run it with the , point to . administrator Run as Continue Continue makecert , right-click Microsoft , and then double-click , and then family practitioner administrators to to administrators family practitioner makecert stem encrypts the data when in transit in transit data when the stem encrypts Programs

to be sure that only authorized users users authorized only that sure be to . All , and then click , click System and Control Panel dow, type the following command: , point to , click an SSL certificate on IIS an SSL certificateon You will only then ensure that authorized users can Visual Studio Tools pointment service. This requires you to apply transport- to apply you This requires service. pointment Start Start any problems with Administrative Tools Administrative , click 2008 Command Prompt , point to 2008, point to

User Account Control dialog click box, User Account User Account Control dialog click box, User Account Maintenance Manager Services (IIS) Information HTTPS-Key if "Succeeded" message the see You should correctly. If you have makecert -sr LocalMachine -ss My -n CN=LON-DEV -sky exchange -sk Studio see its options. see its options. Studio 3. 3. win prompt command In the 2. In the In 2. 5. In the In 5. level security to a message exchange that encrypts the entire communication, communication, entire the that encrypts exchange a message to level security headers. including message data. access patient exercise are as follows: for this The main tasks 1. SSL certificate on IIS. an Create and install 2. service. your site to host Web Create an IIS-based 3. site. IIS-based Web functionality to your service Add the 4. service. Call the SSL-protected across the Internet. Internet. across the by the connections made will secure In this exercise, you the ap client application to Task 1: Create and install 1. taskbar, click On the make appointments for patients. You need need for patients. You make appointments sy the that and appointments can make such for Internet Communication Communication for Internet Security Applying 2: Exercise Scenario allows remote management system clinic The

4. 4. taskbar, click On the

f L8-160 Module 8: Implementing WCF Security MCT USE ONLY. STUDENT USE PROHIBITED

161 - as , and , and Run as Visual

Add , and then , and then . . . In the right the In . , and then , and then , and then , and then . template. Set the Set the template. Microsoft , point to , point , set the SSL SSL the , set Local IIS . Lab: Protecting a Service a Service Protecting Lab: L8 dialog box, go to the the to go box, dialog , in the left pane, expand expand left pane, the , in dialog box, go to the the to go dialog box, Default Web Site Default to Basic Visual to https 2008, and then click , point to

Project/Solution . to Visual C# Create New Virtual WCF Service WCF ContosoInternetGateway . Continue Type Close Add . Studio

Language Open Project dialog box, click box, dialog Programs , right-click , right-click OK

Language Open Project . . All Visual

Solution 'ConnectedWCF' Solution enter dialog box, dialog box, set box, dialog Web Sites , and then click the , and then Open, and then click , point to dialog box, select the the select box, dialog dialog box, click click box, dialog dialog box, click click box, dialog . , and then click , and Choose Location Choose Start . and specify the language as follows: and specify t Web Site ConnectedWCF.sln ConnectedWCF.sln

node, expand node, expand LON-DEV HTTP menu, point to Defaul \Internet\ConnectedWCF E:\Labfiles\Starter\VB Internet\ConnectedWCF E:\Labfiles\Starter\CS\ icon in the upper-right corner of the dialog box. of the corner upper-right icon in the New Web Site Web New to name. name. File 2008, right-click Microsoft

Add Web Site Binding Add New Web Site New Virtual Directory Virtual New Web Site Bindings Internet Information Services (IIS) Manager (IIS) Services Information Internet Web Site Bindings Web Site Control dialog click box, User Account Browse. Edit Bindings If you are using Visual Basic, in the Visual Basic, in the If you are using double-click double-click folder Visual C#, in the If you are using folder double-click double-click Basic, set the Visual If you are using Visual C#, set the If you are using Alias LON-DEV

the Directory Directory certificate to the • click administrator Studio • • Location • then click pane, click 9. In the In 9. 9. In the In 9. 1. 1. taskbar, click On the Task 2: Create an IIS-based Web site to host your service the In 6. 4. 4. Do one of following: the 3. On the the On 3. 7. In the In 7. the In 2. 8. In the In 8. 5. 5. right-click Explorer, In Solution 6. In the In 6. 7. Click 8. 8. pane of the In the left

f

MCT USE ONLY. STUDENT USE PROHIBITED

, folder. Back . , expand , expand node...... In the right pane, pane, right . In the . Web Sites . , and then click OK , and then . , and then press ENTER. press , and then SSL Settings OK E:\Labfiles\Starter\CS\ E:\Labfiles\Starter\CS\ ContosoInternetGateway , but leave all the other properties properties all the other , but leave Select Folder Authentication node, expand node, expand Features View Features ContosoInternetGateway (IIS) Manager navigation bar, click bar, Manager navigation (IIS) box. Require SSL Require . You should see the message "The changes have have "The changes message the see . You should LON-DEV dialog box, verify that the address for the new Web new the for address verify that the box, dialog dialog box, click click box, dialog dialog box, do one of the following: following: of the one do box, dialog Folder dialog box, click the the click dialog box, ContosoInternetGateway Apply pane, click Basic Authentication icon in the toolbar. toolbar. the in icon Open. , and then click the , and then Internet Information Services (IIS) Manager (IIS) Services Information Internet . check box at the bottom of the dialog of the bottom box at the check Layer Sockets Secure Use New Folder New Authentication Browse For Folder For Browse Add New Web Site Browse For Folder For Browse dialog box, click click box, dialog Directory Virtual New Location Choose https://localhost/ContosoInternetGateway next to the Browse next to the Enable . Internet\ConnectedWCF If you are using Visual C#, go to the folder the folder to Visual C#, go If you are using If you are using Visual Basic, go to the folder the folder to go Visual Basic, using If you are \Internet\ConnectedWCF E:\Labfiles\Starter\VB

click and then in the main panel, double-click and then in the main panel, been successfully saved". been successfully at their default values. default values. at their Default Web Site Web Default Select the Select the click box, and then site is • • 26. 26. Manager. (IIS) Services Information Internet Close the 24. Information Services In the Internet 25. In the In 25. 21. 21. main panel, double-click of the In the IIS section 22. Settings pane, select In the SSL 23. 23. In the right pane, click 15. In the In 15. the In 16. 19. pane, expand the In the left 20. main pane, click of the bottom At the 18. 18. Switch to the 14. In the In 14. 17. In the In 17. Click 10. 12. Click the Click 12. 13. folder new Rename the 11. In the the In 11. L8-162 Module 8: Implementing WCF Security MCT USE ONLY. STUDENT USE PROHIBITED

163 - . , . . . In . Service.vb Service.cs. View Markup and Edit WCF , and then click Add , and then and Lab: Protecting a Service a Service Protecting Lab: L8 tab, click . In the right pane, set the IService.vb attribute, and then change the the change and then attribute, Web site. IService.cs AppointmentService.svc , and then click Service Projects as . file, and then click then click file, and folder under folder node. ppointmentServiceImplementation ppointmentServiceImplementation CodeBehind 2008.

web.config Service.svc Endpoints Studio

folder, and do one of the following: one of the following: folder, and do (Empty Name) dialog box, click the click the box, dialog folder, and then click folder, Visual

AppointmentService.svc . attribute to Service attribute Services App_Code https://localhost/ContosoInternetGateway/ . Microsoft Add Reference value to If you are using Visual Basic, delete the files If you are using Visual If you are using Visual C#, delete the files If you are using Visual

and then click the first click the first and then com.contoso.AppointmentService.A [Visual C#] <%@ ServiceHost Language="C#"Debug="true" Service="com.contoso.AppointmentService.AppointmentServiceImplement ation" %> [Visual Basic] <%@ ServiceHost Language="vb"Debug="true" Service="com.contoso.AppointmentService.AppointmentServiceImplement ation" %> Reference Configuration Name com.contoso.AppointmentService.A value of the value of the pointmentServiceImplementation com.contoso.AppointmentService.Ap the code view window, remove the the window, remove view the code , and then click OK then , and AppointmentService • https://localhost/ContosoInternetGateway/ • 8. 8. right-click Explorer, In Solution 10. 10. expand the pane, In the left Task 3: Add the service functionality to your IIS-based Web site to 1. Switch

6. 6. rename Explorer, In Solution 5. In the In 5. 9. Expand the the Expand 9. 2. 2. the expand Explorer, In Solution the Expand 3. 7. Right-click the the Right-click 7. 4. Right-click

f

MCT USE ONLY. STUDENT USE PROHIBITED

. In . In . . , and then . New Binding Binding New . Verify that you , click and then serviceMetadata Service Behaviors and the value true of and the value to node, change the binding to to binding change the node, property to property empty.Address dialog box, click click dialog box, Metadata_HTTPS endpoint. endpoint. . . , change the contract to . Under folder, and then click then and folder, ge "There is a problem with this "There is a problem ge folder, expand the the expand folder, to TransportClientCredentialType . Continue to this Website to Continue folder, and then click and then folder, tGateway/AppointmentService.svc . Leave the . Leave OK (Empty Name) Solution 'Connected WCF' 'Connected Solution AppointmentServiceImplementation property of the binding to to binding of the property Bindings . . Advanced APService_HTTPS . BindingConfiguration Name Exit Save basicHttpBinding Create a New Binding New a Create to ServiceBehavior , and then set the name to name set the then and , , and then click , and tab. property to Transport . Ensure that the solution builds successfully. successfully. builds that the solution Ensure . to false APService_HTTPS . In the . In the Binding Mode menu, click menu, menu, click menu, Security File File service test page for the test page service folder, expand the folder, expand , set the , set the TransportSecurityProperties None. BasicHttpSecureTransportBindingConfig the right pane, change the value of HttpsGetEnabled value the change pane, the right Configuration basicHttpBinding mexHttpsBinding BasicHttpSecureTransportBindingConfig HttpGetEnabled Solution Rebuild https://localhost/ContosoInterne Internet Explorer will display the messa Website's security certificate." Click certificate." Website's security see the com.contoso.AppointmentService.AppointmentServiceContract name to set the 19. 19. pane, expand the In the left 17. pane, click the In the left 18. 18. the pane, set right In the the Change 11. 13. pane, right-click the In the left 14. 14. the pane, set right In the the On 21. 22. right-click Explorer, In Solution 15. Click the Click 15. the Change 16. 20. On the the On 20. 23. URL the to then go and Explorer, Start Internet 24. 24. Explorer. Close Internet 12. the second pane, click left In the L8-164 Module 8: Implementing WCF Security MCT USE ONLY. STUDENT USE PROHIBITED

165 . - " _

. comment, Edit WCF TODO 5 folder, and then then and folder, View Code Lab: Protecting a Service a Service Protecting Lab: L8 project. project. Bindings , and then click . Under into the constructor. constructor. the into tGateway/AppointmentService.svc to TransportClientCredentialType method, locate the the locate method, tab. FPAdminClient "); app.config to pass the value value pass the to class file, and then click Security look like the following. like the following. look ation Editor, expand the . property to Transport FPAdminForm . BasicHttpBinding Mode GetAppointmentServiceProxy APService_HTTP https://localhost/ContosoInterne BasicHttpSecurityMode.Transport Configuration , set the TransportSecurityProperties, set the None. and then make the following changes: and then make the a. to of the endpoint address Change the URL Your code should now b. Alter the the b. Alter // TODO 5 EndpointAddress addressnew = EndpointAddress("https://localhost/ContosoInternetGateway/" + "AppointmentService.svc BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); EndpointAddress("https://localhost/ContosoInternetGateway/ & "AppointmentService.svc") Dim bindingNew As BasicHttpBinding(BasicHttpSecurityMode.Transport) [Visual C#] [Visual Basic] ' TODO 5 Dim addressNew _ As click 5. 5. right-click Explorer, In Solution Task 4: Call the SSL-protected service 1. 2008. Visual Studio Switch to 2. the expand Explorer, In Solution 6. Configur In the Service the In 4. 7. pane, click the right In the 8. Change the the Change 8. 3. Right-click the the Right-click 3.

f

MCT USE ONLY. STUDENT USE PROHIBITED

tab. , . . Verify that the .

Create Appointment class file, and then click class file, and then Stop Debugging Find Slots PermissiveCertificatePolicy "CN=LON-DEV" e message "Could not establish a trust a trust establish not message "Could e form, click form, click the form, channel with authority 'localhost'."channel with authority FPAdminForm comment, and then add the following the following add and then comment, menu, click Debug method on . . Start Without Debugging. Without Start . Start Debugging Save Exit Enact TODO 5 TODO . Verify that no exception occurs and that the list of possible of possible the list that and occurs no exception that . Verify menu, click menu, menu, click menu, menu, click menu, click menu, . Locate the the . Locate Debug File File Debug Clinic Administration Client Administration Clinic Clinic Administration Client Administration Clinic Find Slots After completing this exercise, you have seen how to After completing this exercise, you have secure message [Visual C#] // TODO 5 PermissiveCertificatePolicy.Enact("CN=LON-DEV"); [Visual Basic] ' TODO 5 PermissiveCertificatePolicy.Enact("CN=LON-DEV") passing the name used in the certificate: in the used passing the name statement that calls the statement that relationship for the SSL/TLS secure secure SSL/TLS the relationship for application throws an exception with th application throws appointment times appears. appointment times View Code Results: security. contents across the Internet using transport-level 15. On the the On 15. 10. On the the On 10. the On 11. the On 9. 13. 13. on the 2008, In Visual Studio 16. On the the On 16. Click 17. 18. Client form. Appointment FP Close the 12. On the the On 12. 14. 14. the right-click Explorer, In Solution L8-166 Module 8: Implementing WCF Security MCT USE ONLY. STUDENT USE PROHIBITED

167 - Lab: Implementing Transactions for a Service L9

6461A-LON-DEV-09 Student Virtual Machine: Virtual Machine: User Name: Password: Pa$$w0rd Password:

Estimated time: 40 minutes Logon Information: Logon Information: • Module 9: Implementing Transactions Transactions 9: Implementing Module Transactions Implementing Lab: for a Service • •

MCT USE ONLY. STUDENT USE PROHIBITED

. Run as 6461- Visual

. . Pa$$w0rd Student Microsoft ice to ensure that . 2008, and then click , point to

Project/Solution Continue Studio

using the password using the Programs

from client to serv from All e of appointment and e creation the the Visual

the appointment service contract. service appointment the Student ansaction rolls back the changes to the the to changes rolls back the ansaction as virtual machine and log on as on and log virtual machine Open, and then click , point to Start . menu, point to 6461-LON-DEV-09 6461-LON-DEV-09 File 2008, right-click Microsoft

User Account Control dialog click box, User Account

appointment service. appointment service. LON-DEV-09. administrator Studio appointments are not marked as taken unless subsequent processing succeeds. processing succeeds. subsequent as taken unless marked are not appointments exercise are as follows: for this The main tasks the Start 1. 2. Add transactional requirements to 3. transactions. to flow service Configure the 4. transactions. client to flow Configure the 5. client. Start a transaction from the 6 Ensure that failure in the client tr Task 2: Add transactional requirements to the appointmentservice contract 1. taskbar, click On the 1. 1. double-click Client, and then Control Server Remote Virtual Open the to on Log 2. Task 1: Start the 6461-LON-DEV-09 virtual machine and log on as Student Exercise 1: Control the Flow of a Transaction from Client to to Client from a Transaction of Flow the Control 1: Exercise Service Scenario requirement The System. Management Clinic Contoso for the developer You are a that th says appointment for making an together. performed be must appointment letter issuing of the will flow a transaction In this exercise, you 3. On the the On 3. 2. In the In 2.

f f L9-168 Module 9: Implementing Transactions MCT USE ONLY. STUDENT USE PROHIBITED

169 - . Open Open attribute to attribute class file, , and then then , and , and then then , and Code

View project. TransactionFlow , and then click , Lab: Implementing Transactions for a Service L9 Basic® development system, in the in the system, Basic® development . . . AppointmentServiceContract AppointmentService operation with a parameter of parameter operation with a comment, and then add the add and then comment, dialog box, go to the folder the folder to go box, dialog ConnectedWCF.sln ConnectedWCF.sln dialog box, go to the folder folder the to go box, dialog AppointmentServiceContract TODO 1 TODO If you are using Microsoft® Visual Microsoft® using If you are Open Project E:\Labfiles\Starter\VB\TransactionFlow\ConnectedWCF double-click double-click Project E:\Labfiles\Starter\CS\TransactionFlow\ConnectedWCF double-click If you are using Microsoft Visual C#® development tool, in the tool, Visual C#® development Microsoft If you are using CreateAppointment

... // TODO 1 [TransactionFlow(TransactionFlowOption.Mandatory)] ... [Visual Basic] ... ' TODO 1. _ ... [Visual C#] • • TransactionFlowOption.Mandatory the locate the locate the 4. following: Do one of the 5. 5. the expand Explorer, In Solution 6. Right-click 7. 7. for the window Editor In the Code

MCT USE ONLY. STUDENT USE PROHIBITED

class

, and dialog box, dialog box, project, right-click right-click project, OperationBehavior assembly, and then click and then assembly, Add Reference comment, and then import the the import and then comment, . In the . In the . TODO 3 TODO operation with a parameter of operation with a parameter AppointmentServiceImplementation AppointmentServiceImplementation AppointmentService set to true System.Transactions Add Reference comment, and then add the add the and then comment, namespace. . Code

CreateAppointment TODO 2 tab, click the tab, click the .NET . attribute to the TransactionsScopeRequired System.Transactions file, locate the usingSystem.Transactions; ... Imports System.Transactions ... [Visual C#] ... // TODO 3 [Visual Basic] ... ' TODO 3. [OperationBehavior(TransactionScopeRequired=true)] ... _ ... [Visual C#] ... // TODO 2 [Visual Basic] ... ' TODO 2. click the OK , and then click and then References, then click View then click 4. 4. locate the window, Editor In the Code 3. 3. the under Explorer, In Solution Task 3: Configure the service to flow transactions 1. right-click Explorer, In Solution

2. 2. for the window Editor In the Code

f L9-170 Module 9: Implementing Transactions MCT USE ONLY. STUDENT USE PROHIBITED

171 -

class. ShowTransactionalStatus Lab: Implementing Transactions for a Service L9 comment, and then add the the add then and comment, TODO 4 TODO method to the AppointmentServiceImplementation scope", methodName); } } ... Console.WriteLine("{0} called in transactional scope, " + "id is {1}", methodName, Transaction.Current.TransactionInformation.LocalIdentifier); } else { Console.WriteLine("{0} called outside oftransactional [Visual C#] ... // TODO 4 private static void ShowTransactionalStatus(string methodName) { if (Transaction.Current != null) { _ "scope", methodName) End If End Sub ... Private Shared Sub ShowTransactionalStatus(ByVal methodName As String) If Transaction.Current IsNot Nothing Then Console.WriteLine("{0} called in transactional scope, " & _ "id is {1}", methodName, _ Transaction.Current.TransactionInformation.LocalIdentifier) Else Console.WriteLine("{0} called outside of transactional " & [Visual Basic] ... ' TODO 4. the Locate 5.

MCT USE ONLY. STUDENT USE PROHIBITED

project, project, . in the in the category. category. , and then click , and then , and then click , and then True True nfiguration Editor, . . ShowTransactionalStatus property to property property to property (Configuration) (Configuration) netTcpBinding wsHttpBinding Edit WCF Configuration Edit WCF in the in in the in property property to property property to pane of the WCF Configuration Editor, Editor, Configuration WCF of the pane pane of the WCF Co WCF of the pane ContosoServicesSelfHostExtConfig WCF Configuration Editor, right-click Editor, Configuration WCF WCF Configuration Editor, right-click Editor, Configuration WCF TransactionFlow Name TransactionFlow Name dialog box, select select box, dialog click dialog box, file and then click click file and then method. CreateAppointment tab, set the the tab, set tab, set the the tab, set the tab, set tab, set the the tab, set comment, and then invoke the the invoke then and comment, app.config ) category. ) category. Binding Binding Binding Binding TODO 5 TODO New Binding Configuration Binding click New and then , New Binding Configuration Binding click New and then , Create a New Binding a New Create Create a New Binding a New Create General General NetTcpTransactionalBindingConfig ( WsHttpTransactionalBindingConfig ( . . Bindings b. On the the b. On do the following: the a. On the b. On OK OK do the following: the a. On Bindings ...... [Visual C#] ... // TODO 5 ShowTransactionalStatus("CreateAppointment"); [Visual Basic] ... ' TODO 5. ShowTransactionalStatus("CreateAppointment") right-click the right-click the method from inside the the inside from method 13. 13. NewBinding0 In the netTcpBinding: 12. In the In 12. 10. NewBinding0 In the wsHttpBinding: 11. the of pane In the Configuration 8. 8. the of pane In the Configuration 9. In the In 9. 7. 7. the expand Explorer, In Solution the Locate 6. L9-172 Module 9: Implementing Transactions MCT USE ONLY. STUDENT USE PROHIBITED

, 173 -

, , and Services Run as Run , click then and . . , and then click and then , , point, and to Accessories Unblock Allow project. . Lab: Implementing Transactions for a Service L9 Programs onFlow\ConnectedWCF\ContosoSer

as the value of the of the value as the as the value of the of the value as the ppointmentServiceImplementation . All Solution 'Connected WCF' 'Connected Solution dialog box, click dialog box, e WCF Configuration Editor, expand expand Editor, Configuration e WCF . . . . , right-click AppointmentServiceReference , point to entry and select nt to flow transactions entry and select and select entry Save Exit property. property. ClinicAdminClient Start . Ensure that the solution builds successfully before moving before successfully builds that the solution Ensure . . ContosoServicesSelfHostExtConfig.exe menu, click menu, menu, click menu, APService_WS APService_TCP Service References File File User Account Control dialog click box, User Account Security Alert Windows If you are using Visual Basic, go to the folder the folder to Basic, go Visual If you are using E:\Labfiles\Starter\VB\Transacti vicesSelfHostExtConfig\bin\debug the folder to Visual C#, go If you are using E:\Labfiles\Starter\CS\TransactionFlow\ConnectedWCF\ContosoSer . vicesSelfHostExtConfig\bin\debug

Update Service Reference Service then click Update administrator • Windows Explorer then click Windows • Explorer, expand the expand com.contoso.AppointmentService.A and then expandEndpoints WsHttpTransactionalBindingConfig BindingConfiguration BindingConfiguration NetTcpTransactionalBindingConfig Rebuild Solution Rebuild on. 5. In the In 5. 4. In the In 4. 2. 2. Explorer: in host transactional Locate the 7. Expand Expand 7. 6. 6. In Solution system. development 2008 Visual Studio® Microsoft Switch to Task 4: Configure the clie 1. taskbar, click On the 3. Right-click 14. th of pane Configuration In the 16. Click the Click 16. the On 17. 15. Click the Click 15. 18. On the On 18. 19. 19. right-click Explorer, In Solution

f

MCT USE ONLY. STUDENT USE PROHIBITED

. .

, and , and Code

Bindings View ) category of ) category ) category of ) category assembly, and assembly, . General General . In the. In Add Reference project. project. , and then click then , and project, right-click the the right-click project, comment, and then import the the import and then comment, True in the ( True in the ( System.Transactions TODO 9 TODO by pressing ENTER in the console console in the ENTER by pressing ClinicAdminClient ClinicAdminForm e WCF Configuration Editor, expand Editor, Configuration e WCF Edit WCF Configuration Edit WCF property to to property property to to property ClinicAdminClient . . tab, click the click the tab, Save Exit , and then click Add Reference , and then namespace. .NET ction from the client . tab. tab. References file, and then click file, and menu, click menu, menu, click menu, File File Binding Binding then set the TransactionFlow the then set the then set the TransactionFlow the then set the // TODO 9 usingSystem.Transactions; ... ' TODO 9. Imports System.Transactions ... [Visual C#] ... [Visual Basic] ... window. the click dialog box, then click OK ContosoServicesSelfHostExtConfig app.config System.Transactions 12. (netTcpBinding) named APService_TCP Click the binding configuration 13. On the On 13. 10. 10. th of pane In the Configuration Task 5: Start a transa 1. the expand Explorer, In Solution 9. In Visual Studio 2008, in the 8. the stop updates, reference service After the 14. On the On 14. 11. named APService_WS Click the binding configuration (wsHttpBinding) 2. Right-click 3. 3. right-click Explorer, In Solution 4. 4. locate the window, Editor In the Code

f L9-174 Module 9: Implementing Transactions MCT USE ONLY. STUDENT USE PROHIBITED 175 , - Patient Letters Service Letters Patient and method. Wrap the lines of code lines of code Wrap the method. Lab: Implementing Transactions for a Service L9 an appointment and send a letter in a and send a an appointment Appointment Service Appointment at the end of the scope. scope. end of the the Complete() at comment in the in the comment TODO 10 TODO patientLetterServiceProxy.SendLetter(LetterType. _ ConsultationBooked, patientId, doctorId,slot) scope.Complete() End Using ... slot) Dim patientLetterServiceProxy As PatientLetterServiceContract = _ New PatientLetterServiceContractClient("PLService_HTTP") 'TODO 11. [Visual Basic] ... ' TODO 10. Using scope As New TransactionScope() Dim proxy As AppointmentServiceContract = _ GetAppointmentServiceProxy() appointmentId = proxy.CreateAppointment(patientId, doctorId, MakeAppointmentWithClientTransaction the for proxies that create and then use these proxies to create to proxies these use and then . Call TransactionScope the Locate 5.

MCT USE ONLY. STUDENT USE PROHIBITED

. tab. into OK , click and then NH991199Z . . Create Appointment Unblock Create form, click the form, Solution 'Connected WCF' 'Connected Solution e client transaction rolls back the dialog box, click dialog box, . Start Debugging . Stop Debugging . Ensure that the solution builds successfully before moving before successfully builds that the solution Ensure . , and then click the first slot on the list. Make a note of the Make a note list. on the the first slot click , and then again, and then ensure that the slot you chose is no longer is no chose the slot you that ensure then again, and menu, click menu, menu, click menu, drop-down list box, and then click click and then list box, drop-down Debug Debug Windows Security Alert Windows Clinic Administration Client Administration Clinic Find Slots Find Slots Patient // TODO 11. patientLetterServiceProxy.SendLetter(LetterType. ConsultationBooked, patientId, doctorId, slot); scope.Complete(); } ... AppointmentServiceContract proxy = GetAppointmentServiceProxy(); appointmentId = proxy.CreateAppointment(patientId, doctorId, slot); PatientLetterServiceContract patientLetterServiceProxy = new PatientLetterServiceContractClient("PLService_HTTP"); [Visual C#] ... // TODO 10. using (TransactionScope scope = new TransactionScope()) { Rebuild Solution Rebuild on. the time for the slot that you have selected. Type the patient ID patient the Type selected. have you that slot time for the listed as available. changesthe appointment to service Task 6: Ensure that failure in th the On 1. 6. 6. right-click Explorer, In Solution

2. In the In 2. 4. Click 5. 5. click made, has been appointment that the confirming dialog box In the 3. In the In 3. 6. Click the On 7.

f L9-176 Module 9: Implementing Transactions MCT USE ONLY. STUDENT USE PROHIBITED

177 -

tab. into the TODO 11 TODO , click and then . class file, in the class file,

project. project. NH991199Z Create Appointment Code

. View method, locate the locate the method, Create Lab: Implementing Transactions for a Service L9 form, click the form, ClinicAdminForm ClinicAdminClient Solution 'Connected WCF' 'Connected Solution

, and then click click , and then . Start Debugging d the following code. d the following code. . , and then click to select the first slot on the list. Make a note Make a note list. the on slot first the to select click , and then menu, click menu, ClinicAdminForm Debug drop-down list box, and then click click and then list box, drop-down Clinic Administration Client Administration Clinic Find Slots MakeAppointmentWithClientTransaction comment, and then ad and then comment, if (causeAnIntentionalError) { throw new ApplicationException("This is an intentional error " + "to cause problems for a transaction"); } ... End If End If ... [Visual C#] ... // TODO 11 [Visual Basic] ... ' TODO 11. If causeAnIntentionalError Then Throw New ApplicationException("This is an intentional error" & _ "to cause problems for a transaction") Rebuild Solution Rebuild Patient of which slot you have selected. Type the patient ID the Type have selected. you of which slot 10. 10. for the window Editor the Code In 11. 11. right-click Explorer, In Solution 12. On the the On 12. 8. the expand Explorer, In Solution 14. Click 14. 13. In the In 13. 9. Right-click 9. Right-click

MCT USE ONLY. STUDENT USE PROHIBITED

. been operation have OK ve seen how to flow a transaction d ensure that when the transaction is d ensure that when CreateAppointment . Stop Debugging again, and then verify that the slot you chose is still available. you chose is still that the slot verify then again, and menu, click menu, Debug Find Slots After completing this exercise, you ha After completing this rolled back because of this client-side exception that aborts the transaction. transaction. aborts the that exception client-side this of because rolled back This proves that the effects of the the effects that This proves Results: a service an to from a client application the service are rolled back. by made changes aborted, the 17. On the the On 17. 15. click message, error displaying the dialog box In the 16. Click 16. L9-178 Module 9: Implementing Transactions MCT USE ONLY. STUDENT USE PROHIBITED

179 . - . . , click and then . Clinic Management Management Clinic transaction rolls back transaction rolls so that it can act as a client so Project/Solution Clinic Management Service Management Clinic . . Lab: Implementing Transactions for a Service L9 code that creates the appointment and code that creates the Service Clinic Management you created earlier so you created the that server , and , and icTransactions\ConnectedWCF , and , and icTransactions\ConnectedWCF 2008.

Patient Letter Letter Service Patient Solution 'Connected WCF' 'Connected Solution and Studio Open, and then click

Clinic Management Service Clinic Management cations with a call to the ConnectedWCF.sln ConnectedWCF.sln Clinic Management Service Management Clinic Visual dialog box, do one of the following: the following: of one do box, dialog

. menu, point to Microsoft File . Appointment Service Appointment Open Project Open then double-click then double-click If you are using Visual Basic, go to Visual Basic, go If you are using E:\Labfiles\Starter\VB\Automat then double-click to C#, go Visual If you are using E:\Labfiles\Starter\CS\Automat

Service the changes to the appointment service. the appointment to the changes for the • • Rebuild Solution Rebuild 4. Replace the client invo 2. 2. client endpoints. on the flow Enable transaction 3. the in workflow and letter appointment the Implement 1. Switch to 1. Switch The main tasks for this exercise are as follows: for this The main tasks 1. the to references Add 5. Ensure that failure in the Task 1: Add references to the Clinic Management Service so that it can act as a client for the Appointment Service and Patient Letter Service send the patient letter from the client to the the to the client from letter patient send the Exercise 2: Force a Transaction to Start When a Service Service a When to Start a Transaction Force 2: Exercise Is Called Operation to refactor the decided have client, you on the for transactions need the To avoid workflow code transactional of small piece transactions. creates all the will move the workflow In this exercise, you 2. On the the On 2. 3. In the In 3. 4. 4. right-click Explorer, In Solution

f

MCT USE ONLY. STUDENT USE PROHIBITED

. View . Run as Run

box

project. project. box . . , and then click then and , Address Namespace . Unblock . . Allow Add Service Reference Add Service st:8001/Contoso Delete into the into the into Transactions\ConnectedWCF\Cont Transactions\ConnectedWCF\Cont locate the service host executable file: executable host the service locate ClinicManagementService PatientLetterServiceReference Solution Explorer, right-click the right-click Explorer, Solution dialog box, click dialog box, http://localho file and click file and click project, and then click Add Service Reference and then project, box, type box, type box, type box, type app.config .

.

. , and then click click and then , ClinicManagementServiceImplementation ContosoServicesSelfHostExtConfig.exe , and then click , and then Service References Address Namespace OK Go Go OK AppointmentServiceReference http://localhost:8000/Contoso by pressing ENTER in the in the ENTER pressing by ContosoServicesSelfHostExtConfig dialog box, perform the following tasks: following the perform dialog box, Reference Service Add dialog box, do the following: the following: do dialog box, Reference Service Add User Account Control dialog click box, User Account Security Alert Windows . If you are using Visual Basic, go to the folder the folder to go Visual Basic, using If you are E:\Labfiles\Starter\VB\Automatic osoServicesSelfHostExtConfig\bin\debug If you are using Visual C#, go to the folder the folder to Visual C#, go If you are using E:\Labfiles\Starter\CS\Automatic osoServicesSelfHostExtConfig\bin\debug

d. Click console window. b. Click • b. Click c. Type Code administrator • c. In the c. In d. Click ClinicManagementService a. In the a. In a. Type 13. Stop the the Stop 13. 14. the expand Explorer, In Solution 15. Right-click on the on Right-click 15. 5. then and Explorer, Windows Switch to 16. Right-click 16. 8. In the In 8. 7. In the In 7. 9. 2008. In Switch to Visual Studio the In 10. 6. Right-click 12. In the In 12. 11. Right-click 11. L9-180 Module 9: Implementing Transactions MCT USE ONLY. STUDENT USE PROHIBITED

.

181 - and

Bindings . project, right- , and then verify that and then , ) category of the ) category General in the ( Lab: Implementing Transactions for a Service L9 True Edit WCF Configuration WCF Edit APService_TCP on the appointment service client on the appointmentservice e WCF Configuration Editor, expand Editor, Configuration e WCF ContosoServicesSelfHostExtConfig . . Save Exit property is set to is set property comment, and then import the the import and then comment, file, and then click TODO 12 TODO menu, click menu, click app.config tab. TransactionFlow PatientLetterServiceReference; ... [Visual C#] ... // TODO 12 using com.contoso.ClinicManagementService.AppointmentServiceReference; using com.contoso.ClinicManagementService. ... ' TODO 12. Imports Com.contoso.ClinicManagementService. _ AppointmentServiceReference Imports com.contoso.ClinicManagementService. _ PatientLetterServiceReference ... [Visual Basic] click the the Binding com.contoso.ClinicManagementService.AppointmentServiceReference com.contoso.ClinicManagementService.PatientLetterServiceReference namespaces. 2. 2. th of pane In the Configuration 1. 1. in the Explorer, In Solution Task 2: Enable transaction flow endpoint 3. Click the binding configuration named the Locate 17. File the 4. On 5. On the File the 5. On

f

MCT USE ONLY. STUDENT USE PROHIBITED

. class View Code

View project. project. project. . method, select the method, select project. project. Code

, and then click , and then View . d letter the Clinic workflow in ClinicManagementServiceContract ClinicManagementService ClinicAdminClient ClinicManagementService , and then click click , and then comment, and then add a definition for the definition add a comment, and then TODO 13 ClinicManagementServiceContract click and then , ClinicManagementServiceImplementation ClinicAdminForm MakeAppointmentWithClientTransaction . code for the method, including the method signature and parentheses, right- parentheses, and signature method the including method, the for code then click Copy and code, click the selected [Visual C#] // TODO 13 [OperationContract] string CreateAppointmentWorkflow(string patientId,string doctorId, DateTime slot, bool causeAnIntentionalError); ' TODO 13. _ Function CreateAppointmentWorkflow(ByVal patientId As String, _ ByVal doctorId As String, ByVal slot As DateTime, ByVal _ causeAnIntentionalError As Boolean) String As ... [Visual Basic] ... Code file, locate the operation. operation. CreateAppointmentWorkflow 6. Locate the the Locate 6. 2. Right-click 4. the expand Explorer, In Solution 8. Right-click 7. 7. to the return Explorer, In Solution Task 3: Implement the appointment an 1. the expand Explorer, In Solution Management Service 5. Right-click 3. 3. for the window Editor In the Code

f L9-182 Module 9: Implementing Transactions MCT USE ONLY. STUDENT USE PROHIBITED 183 -

. Paste TODO 14 the TODO file, locate Lab: Implementing Transactions for a Service L9 code window, and then click click and then window, code End Using Return appointmentId End Function ... " error to cause problems for a transaction") End If patientLetterServiceProxy.SendLetter(LetterType. _ ConsultationBooked, patientId, doctorId, slot) scope.Complete() PatientLetterServiceContract = _ New PatientLetterServiceContractClient("PLService_HTTP") 'TODO 11. If causeAnIntentionalError Then Throw New ApplicationException("Thisis an intentional" _ Using scope TransactionScope() As New Dim proxy As AppointmentServiceContract = _ GetAppointmentServiceProxy() appointmentId = proxy.CreateAppointment(patientId, _ doctorId, slot) Dim patientLetterServiceProxy As _ ' TODO 14. Private Function MakeAppointmentWithClientTransaction(ByVal _ patientId As String,ByVal doctorId As String, ByVal slot As _ DateTime) As String Dim causeAnIntentionalError As Boolean = True Dim appointmentId AsString = "UNDEFINED" ' TODO 10. [Visual Basic] ... ClinicManagementServiceImplementation comment, right-click in the comment, 9. the for window Editor In the Code

MCT USE ONLY. STUDENT USE PROHIBITED

} ... patientLetterServiceProxy.SendLetter(LetterType. ConsultationBooked, patientId, doctorId,slot); scope.Complete(); } return appointmentId; PatientLetterServiceContractClient("PLService_HTTP"); // TODO 11 if (causeAnIntentionalError) { throw new ApplicationException("Thisis an intentional" " error to cause problems for a transaction"); } GetAppointmentServiceProxy(); appointmentId = proxy.CreateAppointment(patientId, doctorId, _ slot); PatientLetterServiceContract patientLetterServiceProxy = new { bool causeAnIntentionalError = true; string appointmentId= "UNDEFINED"; // TODO 10 using (TransactionScope scope = new TransactionScope()) { AppointmentServiceContract proxy = [Visual C#] ... // TODO 14 private string MakeAppointmentWithClientTransaction(string patientId, string doctorId, DateTime slot)

L9-184 Module 9: Implementing Transactions MCT USE ONLY. STUDENT USE PROHIBITED

185 - . object, object, message, message, method as the m the following local variable. local TransactionScope causeAnIntentionalError method, perfor Lab: Implementing Transactions for a Service L9 appointmentId r.ShowTransactionalStatus , make the CreateAppointmentWorkflow CreateAppointmentWorkflow statement. scope.Complete() statement. statement that creates the the that creates statement using CreateAppointmentWorkflow and then delete the the delete and then of declaration the parameter after ClinicManagementServiceHelpe of the passing the name [Visual C#] ... // TODO 14 public string CreateAppointmentWorkflow(string patientId, string doctorId, DateTime slot,causeAnIntentionalError)bool ... ' TODO 14. Public Function CreateAppointmentWorkflow(ByVal patientId As String, _ ByVal doctorId As String, ByVal slot As Date, ByVal _ causeAnIntentionalError As Boolean) As StringImplements _ ClinicManagementServiceContract.CreateAppointmentWorkflow ... [Visual Basic] ... b. local variable of the definition Remove the c. calls the that Add a statement tasks: the a. Remove method public, and then change the method signature to match that defined that match to signature method the change then and method public, contract. in the service 11. Inside the the Inside 11. 10. to name method the Change

MCT USE ONLY. STUDENT USE PROHIBITED look like the following. the following. look like patientLetterServiceProxy.SendLetter(LetterType. _ ConsultationBooked, patientId, doctorId,slot) Return appointmentId End Function ... _ New PatientLetterServiceContractClient("PLService_HTTP") ' TODO 11 If causeAnIntentionalError Then Throw New ApplicationException("This is intentional"an & _ " error to cause problems for a transaction") End If Dim proxy As AppointmentServiceContract = _ GetAppointmentServiceProxy() appointmentId = proxy.CreateAppointment(patientId, doctorId, slot) Dim patientLetterServiceProxy As PatientLetterServiceContract = ByVal doctorId As String, ByVal slot As DateTime, ByVal _ causeAnIntentionalError As Boolean) As StringImplements _ ClinicManagementServiceContract.CreateAppointmentWorkflow Dim appointmentId AsString = "UNDEFINED" ClinicManagementServiceHelper.ShowTransactionalStatus( _ "CreateAppointmentWorkflow") [Visual Basic] ... ' TODO 14. Public Function CreateAppointmentWorkflow(ByVal patientId As String, _ The completed code should code completed The

L9-186 Module 9: Implementing Transactions MCT USE ONLY. STUDENT USE PROHIBITED

187 - method in Lab: Implementing Transactions for a Service L9 passing the endpoint name endpoint passing the method, and then replace it with a replace it with and then method, GetAppointmentServiceProxy . CreateAppointmentWorkflow statement that creates a new instance of the instance of the new creates a statement that AppointmentServiceContractClient APService_TCP [Visual Basic] ... Dim proxyAppointmentServiceContract As _ = New AppointmentServiceContractClient("APService_TCP") ...... "error to cause problems for a transaction"); } patientLetterServiceProxy.SendLetter(LetterType. ConsultationBooked, patientId, doctorId, slot); return appointmentId; } PatientLetterServiceContract patientLetterServiceProxy = new PatientLetterServiceContractClient("PLService_HTTP"); // TODO 11 if (causeAnIntentionalError) { throw new ApplicationException("This is an intentional" + string appointmentId "UNDEFINED";= ClinicManagementServiceHelper.ShowTransactionalStatus( "CreateAppointmentWorkflow"); AppointmentServiceContract proxy = GetAppointmentServiceProxy(); appointmentId = proxy.CreateAppointment(patientId, doctorId, slot); [Visual C#] ... // TODO 14 public string CreateAppointmentWorkflow(string patientId, string doctorId, DateTime slot,bool causeAnIntentionalError) { the 12. 12. calls the that statement Locate the

MCT USE ONLY. STUDENT USE PROHIBITED

Run as Run to the , click and then , and then click and then , . . TransactionScopeRequired OperationBehavior Transactions\ConnectedWCF\Cont Transactions\ConnectedWCF\Cont tions with a call to the Clinic Solution 'Connected WCF' 'Connected Solution comment, and add a comment, and add . Ensure that the solution builds successfully before moving before successfully builds that the solution Ensure . . . true ContosoServicesSelfHostExtConfig.exe TODO 14 TODO If you are using Visual Basic, go to the folder the folder to Basic, go Visual If you are using E:\Labfiles\Starter\VB\Automatic osoServicesSelfHostExtConfig\bin\debug If you are using Visual C#, go to the folder the folder to Visual C#, go If you are using E:\Labfiles\Starter\CS\Automatic osoServicesSelfHostExtConfig\bin\debug

// TODO 14 [OperationBehavior(TransactionScopeRequired = true)] ... ' TODO 14. _ ... [Visual C#] ... [Visual Basic] ... [Visual C#] ... AppointmentServiceContract proxy = new AppointmentServiceContractClient("APService_TCP"); ... • Rebuild Solution Rebuild on. then set its CreateAppointmentWorkflow property to to property administrator • Management Service Task 4: Replace the client invoca 1. Explorer. Windows Switch to 2. application: service host transactional Locate the 14. 14. right-click Explorer, In Solution 13. Locate the the Locate 13.

3. Right-click

f L9-188 Module 9: Implementing Transactions MCT USE ONLY. STUDENT USE PROHIBITED

. 189 - View Code project. project. . , and then click then , and method, passing the same the passing method, Allow method with statement that calls that with statement method . Lab: Implementing Transactions for a Service L9 method, and createAppointment_Click by pressing ENTER in the console the ENTER in by pressing ClinicAdminClient ClinicAdminForm , , right-click ClinicManagementServiceReference comment in the in the comment Update Service Reference Update TODO 15 TODO Service References dialog Control click box, User Account MakeAppointmentWithServerTransaction [Visual C#] ... // TODO 15 string appointmentId = MakeAppointmentWithServerTransaction(patientId.Text, doctorId.Text, slot); ...... ' TODO 15. Dim appointmentId As String = _ MakeAppointmentWithServerTransaction(patientId.Text, _ doctorId.Text, slot) ... [Visual Basic] ContosoServicesSelfHostExtConfig and then click window. then replace the statement that calls the that statement replace the then MakeAppointmentWithClientTransaction the parameters. 5. 2008. Studio Switch to Visual 6. the expand Explorer, In Solution the In 4. 8. 8. the stop updates, reference service After the 9. 9. right-click Explorer, In Solution 7. Expand Expand 7. 10. Locate the the Locate 10.

MCT USE ONLY. STUDENT USE PROHIBITED

ClinicAdminForm comment, and then add the following following add the and then comment, TODO 16 TODO ... bool causeAnIntentionalError = false; ClinicManagementServiceContract clinicManagementServiceProxy = new ClinicManagementServiceContractClient(); return clinicManagementServiceProxy.CreateAppointmentWorkflow( patientId, doctorId, slot, causeAnIntentionalError); } [Visual C#] ... // TODO 16 private string MakeAppointmentWithServerTransaction(string patientId, string doctorId, DateTime slot) { ClinicManagementServiceContractClient() Return clinicManagementServiceProxy.CreateAppointmentWorkflow( _ patientId, doctorId, slot, causeAnIntentionalError) End Function ... ' 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 _ [Visual Basic] ... class. method to the to the method MakeAppointmentWithServerTransaction the Locate 11. L9-190 Module 9: Implementing Transactions MCT USE ONLY. STUDENT USE PROHIBITED

191 - . tab. tab. drop- OK into the Patient , click and then . into the class file, locate the project. project. NH991199Z Create Appointment Create Appointment Code

. View Create NH991199Z . Lab: Implementing Transactions for a Service L9 . form, click the form, form, click the form, to true ClinicAdminForm

ClinicAdminClient Solution 'Connected WCF' 'Connected Solution , and then click click , and then Create Service Clinic Management the . Start Debugging . Start Debugging . Stop Debugging variable . , and then click to select the first slot on the list. Make a note Make a note list. the on first slot the to select click , and then , and then click the first slot on the list. Make a note of which of which a note Make list. on the the first slot click , and then no longer you chose is verify that the slot then again, and menu, click menu, menu, click menu, menu, click menu, ClinicAdminForm Debug Debug Debug drop-down list box, and then click click and then list box, drop-down Clinic Administration Client Administration Clinic Clinic Administration Client Administration Clinic Find Slots Find Slots Find Slots ... [Visual C#] ... bool causeAnIntentionalError = true; ... [Visual Basic] ... Dim causeAnIntentionalError As BooleanTrue= down list box, and then click down list box, and method. Change the value of the of the value the Change method. MakeAppointmentWithServerTransaction causeAnIntentionalError Solution Rebuild Patient of which slot you have selected. Type the patient ID the Type you have selected. of which slot slot you have selected. Type the patient ID patient ID the Type selected. have slot you available. 10. 10. right-click Explorer, In Solution 11. On the the On 11. transaction backrolls the changes to the appointment service Task 5: Ensure that failure in the On 1.

13. Click 13. 4. 4. click made, been has the appointment that confirms dialog box In the 3. Click 5. Click the On 6. 9. for the window Editor In the Code the In 12. 2. In the In 2. 7. 7. the expand Explorer, In Solution 8. Right-click

f

MCT USE ONLY. STUDENT USE PROHIBITED

.

. OK Debugging . have been operation

Stop Continue removed the transaction code from the removed the transaction code from ationException was unhandled by user was unhandled ationException CreateAppointment start a transaction on the service. start a transaction on the menu click click menu menu, click Debug Debug again, and then verify that the slot you chose is still available. you chose is still available. verify that the slot then again, and Find Slots After this exercise, you should have rolled back because of this server-side exception that aborts the transaction. the aborts that exception server-side of this because rolled back code' on code' is displayed, the This proves that the effects of the the effects This proves that Results: client and used WCF to automatically 18. 18. on the 2008, In Visual Studio 19. 19. 2008. Studio Close Visual 15. Administration Client. Clinic to the Switch 16. click an error, been has there that states dialog box In the Click 17. 14. 'Applic titled dialog box the When L9-192 Module 9: Implementing Transactions