Scott Klein - WordPress

Transcription

ProfessionalWCF Programming.NET Development with the Windows Communication FoundationScott Klein

ProfessionalWCF Programming

ProfessionalWCF Programming.NET Development with the Windows Communication FoundationScott Klein

Professional WCF Programming: .NET Development with theWindows Communication FoundationPublished byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.comCopyright 2007 by Wiley Publishing, Inc., Indianapolis, IndianaPublished simultaneously in CanadaISBN: 978-0-470-08984-2Manufactured in the United States of America10 9 8 7 6 5 4 3 2 1Library of Congress Cataloging-in-Publication Data:Klein, Scott, 1966Professional WCF programming: .NET development with the Windows communication foundation / Scott Klein.p. cm.Includes index.ISBN 978-0-470-08984-2 (paper/website)1. Application software--Development. 2. Microsoft Windows (Computer file) 3. Microsoft .NET. 4. Web services. I.Title. QA76.76.A65K6 2007 005.3--dc222007003318No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 ofthe 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorizationthrough payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the LegalDepartment, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, oronline at http://www.wiley.com/go/permissions.LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OFTHIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BYSALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BESUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER ISNOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BESOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATIONAND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THEPUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED INTHIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN ANDWHEN IT IS READ.For general information on our other products and services please contact our Customer Care Department within theUnited States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries,and may not be used without written permission. Microsoft and Windows are registered trademarks of Microsoft Corporation in the United States and/or other countries. All other trademarks are the property of their respective owners. WileyPublishing, Inc., is not associated with any product or vendor mentioned in this book.Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be availablein electronic books.

About the AuthorScott Klein is an independent consultant with passions for all things SQL Server, .NET, and XML. He isthe author of Professional SQL Server 2005 XML by Wrox, writes the bi-weekly feature article for the SQLPASS Community Connector, and has contributed articles to both Wrox (www.Wrox.com) and TopXML(www.TopXML.com). He frequently speaks at SQL Server and .NET user groups. When he is not sitting infront of a computer or spending time with his family he can usually be found aboard his Yamaha at thelocal motocross track. He can be reached at ScottKlein@SqlXml.com.

CreditsSenior Acquisitions EditorProject CoordinatorJim MinatelJennifer TheriotDevelopment EditorGraphics and Production SpecialistsHoward A. JonesDenny HagerJennifer MayberryAlicia B. SouthTechnical EditorWilliam G. RyanQuality Control TechniciansEric CharbonneauCynthia FieldsJohn GreenoughCopy EditorProofreading and IndexingKim CoferAptaraEditorial ManagerAnniversary Logo DesignMary Beth WakefieldRichard PacificoProduction EditorProduction ManagerTim TateVice President and Executive Group PublisherRichard SwadleyVice President and Executive PublisherJoseph B. Wikert

ContentsAcknowledgmentsIntroductionxiiixvPart I: Introduction to Windows CommunicationFoundation1Chapter 1: Windows Communication Foundation Overview3The Need for SOAA Look BackUnderstanding Service OrientationService-Oriented Architecture PrinciplesMicrosoft’s Commitment to SOASOA Wrap-upWhy Windows Communication FoundationWCF ArchitectureThe Makeup of WCFWCF FeaturesSummaryChapter 2: Windows Communication Foundation ConceptsMessagesMessage StructureMessaging ProgramsMessaging PatternsChannelsChannel 3343636

ContentsChapter 3: Understanding Windows Communication FoundationWCF Programming ModelSO or OOService ModelWCF Programming MethodsWCF Programming LevelsThe Development ProcessAnd the Answer Is . . .Installing WCFCreating Your First WCF ServiceService 5671717172Part II: Programming Windows Communication Foundation73Chapter 4: Addresses75WCF AddressesAddress TypesAddress FormatsProgramming WCF AddressesEndpointAddress ClassProgramming AddressesSummaryChapter 5: Understanding and Programming WCF BindingsUnderstanding WCF BindingsPredefined Bindings75767780808386878788Programming WCF Bindings109Using CodeUsing Configuration Files110124SummaryChapter 6: Understanding and Programming WCF ContractsWCF ContractsContracts and Their Relationship with the CLRService Contractsviii126127128128128

ContentsService TypesData ContractsMessage ContractsProgramming WCF ContractsData ContractMessage ContractSummaryChapter 7: ClientsClient ArchitectureClient ObjectsClient ChannelsChannel FactoriesClient Communication ting Client CodeGenerating Client CodeDefining Client Bindings and EndpointsTyped versus Untyped ServicesInvoking Operations of a Typed ServicesInvoking Operations of an Untyped ServiceUseful InformationInitializing Channels InteractivelySession and Channel DurationBlocking IssuesException HandlingClient Programming ExampleChannelFactoryDuplexSummaryChapter 8: ServicesOverviewService TypesService ContractsService 93199201201202205206ix

Chapter #ContentsService BehaviorsServiceBehavior AttributeOperationBehavior AttributeUsing Configuration to Specify BehaviorsInstanceContextHandling tract Attribute221222Programming ExampleSummary224228Chapter 9: Transactions and Reliable SessionsTransactionsOverviewTransaction Attributes in System.ServiceModelReliable SessionsOverviewMessage ExchangeSecuring 1Chapter 10: Security253Security Overview254ConceptsWhy WCF Security?CredentialsSecurity Behaviors and BindingsSecurity BehaviorsBindingsSecuring Clients and ServicesBest PracticesSummaryChapter 11: Customizing Windows Communication FoundationExtending ServiceHost and Service Model 69272272273274274279283

ContentsExtending the Channel LayerClient ChannelService ChannelChannel DevelopmentExtending BindingsBuilding Custom BindingsUser-Defined BindingsSummaryChapter 12: Interoperability and IntegrationInteroperabilityWeb Service Protocol SupportWSE (Web Service Enhancements)ASP.NET Web egration305COM MSMQ305308SummaryPart III: Deploying Windows Communication FoundationChapter 13: Deploying Windows Communication FoundationInstalling WCF ServicesSupport Operating SystemsRequired SoftwareInstalling the WCF ServiceWCF Service ConfigurationsUpgrading ServicesTroubleshooting WCF InstallationsClient/Service CommunicationUnexpected Service BehaviorExceptionsSummaryChapter 14: Managing Windows Communication FoundationTracingEnd-to-End TracingService Trace ViewerMessage 23324324326333xi

ContentsService Configuration EditorConfigurationTasksDetailPerformance CountersSummaryChapter 15: Hosting Windows Communication Foundation ServicesHosting versus Self-HostingHostingSelf-HostingQuick ComparisonHosting ged Codea Windows ServiceWASHosting 345351352353356364Appendix A: WCF Template Extensions in Visual Studio365Appendix B: Case Study371Indexxii409

AcknowledgmentsI don’t know if I am just naive or what, but I would have thought that writing a second book wouldhave been easier than writing the first. I quickly learned that no book is easy to write, but to make it goas pain-free as possible you have to surround yourself with the best people possible. Sometimes theyfind you, and sometimes you have to go find them. Once you have everyone assembled, it is like poetryin motion. Therefore it is only appropriate to thank those individuals who made this project much lesspainful than it could have been.First and foremost Clay Andres and Neil Salkind, and everyone at Studio B for that matter, for beingwho they are and for all that they do. They take care of all of the things I don’t want to have to worryabout and let me do what I like to do. Man, that is nice.A huge thanks to the guys at Wrox/Wiley for making this book happen. Jim Minatel, for accepting thebook idea and letting me write it and for being patient with me when I was hitting a few walls. Thatmeant a lot Jim. I appreciate it. Howard Jones, my development editor, was a delight to work with. Ican’t thank Bill Ryan, the technical reviewer, enough for the time and energy he put into this. His comments were priceless.I learned during the writing of the first book that having that “one person” that you could go to forwhatever reason made life so much easier. I had that “one person” during the writing of my first book,but it took me awhile to find that “one person” for this book. But when I found that “one person” forthis book, it was like a whole new world opened up. Ralph Squillace, you are the man! Not many peoplewould take the time he did to help me understand a great many things, but he did and I cannot thankhim enough. Ralph went far above and beyond my expectations. If his boss is reading this, GIVERALPH A RAISE!A large dosage of gratitude also goes out to Clemens Vasters, Brian McNamara, Doug Purdy, JanAlexander, Michael Green, Laurence Melloul, and Kenny Wolf. A thank you to each of these people forletting me ask questions and providing excellent feedback.It has been said that you are only as good as those with whom you associate. So enough cannot be saidabout the love and support of my family, for without them, this book, or anything else I do in life wouldnot be possible. My tremendous wife, Lynelle, who during these times is an anchor for this family, whoheld the house together for the 8 months I spent upstairs. And to my children, who were patient withtheir father knowing that they soon “would get their dad back.” I love you all. I swear they weren’t thattall when I started this book.Now, on to book number three.

IntroductionWhile I was still trying to get the word “Grok” into everyone’s mainstream vocabulary (see the introduction in my first book), I happened upon what at the time was called WinFX, later to be renamed .NETFramework 3.0. Shortly thereafter I attended a local MSDN event where they presented some of the newtechnologies in .NET Framework 3.0, such as Windows Presentation Foundation and WindowsCommunication Foundation. I could hardly contain myself.SOA (Service-Oriented Architecture) is an important concept to Microsoft. The problem is that in thepast, SOA has had a fairly vague definition, but Microsoft is working hard to clear up the concept. SOAis not simply a set of services. SOA is the policies, frameworks, and practices under which the correctservices are provided.Web services were a great start, but SOA can help deliver the business agility and flexible IT that webservices were supposed to deliver. Enter Windows Communication Foundation. WindowsCommunication Foundation (WCF) is a platform for creating and distributing connected applications. Itis a fusion of current distributed system technologies designed and developed from the outset to helpsolve many of the SOA problems.Who This Book Is ForThis book is for developers who want to learn about Windows Communication Foundation and how itcan be a benefit in their environment. Equally, this book is also for those individuals who have spent atleast a little time looking at and playing with WCF and would like to dig deeper into the technology—tosee what WCF has to offer and how it can enhance current applications.A good understanding of the .NET Framework and related technologies (such as web services and theWS-* specifications) will be useful when reading this book, but is not required. If you have work

Graphics and Production Specialists Denny Hager Jennifer Mayberry Alicia B. South Quality Control Technicians Cynthia Fields John Greenough Proofreading and Indexing Aptara Anniversary Logo Design Richard Pacifico 01_089842 ffirs.qxp 3/5/07 7:00 PM Page vi. Contents Acknowledgments xiii Introduction xv Part I: Introduction to Windows Communication Foundation 1 Chapter 1: Windows Communication .