Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using...

126
Object Innovations Course 4153 Student Guide Revision 4.0 Windows Communication Foundation Using C#

Transcript of Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using...

Page 1: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

Object Innovations Course 4153

Student Guide Revision 4.0

Windows Communication Foundation Using C#

Page 2: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC ii All Rights Reserved

Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners.

® is a registered trademark of Object Innovations. Authors: Robert J. Oberg, Julian Templeman and Ernani Junior Cecon Copyright ©2010 Object Innovations Enterprises, LLC All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Published in the United States of America.

Page 3: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC iii All Rights Reserved

Table of Contents (Overview) Chapter 1 WCF Essentials Chapter 2 Addresses and Bindings Chapter 3 Service Contracts Chapter 4 Instance Management Chapter 5 Data Contracts Chapter 6 More about Service Contracts Chapter 7 Handling Errors Chapter 8 WCF Security Appendix A Learning Resources Appendix B Hosting in IIS 7.5

Page 4: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC iv All Rights Reserved

Directory Structure

• Install the course software by running the self-extractor Install_WcfCs_40.exe.

• The course software installs to the root directory C:\OIC\WcfCs.

− Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02 and so on.

− The Labs directory contains one subdirectory for each lab, named after the lab number. Starter code is frequently supplied, and answers are provided in the chapter directories.

− The Demos directory is provided for performing in-class demonstrations led by the instructor.

Page 5: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC v All Rights Reserved

Table of Contents (Detailed)

Chapter 1: WCF Essentials.................................................................................................. 1 What Is WCF?..................................................................................................................... 3 WCF Services ..................................................................................................................... 4 Service Orientation ............................................................................................................. 6 WCF and Web Services ...................................................................................................... 7 WCF = ABC ....................................................................................................................... 8 Address, Binding, Contract................................................................................................. 9 Example – Hello WCF...................................................................................................... 10 Hosting Services ............................................................................................................... 11 Demo – Hello WCF .......................................................................................................... 12 A Service Contract............................................................................................................ 14 Visual Studio WCF Test Host........................................................................................... 15 Visual Studio Tools Menu ................................................................................................ 16 Visual Studio WCF Test Client ........................................................................................ 17 A Quick Test ..................................................................................................................... 18 WCF Test Client ............................................................................................................... 19 Closing the Test Host........................................................................................................ 21 Self-Hosting ...................................................................................................................... 22 ServiceHost Class ............................................................................................................. 23 Base Address..................................................................................................................... 24 Host Life Cycle ................................................................................................................. 25 WCF Clients...................................................................................................................... 26 Channels............................................................................................................................ 27 Demo – A Client for Hello WCF...................................................................................... 28 ChannelFactory ................................................................................................................. 29 Running the Example........................................................................................................ 30 Base Address Example ..................................................................................................... 31 Uri Class ........................................................................................................................... 32 Configuration Files ........................................................................................................... 33 Simplified Host Code........................................................................................................ 34 Proxy Initialization ........................................................................................................... 35 Metadata Exchange........................................................................................................... 36 Metadata Exchange Example............................................................................................ 37 Behaviors .......................................................................................................................... 38 Standard Endpoints ........................................................................................................... 39 A Service in a Browser ..................................................................................................... 40 Proxy Demo – SvcUtil ...................................................................................................... 41 Proxy Demo – Visual Studio Proxy.................................................................................. 43 Lab 1 ................................................................................................................................. 45 WCF Architecture............................................................................................................. 46 ServiceHost and ChannelFactory...................................................................................... 48 Service Contexts and Instances......................................................................................... 49

Page 6: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC vi All Rights Reserved

Summary ........................................................................................................................... 50

Chapter 2: Addresses and Bindings .................................................................................. 55 Addresses .......................................................................................................................... 57 Transports ......................................................................................................................... 58 Bindings ............................................................................................................................ 59 Message Exchange Patterns (MEPs) ................................................................................ 60 Security ............................................................................................................................. 61 Choosing a Binding .......................................................................................................... 62 HTTP Bindings ................................................................................................................. 63 TCP and Named Pipe Bindings ........................................................................................ 64 MSMQ Bindings............................................................................................................... 65 Importance of BasicHttpBinding ...................................................................................... 66 Demo – ASMX Web Service Client ................................................................................. 67 Working with Endpoints ................................................................................................... 71 Default Endpoints and Bindings ....................................................................................... 72 Default Endpoints Example .............................................................................................. 73 Helper Methods................................................................................................................. 74 ServiceDescription Class .................................................................................................. 75 Multiple Endpoints ........................................................................................................... 76 Multiple Endpoints Configuration File............................................................................. 78 Multiple Protocol Example............................................................................................... 79 Simple Host Code ............................................................................................................. 80 Lab 2 ................................................................................................................................. 81 Summary ........................................................................................................................... 82

Chapter 3: Service Contracts............................................................................................. 89 Service Contracts at Class Level ...................................................................................... 91 Service Contracts at Interface Level................................................................................. 92 Benefits of Interface Level Definition .............................................................................. 93 A Service with Multiple Contracts ................................................................................... 94 ServiceContractAttribute .................................................................................................. 96 ServiceContract Attribute Example .................................................................................. 97 Attributes in WSDL .......................................................................................................... 99 Viewing WSDL Files...................................................................................................... 100 Contract Inheritance........................................................................................................ 101 Operation Overloading ................................................................................................... 103 Enabling Operation Overloading .................................................................................... 104 Operation Overloading Client......................................................................................... 105 Lab 3 ............................................................................................................................... 106 Summary ......................................................................................................................... 107

Chapter 4: Instance Management ................................................................................... 117 Behaviors ........................................................................................................................ 119 WCF Behaviors............................................................................................................... 120 Configuring Behaviors.................................................................................................... 121 Configuring Behaviors in Code ...................................................................................... 122

Page 7: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC vii All Rights Reserved

WCF Instancing Models ................................................................................................. 123 Per-Call Instancing ......................................................................................................... 124 Per-Session Instancing.................................................................................................... 125 Sessions and Threading .................................................................................................. 126 Singleton Instancing ....................................................................................................... 127 Which Model to Use? ..................................................................................................... 128 PerSession Example........................................................................................................ 129 PerCall Example ............................................................................................................. 132 Singleton Example .......................................................................................................... 133 Lab 4 ............................................................................................................................... 134 Summary ......................................................................................................................... 135

Chapter 5: Data Contracts............................................................................................... 141 Data Contracts................................................................................................................. 143 Data Contract Example ................................................................................................... 144 Data Contract Demonstration ......................................................................................... 145 XSD for Data Contract.................................................................................................... 148 Client Demo.................................................................................................................... 150 Arrays.............................................................................................................................. 152 Array in XML Schema.................................................................................................... 153 Array in Proxy ................................................................................................................ 154 Generic Collections......................................................................................................... 155 Generic Collection in XML Schema .............................................................................. 156 Generic Collection in Proxy ........................................................................................... 157 Lab 5A ............................................................................................................................ 158 Enumerations in Data Contracts ..................................................................................... 159 Enumeration Data Contract Example ............................................................................. 160 Employee Client Program............................................................................................... 161 Saving and Restoring ...................................................................................................... 162 Serialization in WCF ...................................................................................................... 163 Serialization in .NET ...................................................................................................... 164 Serialization Example ..................................................................................................... 165 SOAP Serialization ......................................................................................................... 166 DataContract Serialization.............................................................................................. 167 JSON Serialization.......................................................................................................... 169 Using XmlSerializer ....................................................................................................... 170 XmlSerializer Example................................................................................................... 172 Restoring Data ................................................................................................................ 174 Versioning....................................................................................................................... 176 New and Missing Members ............................................................................................ 177 Versioning Demonstration.............................................................................................. 178 New Client of Old Service.............................................................................................. 180 Round Trip ...................................................................................................................... 181 Required Members.......................................................................................................... 182 OnDeserializing Event .................................................................................................... 183 Lab 5B............................................................................................................................. 184

Page 8: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC viii All Rights Reserved

Summary ......................................................................................................................... 185

Chapter 6: More about Service Contracts ..................................................................... 197 Versioning Service Contracts ......................................................................................... 199 Versioning Example........................................................................................................ 200 Version 1 Service............................................................................................................ 201 Version 2 Service............................................................................................................ 202 New Operations .............................................................................................................. 203 Version 3 Service............................................................................................................ 204 Version 1 Client / Version 3 Service .............................................................................. 205 Version 2 Client / Version 2 Service .............................................................................. 206 Version 3 Client / Version 3 Service .............................................................................. 207 Message Exchange Patterns............................................................................................ 208 Request-Reply................................................................................................................. 209 Oneway ........................................................................................................................... 210 Oneway Example ............................................................................................................ 211 Duplex............................................................................................................................. 212 Callbacks......................................................................................................................... 213 Invoking a Callback ........................................................................................................ 214 Callback on the Client..................................................................................................... 215 Asynchronous Proxies .................................................................................................... 216 Threading Considerations ............................................................................................... 217 Lab 6 ............................................................................................................................... 219 Summary ......................................................................................................................... 220

Chapter 7: Handling Errors ............................................................................................ 229 Errors in Distributed Systems ......................................................................................... 231 Errors in .NET and WCF ................................................................................................ 232 Demo of WCF Error Behavior........................................................................................ 233 Service Library Code ...................................................................................................... 235 Client Code ..................................................................................................................... 236 Client Exception Handling.............................................................................................. 237 Exception Handling Demo.............................................................................................. 238 Fault Exceptions ............................................................................................................. 240 Faults............................................................................................................................... 241 Exception Details in Faults ............................................................................................. 242 Exception Details ............................................................................................................ 243 Exceptions Dialog........................................................................................................... 245 Exception Details Demo ................................................................................................. 246 Fault Contracts ................................................................................................................ 248 Fault Contract Example .................................................................................................. 249 Fault Contract Example – Client .................................................................................... 250 Custom Faults ................................................................................................................. 251 Faulted Channels............................................................................................................. 252 Lab 7 ............................................................................................................................... 253 Summary ......................................................................................................................... 254

Page 9: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC ix All Rights Reserved

Chapter 8: WCF Security ................................................................................................ 263 Services and Security...................................................................................................... 265 Security Aspects of Services........................................................................................... 266 Transfer Security............................................................................................................. 267 Transport Security........................................................................................................... 268 Scenarios for Transport Security .................................................................................... 269 Configuring Transport Security ...................................................................................... 270 Transport Security Example ........................................................................................... 271 Host’s Security Configuration ........................................................................................ 272 Client’s Security Configuration ...................................................................................... 273 Message Security ............................................................................................................ 274 Scenarios for Message Security...................................................................................... 275 Configuring Message Security........................................................................................ 276 Other Security Modes ..................................................................................................... 277 Certificates ...................................................................................................................... 278 Certificate Demo............................................................................................................. 279 Managing Certificates..................................................................................................... 280 Exception Details ............................................................................................................ 284 Client Certificate Configuration ..................................................................................... 286 Sending Credentials ........................................................................................................ 289 Username Credentials ..................................................................................................... 290 Username Example ......................................................................................................... 291 Lab 8 ............................................................................................................................... 294 Summary ......................................................................................................................... 295

Appendix A: Learning Resources.................................................................................... 307

Appendix B: Hosting in IIS 7.5........................................................................................ 311 Internet Information Services ......................................................................................... 312 Installing IIS 7.5 ............................................................................................................. 313 WCF with IIS 7.5............................................................................................................ 314 .NET Framework Version............................................................................................... 315 Demo – Hello WCF ........................................................................................................ 318 A Service Contract.......................................................................................................... 320 A Website for the Service ............................................................................................... 321 WCF Service Template................................................................................................... 323 Service Configuration ..................................................................................................... 324 Referencing the Class Library ........................................................................................ 325 Examining the Service in the Browser ........................................................................... 326 WCF Clients.................................................................................................................... 327 Creating WCF Clients..................................................................................................... 328 Demo – A Client for Hello WCF.................................................................................... 329 Service as an IIS Application.......................................................................................... 333 Converting to an Application.......................................................................................... 334 Configuring as an Application........................................................................................ 335 Moving a WCF Solution................................................................................................. 336

Page 10: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC x All Rights Reserved

Page 11: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

WCF Essentials

Page 12: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 2 All Rights Reserved

WCF Essentials

Objectives

After completing this unit you will be able to:

• Explain how WCF unites and extends existing distribution technologies.

• Explain the concepts of address, binding, contract and endpoint.

• Describe how WCF services can be hosted

• Create a simple self-hosted WCF service configured via code.

• Implement a client of a WCF service using a Channel Factory.

• Use a configuration file to configure a service.

• Configure a service to export metadata.

• Use metadata to automatically generate a proxy for a service.

• Understand the WCF architecture and runtime.

Page 13: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 3 All Rights Reserved

What Is WCF?

• Windows Communication Foundation (WCF) is a new service-oriented programming framework for creating distributed applications.

− It was previously known as ‘Indigo’ and is part of .NET 3.0 and higher.

• WCF is designed to provide one mechanism for building connected applications:

− Within app domains

− Across app domains

− Across machines

• WCF builds upon and extends existing ways of building distributed applications:

− ASMX Web services, .NET Remoting, COM, MSMQ.

• All these do the same basic job (connecting elements in distributed applications) but they are very different at the programming level, with complex APIs and interactions.

− WCF provides one model for programming distributed applications. Developers only need to learn one API.

• WCF leverages existing mechanisms.

− It uses TCP, HTTP and MSMQ for transport.

Page 14: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 4 All Rights Reserved

WCF Services

• When using WCF, you create and consume services.

− A service comprises a set of related operations, which the programmer sees as method calls.

• Services are described by metadata, which clients can use to determine what operations are available, and how the service can be contacted.

− Metadata for WCF services is similar to the WSDL used by web services.

• Clients and services exchange messages.

− A client (which can be another service) communicates with a WCF service by sending and receiving messages. WCF uses SOAP as its messaging mechanism, and SOAP messages can be sent using a number of transports.

− Using SOAP does not imply that WCF communication is inefficient; efficient binary encodings are employed whenever possible.

• WCF supports several transports out of the box.

− TCP, HTTP, HTTPS and MSMQ.

− Custom transports can be added.

Page 15: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 5 All Rights Reserved

WCF Services

• WCF supports the WS-* family of Web service protocols.

− The WS-* family of protocols have been developed by various bodies (including OASIS and W3C) to provide features such as security, transactions and reliable messaging to web services.

• WCF is very good at interop.

− Support for a wide range of transports, encodings and the WS-* protocols means that WCF services can interoperate with a wide range of platforms and technologies, including J2EE and web services using WS-* protocols.

• WCF provides a foundation for service orientation.

− WCF helps developers write distributed applications in which loosely coupled services are called by clients and one another.

Page 16: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 6 All Rights Reserved

Service Orientation

• Service orientation is characterized by four concepts.

• Boundaries are explicit

− The boundary between client and service is explicit and highly visible, because calls are made via SOAP messages. There is no pretending – as there is in DCOM and Java’s RMI – that you are simply playing with a remote object, and can thus ignore the cost of remoting.

• Services are autonomous

− Services are independent entities that each have their own life cycle; they may have been developed completely independently of one another. There is no run-time making sure that services work well together, and so services must be prepared to handle failure situations of all sorts.

• Share schemas and contracts, not classes

− Services are not limited to implementation in OO languages, and so service details cannot be provided in terms of classes. Services should share schemas and contracts, and these are typically described in XML.

• Use policy-based service compatibility

− Services should publish their requirements (i.e. requiring message signing or HTTPS connections) in a machine readable form. This can be used at runtime to ensure compatibility between service and client.

Page 17: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 7 All Rights Reserved

WCF and Web Services

• Even though it uses SOAP messaging, WCF is more than simply another way of writing Web services.

− WCF can be used to write traditional Web services, as well as more sophisticated services that can use the WS-* protocols. But the design of WCF means that it provides a far more general solution to distribution than Web services.

• WCF can use several transports.

− Web services tend to use HTTP or HTTPS, while WCF is configured to use TCP, HTTP, HTTPS and MSMQ. It is also possible to add new transports, should the need arise.

• WCF can work throughout the enterprise.

− WCF services can be hosted in-process, by a Windows Service or IIS. Message exchange will be optimized to use the most efficient method for exchanging data for a particular scenario.

• WCF is good at interop.

− WCF services can interoperate with a number of different platforms and technologies.

• WCF is highly customizable.

− It is possible to customize almost every part of WCF, adding or modifying transports, encodings and bindings, and plugging in new ‘behaviors’ that affect the way WCF services work.

Page 18: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 8 All Rights Reserved

WCF = ABC

Service

CBA

CBA

CBA

A

B

C

Client C B A

= address

= binding

= contract

Where?

How?

What?

CB A = an endpoint

Page 19: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 9 All Rights Reserved

Address, Binding, Contract

• An address defines where a service can be found.

− It will often be an HTTP address, although other addressing schemes are supported.

• A binding defines how a service can be contacted

− Via HTTP, TCP, MSMQ or some custom mechanism.

• A contract defines what a service can do.

− In terms of method calls, their arguments and return types.

• A combination of an address, a binding and a contract is called an endpoint.

− A service can expose more than one endpoint, and endpoint data can be made available to clients in the form of metadata.

Page 20: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 10 All Rights Reserved

Example – Hello WCF

• A contract defines a set of operations that a service supports.

− Define a contract as an interface decorated with the ServiceContract attribute.

− Decorate operations with the OperationContract attribute.

[ServiceContract] public interface IHello { [OperationContract] string SayHello(string name); }

• A service class implements the interface.

− And so it has to implement all the operations defined in the contract.

public class Hello : IHello { public string SayHello(string name) { return "Hello, " + name; } }

• Note that this code says nothing about how the client communicates with the service.

− It is only the 'C' of the service 'ABC'.

Page 21: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 11 All Rights Reserved

Hosting Services

• There are three ways to host a WCF service.

• Self-hosting in an EXE.

− Use any type of EXE: Console application, Windows application (Windows Forms or WPF), or Windows Service.

− Need to manage service lifecycle yourself.

• Hosting in IIS.

− IIS will manage the service lifecycle for you, starting the service when the first request comes in.

− You can only use HTTP and port 80.

− Configure the service using a .svc file.

• Hosting in Windows Process Activation Service (WAS)

− WAS is a feature that is part of Vista, Windows Server 2008 and Windows 7.

− Similar advantages to hosting in IIS, but you can use other transports and ports as well.

− WAS also uses .svc files.

Page 22: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 12 All Rights Reserved

Demo – Hello WCF

• We’ll create a “Hello WCF” service that is self-hosted.

• Our solution will have three projects:

− A class library implementing the service

− A console application that hosts the service.

− A console application that invokes the service

1. Run Visual Studio 2010 as Administrator1. Create a new blank solution HelloWCF in the Demos folder.

2. In Solution Explorer, right-click over the solution and choose Add | New Project.

1 When working with WCF on Windows Vista and above it is important to always run Visual Studio as Administrator. If you forget, you’ll encounter strange errors!

Page 23: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 13 All Rights Reserved

Demo – Hello WCF (Cont’d)

3. From the WCF project types choose the WCF Service Library template. Enter HelloLib as the name of your new project.

4. Change the name of the file Service1.cs to HelloService.cs, and IService1.cs to IHelloService.cs. Say Yes to renaming all references in the project to the corresponding code element.

5. Examine the contents of these files, which include comments and starter code for both a Service Contract and also a Data Contract.

6. Examine also the file App.config. The renaming was not perfect, as under the <baseAddresses> tag there is still use of Service1. There is actually a reason for this, as we’ll see when we make us of the test programs WcfSvcHost.exe and WcfTestClient.exe.

Page 24: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 14 All Rights Reserved

A Service Contract

7. Edit IHelloService.cs to include only a simple service contract IHelloService with one method, SayHello().

namespace HelloLib { [ServiceContract] public interface IHelloService { [OperationContract] string SayHello(string name); } } 8. Edit HelloService.cs to implement the service contract.

namespace HelloLib { public class HelloService : IHelloService { public string SayHello(string name) { return "Hello: " + name; } } } 9. Build the service library project.

Page 25: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 15 All Rights Reserved

Visual Studio WCF Test Host

• To test the service we need both a host and a client program.

• We will implement both, but first let’s look at tools provided with Visual Studio.

− There is a test host WcfSvcHost.exe and a test client WcfTestClient.exe.

− Both are located in:

\Program Files\Microsoft Visual Studio 10.0\Common7\IDE

− This folder is already on the path of the Visual Studio command prompt.

• Bring up the Visual Studio command prompt from the Start Menu.

− It is under Visual Studio tools.

• Enter the command WcfSvcHost.exe without any arguments. You’ll get a message box explaining the usage. The first two arguments are required.

WcfSvcHost.exe /server:MyServer.dll /config:App.config /client:MyClient.exe /clientArgs:arg1,arg2,...

Page 26: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 16 All Rights Reserved

Visual Studio Tools Menu

• We’ll add the test host to the Tools menu.

1. Select menu item Tools | External Tools.

2. For title enter “Test Host”. For command navigate to the tool.

3. For arguments enter the following. Note that you can save typing by using the button.

/service:$(TargetPath) /config:$(ProjectDir)App.Config

Page 27: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 17 All Rights Reserved

Visual Studio WCF Test Client

• In a similar manner add a new external tool with title “Test Client” for the program WcfTestClient.exe.

− We don’t need to supply any arguments.

Page 28: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 18 All Rights Reserved

A Quick Test

1. Build the class library project.

2. Bring up the Test Host. It should start right up from the Tools menu because of the way we configured arguments. Click on the bubble to see detailed information.

3. You should see that the WCF Service Host has started.

4. Right click on the service. Choose Copy Metadata Address from the context menu.

5. Next, bring up the Test Client from the Tools menu.

Page 29: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 19 All Rights Reserved

WCF Test Client

6. Examine the documentation on the Start Page.

7. Choose the menu item File | Add Service. Paste in the metadata address you copied from WCF Service Host.

8. Click OK. You will see a tree view showing service projects that you are testing.

9. Double-click on the SayHello() method.

Page 30: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 20 All Rights Reserved

WCF Test Client (Cont’d)

10. You will see a form in which you can enter values for the parameters to SayHello().

11. In our case there is only one parameter. Enter a value for the name and click Invoke. After a few seconds you should see the response.

12. This concludes our quick test. Close the test client by File | Exit.

Page 31: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 21 All Rights Reserved

Closing the Test Host

13. File | Exit or File | Close will not close the test host.

• A pitfall may be that an instance of WCF Service Host remains running when you don’t think it is.

− To check for this, display the hidden icons from the task bar.

− To close, find the icon for WCF Service Host.

− Right-click over the icon and choose Exit from the context menu.

14. The program at this point is saved in Chap01\HelloWCF\LibraryOnly.

Page 32: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 22 All Rights Reserved

Self-Hosting

• Next we will add a console application that will host our service.

1. Right-click over the solution and choose Add | New Project.

2. From the Windows group choose Console Application. Assign the name Host and click OK.

3. Add a project reference to HelloLib and a .NET reference to System.ServiceModel. Import these two.

using System.ServiceModel; using HelloLib; 4. Provide this code in Main().

using (ServiceHost host = new ServiceHost( typeof(HelloService))) { host.AddServiceEndpoint( typeof(IHelloService), new BasicHttpBinding(), "http://localhost:8000/HelloService"); host.Open(); Console.WriteLine( "Press ENTER to terminate service host"); Console.ReadLine(); } 5. Right-click on the Host project and choose Set as Startup

Project from the context menu.

6. Build and run to make sure you get a clean compile and no runtime errors for the host. Press the ENTER key and exit.

Page 33: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 23 All Rights Reserved

ServiceHost Class

• The ServiceHost is used to implement a host.

− In self-hosting you instantiate an instance of ServiceHost directly.

− IIS and WAS use ServiceHost on your behalf.

• The main constructor requires a service type and zero or more base addresses.

public ServiceHost( Type serviceType, params Uri[] baseAddresses )

• Our example illustrated the simplest case with no base addresses specified.

ServiceHost host = new ServiceHost( typeof(HelloService))

− Endpoints must then supply an absolute URI for an address.

host.AddServiceEndpoint( typeof(IHelloService), // contract new BasicHttpBinding(), // binding "http://localhost:8000/HelloService"); // address

− Note the “ABC” of address, binding and contract for the endpoint.

Page 34: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 24 All Rights Reserved

Base Address

• Our next example illustrates specifying a base address for the http:// addressing scheme.

Uri httpBaseAddress = new Uri("http://localhost:8000/"); using (ServiceHost host = new ServiceHost( typeof(HelloService), // service type httpBaseAddress)) // base address

• In adding an endpoint we now specify a relative address.

host.AddServiceEndpoint( typeof(IHelloService), // contract new BasicHttpBinding(), // binding "HelloService"); // relative address // complete address is // http://localhost:8000/HelloService

− See Chap01\HelloWCF\BaseAddress.

Page 35: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 25 All Rights Reserved

Host Life Cycle

• A service host life cycle is controlled by calls to Open() and Close().

− Open() allows calls into the host, which are processed by worker threads.

− Close() gracefully exits the host, refusing new calls to the host but allowing calls in progress to complete.

− The CloseTimeout property (10 seconds by default) specifies the length of time the host will wait for the calls in progress to complete before shutting down anyway.

• The C# using statement facilitates managing the host’s life cycle.

− ServiceHost implements the IDisposable interface. Exiting a using block, either through normal program flow or via an exception, will call the Dispose() method, which in turn calls Close().

using (ServiceHost host = new ServiceHost(... { ... host.Open(); Console.WriteLine( "Press ENTER to terminate service host"); Console.ReadLine(); }

Page 36: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 26 All Rights Reserved

WCF Clients

• As in all common distribution technologies, clients interact with services through proxies.

− The proxy hides details of the communication mechanism being used from the client code.

− The proxy implements the same interface as the service, so that the client can use exactly the same calls.

• Proxies are created using metadata provided by the service.

− Note that the page shown in the previous page gives instructions for generating a proxy.

• The ABC (address, binding, contract) information provided by the service can be used to construct a proxy that

− Knows where to contact the service.

− Implements code to use the appropriate communication mechanism (eg. HTTP versus TCP).

− Implements the operations defined in the service interface.

• There are two approaches to creating proxies:

− “On the fly” using the ChannelFactory class.

− Auto-generate in advance by using a tool such as SvcUtil.exe or by adding a Service Reference in Visual Studio.

Page 37: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 27 All Rights Reserved

Channels

• Channels are used for communication between clients and services in WCF.

• Client code creates a proxy.

− The client often uses a ChannelFactory object to create the proxy. The proxy sends messages through the channel stack to the Dispatcher, which makes a call to an endpoint on the service.

• Service code often uses ServiceHost objects to manage WCF services.

Client

Proxy

Protocol Channel(s)

Transport Channel

Protocol Channel(s)

Transport Channel

Dispatcher

Service Endpoints

Page 38: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 28 All Rights Reserved

Demo – A Client for Hello WCF

• We’ll create a console client.

1. Add a third project to the solution, another Console Application. Specify Client as the name of your new project.

2. Add a reference to the System.ServiceModel assembly and import the corresponding namespace.

3. Provide the IHelloService service contract definition.

... using System.ServiceModel; namespace Client { [ServiceContract] public interface IHelloService { [OperationContract] string SayHello(string name); } class Program { static void Main(string[] args) { ...

Page 39: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 29 All Rights Reserved

ChannelFactory

4. Provide the following code in Main(). This initialize a proxy object as an instance of the ChannelFactory class. It is based on an endpoint that is compatible with the endpoint in the service.

EndpointAddress ep = new EndpointAddress( "http://localhost:8000/HelloService"); IHelloService proxy = ChannelFactory<IHelloService>.CreateChannel( new BasicHttpBinding(), ep); 5. Provide the following code to use the proxy object to call the

SayHello() method of the service and display the result. Exit the client program when the user presses the ENTER key.

string result = proxy.SayHello("ChannelFactory"); Console.WriteLine(result); Console.WriteLine( "Press ENTER to terminate client"); Console.ReadLine(); 6. Build the solution, now consisting of three projects. The

solution is saved in Chap01\HelloWCF\ChannelFactory.

Page 40: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 30 All Rights Reserved

Running the Example

1. Right-click over the Host project and select Debug | Start new instance from the context menu. Output:

Press ENTER to terminate client 2. Right-click over the Client project and select Debug | Start new

instance from the context menu. Output:

Hello: ChannelFactory Press ENTER to terminate client 3. Terminate first the client and then the host.

Page 41: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 31 All Rights Reserved

Base Address Example

• A few pages back we looked at an alternative way of specifying the address for an endpoint.

− The service host has one or more base addresses, and endpoints are specified using relative addresses.

host.AddServiceEndpoint( typeof(IHelloService), // contract new BasicHttpBinding(), // binding "HelloService"); // relative address // complete address is // http://localhost:8000/HelloService

• We instrument the host code to display all the base addresses before calling Open().

ShowBaseAddresses(host.BaseAddresses); ... static void ShowBaseAddresses( ReadOnlyCollection<Uri> addresses) { Console.WriteLine("Base Addresses:"); foreach (Uri addr in addresses) Console.WriteLine(" {0}", addr.OriginalString); }

• The client program is identical, because we’ve not changed the metadata for the contract.

• Here is the output from running the host: Base Addresses: http://localhost:8000/ Press ENTER to terminate service host

Page 42: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 32 All Rights Reserved

Uri Class

• The Uri class encapsulates a uniform resource identifier (URI) and provides easy access to the parts of the URI.

• Common properties include:

AbsolutePath Absolute path of the URI

IsAbsoluteUri Is the URI instance absolute?

LocalPath Local operating system representation of a file name

OriginalString The original URI string that was passed to the Uri constructor

PortNumber Port number of the URI

Scheme Scheme name of the URI (e.g. file, ftp, http, https, net.pipe, net.tcp, etc.)

Page 43: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 33 All Rights Reserved

Configuration Files

• In WCF there are always two options for supplying configuration information:

− In code, like we’ve done so far.

− In configuration files such as App.config and Web.config.

• As an example, the file App.config in the Host project provides the same configuration information as the WCFHello\BaseAddress code example.

− See WCFHello\Config for the complete example.

<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <services> <service name="HelloLib.HelloService"> <endpoint address="HelloService" binding="basicHttpBinding" contract="HelloLib.IHelloService" /> <host> <baseAddresses> <add baseAddress= "http://localhost:8000/" /> </baseAddresses> </host> </service> </services> </system.serviceModel> </configuration>

− Again we specify the address by the combination of a base address and a relative address.

Page 44: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 34 All Rights Reserved

Simplified Host Code

• When we have configuration specified in a configuration file, the host code becomes simpler.

static void Main(string[] args) { using (ServiceHost host = new ServiceHost( typeof(HelloLib.HelloService))) { host.Open(); ShowBaseAddresses(host.BaseAddresses); Console.WriteLine( "Press ENTER to terminate service host"); Console.ReadLine(); host.Close(); } } ...

• The last three examples all had identical client code; we did not change the metadata, only how it was described.

− HelloWCF\ChannelFactory

− HelloWCF\BaseAddress

− HelloWCF\Config

Page 45: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 35 All Rights Reserved

Proxy Initialization

• Up until now we’ve been creating a proxy directly by using a channel factory.

• This approach makes several assumptions:

− You know the endpoint address.

− You have a copy of the server contract definition.

− You know the required protocols or binding configurations.

• If you are developing both the service and the client, these are reasonable assumptions.

• But in the world of distributed computing when you need to talk to a service you don’t own, these are not reasonable assumptions.

• When you don’t own both the client and the service sides, a more effective approach is to generate the proxy automatically from metadata exported by the service.

− The metadata enables you to “know” the things you need to.

− The process of constructing a proxy is automated through the use of tools.

Page 46: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 36 All Rights Reserved

Metadata Exchange

• Metadata can be exported by a service through a special endpoint, known as a metadata exchange endpoint.

• This endpoint enables the generation of a proxy and a configuration file in the client project.

• To support this metadata exchange you need to do two things:

− Add the metadata exchange endpoint to the host configuration.

− Enable the metadata exchange behavior.

• A metadata exchange (mex) endpoint, like other endpoints, requires an address, a binding, and a contract.

− For the address you need the base address for the selected binding protocol (we’re using http exclusively in this chapter).

− The contract is the predefined IMetadataExchange.

Page 47: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 37 All Rights Reserved

Metadata Exchange Example

• We illustrate metadata exchange with a new variation of our HelloWCF example.

− See HelloWCF\SvcUtil. Here is the host’s configuration file, with changes indicated in bold.

<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <services> <service behaviorConfiguration="serviceBehavior" name="HelloLib.HelloService"> <endpoint address="HelloService" binding="basicHttpBinding" contract="HelloLib.IHelloService" /> <endpoint binding="mexHttpBinding" contract="IMetadataExchange"/> <host> <baseAddresses> <add baseAddress="http://localhost:8000/" /> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="serviceBehavior"> <serviceMetadata httpGetEnabled="True"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>

Page 48: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 38 All Rights Reserved

Behaviors

• A behavior affects the service model locally, on either the service side or client side.

− A behavior is not part of the metadata and does not affect the contract. They are not shared between service and client.

− Rather they have a local effect on how the service model processes messages.

• Service behaviors exist for metadata, debugging, security, serialization and throttling.

• Client behaviors exist for debugging, security, serialization, timeouts, and routing.

• A new <behaviors> element is provided in the configuration file.

− A behavior has a name.

− This name is used by the behaviorConfiguration attribute of the <service> element to tie a service to a behavior2.

− Client behaviors work in a similar manner in the configuration file.

• Behaviors can also be specified in code.

2 This use of the behaviorConfiguration attribute is optional in WCF 4.0.

Page 49: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 39 All Rights Reserved

Standard Endpoints

• An endpoint for metadata exchange almost always has exactly the same elements.

− To obviate the need for repetitive configuration, WCF 4.0 provides several standard endpoints.

− See the simplification in HelloWCF\StandardEndpoints.

<configuration> <system.serviceModel> <standardEndpoints> <mexEndpoint> <standardEndpoint /> </mexEndpoint> </standardEndpoints> <services> <service name="HelloLib.HelloService"> <endpoint address="HelloService" binding="basicHttpBinding" contract="HelloLib.IHelloService" /> ... </service> </services> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="True"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>

− Other standard endpoints are available for discovery, workflow and web.

Page 50: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 40 All Rights Reserved

A Service in a Browser

• A nice feature of WCF is that it enables viewing useful information about the service in a browser.

− Point the browser to the base address.

− For our example the base address is http://localhost:8000/.

− This useful page tells you how to create and use a proxy in your client program. (If no metadata exchange, you would see nice instructions for implementing it.)

Page 51: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 41 All Rights Reserved

Proxy Demo – SvcUtil

• The AutoProxy folder in the Demos directory contains starter code.

− It is a copy of HelloWCF\Config with App.config modified to support metadata exchange, as we have seen.

1. Build the starter solution.

2. Start the host.

3. Point your browser to http://localhost:8000/ and verify that the information about HelloService shown on the previous page is displayed. Note the instructions.

4. Bring up a Visual Studio command prompt and navigate to the Demos\SvcUtil folder.

5. Enter this command (note that it is not case sensitive):

svcutil.exe http://localhost:8000/?wsdl 6. There should be created files HelloService.cs and

output.config.

7. Copy these files down to the Client folder. Rename output.config to App.config. (If App.config already existed, you should edit the configuration information from output.config into it.) Add the files to the Client project.

8. Terminate the host and rebuild the solution.

9. In Program.cs in the Client project remove the using statement bringing in the namespace System.ServiceModel. (It is now only needed in the proxy that was generated. You still need a reference to the assembly, though.)

Page 52: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 42 All Rights Reserved

Proxy Demo – SvcUtil (Cont’d)

10. Remove the interface definition.

11. Remove the first two statements in Main() setting up an endpoint and initializing a proxy from a channel factory.

12. Examine the file HelloService.cs and note that the proxy class is HelloServiceClient.

13. Provide the following code to initialize the proxy and to close it when done. Again we’ll follow the pattern of the C# using statement.

static void Main(string[] args) { using (HelloServiceClient proxy = new HelloServiceClient()) { string result = proxy.SayHello("SvcUtil"); Console.WriteLine(result); Console.WriteLine( "Press ENTER to terminate client"); Console.ReadLine(); } } 14. Build the solution. Start the host and then the client. You

should see this output from the client:

Hello: SvcUtil Press ENTER to terminate client 15. Terminate the client and then the host. The completed demo

is saved in HelloWCF\SvcUtil. The invocation of svcutil.exe is done in a small batch file MakeProxy.bat

Page 53: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 43 All Rights Reserved

Proxy Demo – Visual Studio Proxy

• Continue in the AutoProxy folder from the previous demo.

1. In the Client project delete the files HelloService.cs and App.config.

2. Start the host outside of Visual Studio. (Right-click over the file Host.exe in the bin\Debug folder and choose Run as Administrator from the context menu.)

3. In Visual Studio right-click over References in the Client project and choose Add Service Reference. For the address enter http://localhost:8000/. Expand the tree so that you can see the contract. Leave the namespace as it is. Click OK.

Page 54: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 44 All Rights Reserved

Proxy Demo – VS Proxy (Cont’d)

4. Terminate the host.

5. In Solution Explorer, observe the new files in the Client project. You can see all files by clicking the Show All Files button . The important new files are Reference.cs and app.config.

6. Examine Reference.cs. The proxy class is HelloServiceClient and the namespace is Client.ServiceReference1. (We could have changed the namespace when we generated the service reference.)

7. All we need to do to use the preceding client program is to import the namespace.

using Client.ServiceReference1; 8. Build the solution. Test by starting the host and then the client.

The completed demo is saved in HelloWCF\VSProxy.

Page 55: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 45 All Rights Reserved

Lab 1

Creating a Simple Service and Client

In this lab, you will use Visual Studio 2010 to create a simple WCF service that is self-hosted. The metadata exchange endpoint is implemented with the help of starter code provided by Visual Studio. Note that the binding is wsHttpBinding rather than the basicHttpBinding that was used in the earlier example. You are provided with a Windows Forms application for the client. Create the proxy by adding a Service Reference using Visual Studio.

Detailed instructions are contained in the Lab 1 write-up at the end of the chapter.

Suggested time: 40 minutes

Page 56: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 46 All Rights Reserved

WCF Architecture

• Services and clients exchange SOAP messages.

− But they are not limited to text format; they can be sent in binary if that is more efficient.

• Channels abstract the communication process.

− Channels can be composed, so that the output from one channel acts as the input to another.

− There are two types of channel.

• Transport channels implement transport mechanisms

− Such as HTTP and TCP/IP.

• Protocol channels implement elements of the SOAP-based messaging protocol

− For example, the security channel implements SOAP security.

− The channel stack can be specified in configuration files or in code.

• Behaviors extend or modify service and client operation

− For example, whether metadata is published, or authentication is required.

− Behaviors can be specified in configuration or code.

Page 57: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 47 All Rights Reserved

WCF Architecture

• The following diagram illustrates the overall architecture of WCF.

− We looked at this diagram earlier in the chapter when we created a simple proxy using the ChannelFactory class.

Client

Proxy

Protocol Channel(s)

Transport Channel

Protocol Channel(s)

Transport Channel

Dispatcher

Service Endpoints

Page 58: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 48 All Rights Reserved

ServiceHost and ChannelFactory

• ServiceHost is used on the server side.

− A ServiceHost is used to host services in code (ie. Self-hosted services). The ServiceHost creates a ServiceDescription object, which consists of a type (implementing the service), a collection of behaviors (which control how the service behaves) and descriptions of one or more endpoints.

− The WCF runtime uses the ServiceDescription to build the channel stack and configure the endpoints.

• ChannelFactory is used on the client side.

− A ChannelFactory creates a ClientDescription. This consists of a collection of behaviors, and one endpoint. There is no need for a type, because clients don’t implement service contracts.

− The WCF runtime uses the ClientDescription to build the channel stack and proxy.

Page 59: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 49 All Rights Reserved

Service Contexts and Instances

• Each .NET host process can contain one or more app domains, and each app domain may contain zero or more ServiceHosts.

− Within a ServiceHost, service instances live in contexts; a WCF context is similar to a COM+ (Enterprise Services) context or a .NET context-bound object, in that it provides an environment in which service instances live.

− Properties and methods on the context allow the developer to control the behavior of the service instance, especially with respect to concurrency and object lifetime. A context can host at most one instance of a service object, so it is possible to have empty contexts.

Host Process

AppDomain

ServiceHost

Context

Service Object

Empty Context

Page 60: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 50 All Rights Reserved

Summary

• WCF unifies a number of existing technologies for creating distributed applications.

• WCF services are defined by addresses, bindings and contracts.

• WCF services can be hosted in IIS or WAS, or they can be self-hosted.

− We will use self-hosting throughout this course.

• WCF services and clients can be configured in code or via XML configuration files.

• You can implement a client of a WCF service using a Channel Factory.

• A WCF service can be configured to export metadata, which can be used to automatically generate a proxy for a service.

Page 61: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 51 All Rights Reserved

Lab 1

Creating a Simple WFC Service and Client

Introduction In this lab, you will use Visual Studio 2010 to create a simple WCF service that is self-hosted. The metadata exchange endpoint is implemented with the help of starter code provided by Visual Studio. Note that the binding from the Visual Studio starter code is wsHttpBinding rather than the basicHttpBinding that was used in the earlier example. You are provided with a Windows Forms application for the client. Create the proxy by adding a Service Reference using Visual Studio.

Suggested Time: 40 minutes Root Directory: OIC\WcfCs Directories: Labs\Lab1\SimpleMath (do your work here)

Chap01\SimpleMath\Step0 (starter code) Chap01\SimpleMath\Step1 (answer)

1. Part 1: Create the Service Library 1. Start Visual Studio 2010 as Administrator. Open the starter solution, which has a

Windows Forms project WinClient.

2. Add a new project MathLib to your solution using the WCF Service Library template.

3. Rename the file IService1.cs to IMath.cs and the file Service1.cs to MathService.cs.

4. In the files IMath.cs and MathService.cs, delete the starter code except for the namespace imports and the declaration of the MathLib namespace.

Page 62: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 52 All Rights Reserved

5. In the file IMath.cs, provide the following simple service contract IMath.

namespace MathLib { [ServiceContract] public interface IMath { [OperationContract] int Add(int x, int y); [OperationContract] int Subtract(int x, int y); } } 6. In the file MathService.cs, provide the following implementation:

namespace MathLib { public class MathService : IMath { public int Add(int x, int y) { return x + y; } public int Subtract(int x, int y) { return x - y; } } } 7. Build the solution.

Part 2: Create the Host 2. Add a new Console Application Host to your solution.

3. Add a reference to the MathLib project and the System.ServiceModel assembly.

4. In Program.cs import the namespaces System.ServiceModel and MathLib.

5. Provide code in Main() to initialize and open a ServiceHost object.

static void Main(string[] args) { using (ServiceHost host = new ServiceHost( typeof(MathService))) { host.Open(); Console.WriteLine("Press ENTER to terminate service host"); Console.ReadLine(); } }

Page 63: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 53 All Rights Reserved

6. Copy the App.config file from the MathLib project to the Host project and add it to the Host project. (You can do this by drag and drop in Solution Explorer.) Edit it to reflect the service and interface you are using. Note that some of the edits will have been made automatically when you changed the file names in the MathLib project. You only have to change the base address. Note that we will go with the empty string for the contract address, so we provide a complete URI for the base address.

<system.serviceModel> <services> <service name="MathLib.MathService"> <endpoint address="" binding="wsHttpBinding" contract="MathLib.IMath"> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="http://localhost:8000/MathService" /> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="True"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="False" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> 7. Build the solution.

Part 3: Implement the Windows Forms Client 1. Start the host outside of Visual Studio. Verify that it has been correctly implemented

by pointing your browser to http://localhost:8000/MathService. You should see a page for the MathService service. Copy this URI into the clipboard.

2. In the Client project right-click over References and choose Add Service Reference.

3. Paste the URI (http://localhost:8000/MathService) into the Address: text box.

Page 64: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 54 All Rights Reserved

4. Click Go. Expand the tree to show the IMath contract.

5. Click OK.

6. In Form1.cs import the namespace WinClient.ServiceReference1.

7. Implement the handler for the Add button.

private void btnAdd_Click(object sender, EventArgs e) { using (MathClient proxy = new MathClient()) { int x = Convert.ToInt32(txtX.Text); int y = Convert.ToInt32(txtY.Text); int result = proxy.Add(x, y); txtResult.Text = result.ToString(); } } 8. In a similar manner implement a handler for the Subtract button.

9. Build the solution.

10. Start up the host (inside or outside of Visual Studio) and then the client. Verify that the buttons work. Close the host and then the client. You’re done!

Page 65: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

89

Chapter 3

Service Contracts

Page 66: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

90

Service Contracts

Objectives

After completing this unit you will be able to:

• Define service contracts at either the class or interface level.

• Implement a service with multiple contracts.

• Show how contracts can be inherited.

• Explain operation overloading.

Page 67: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

91

Service Contracts at Class Level

• A service contract can be defined at the class level.

− Apply ServiceContract and OperationContract attributes directly to the class and its methods.

[ServiceContract] public class HelloService { [OperationContract] public string SayHello(string name) { return "Hello: " + name; } }

− The class name becomes the name of the contract.

<endpoint address="HelloService" binding="basicHttpBinding" contract="HelloLib.HelloService" />

− See ClassHello in the chapter directory for a complete example.

Page 68: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

92

Service Contracts at Interface Level

• A service contract can be defined at the interface level.

− Apply ServiceContract and OperationContract attributes to the interface and its methods.

[ServiceContract] public interface IHelloService { [OperationContract] string SayHello(string name); }

− A class then provides the implementation.

public class HelloService : IHelloService { public string SayHello(string name) { return "Hello: " + name; } }

− The interface name becomes the name of the contract.

<endpoint address="HelloService" binding="basicHttpBinding" contract="HelloLib.IHelloService" />

− See InterfaceHello in the chapter directory for a complete example.

Page 69: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

93

Benefits of Interface Level Definition

• Defining a contract at the interface level is more flexible.

− You can then use this contract in other contexts.

• With contracts defined in interfaces, you can easily implement a service that supports multiple contracts.

[ServiceContract] public interface IHelloService { [OperationContract] string SayHello(string name); } [ServiceContract] public interface IStringService { [OperationContract] string Concat(string name1, string name2); } public class HelloService : IHelloService, IStringService { public string SayHello(string name) { return "Hello: " + name; } public string Concat(string name1, string name2) { return name1 + name2; } }

Page 70: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

94

A Service with Multiple Contracts

• The HelloSevice service on the preceding page implements the contracts IHelloService and IStringService.

− See HelloString for the complete example. There is a Console client program and a Windows client program.

− App.config in the host project defines an endpoint for the second contract.

<endpoint address="HelloService" binding="basicHttpBinding" contract="HelloLib.IHelloService" /> <endpoint address="HelloService" binding="basicHttpBinding" contract="HelloLib.IStringService" />

Page 71: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

95

Multiple Contracts (Cont’d)

• When we add a service reference, we see two interfaces.

− There is an additional generated proxy class

StringServiceClient, used in handler of Concatenate button.

using (StringServiceClient proxy = new StringServiceClient()) { txtResponse.Text = proxy.Concat(txtName1.Text, txtName2.Text); }

Page 72: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

96

ServiceContractAttribute

• The ServiceContract attribute is used on an interface or class to define a service contract.

• The ServiceContractAttribute class has a number of properties.

− Namespace specifies a target namespace for messages, used to disambiguate messages on the wire. The default namespace is http://tempuri.org.

− Name provides a “friendly” name for the contract. The default is the CLR name of the interface used.

− ConfigurationName locates the service element in the configuration file. The default is the CLR name of the implementation class.

− SessionMode specifies whether the contract requires a binding that supports sessions.

− CallbackContract specifies the return contract in a duplex conversation.

− HasProtectionLevel specifies whether all messages supporting the contract have an explicit protection level.

− ProtectionLevel specifies the value of the protection level.

Page 73: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

97

ServiceContract Attribute Example

• The AttributeHello example illustrates specifying a Namespace and a Name.

[ServiceContract(Namespace = "http://oi.com", Name = "IHelloContract")] public interface IHelloService { [OperationContract] string SayHello(string name); }

• We can see these values with the aid of a helper method in the client program.

using (HelloContractClient proxy = new HelloContractClient()) { ShowEndpointInfo(proxy); ShowContractInfo(proxy); ... static void ShowContractInfo( HelloContractClient proxy) { Console.WriteLine("Contract info:"); ContractDescription cd = proxy.Endpoint.Contract; Console.WriteLine("Name: {0}", cd.Name); Console.WriteLine("Namespace: {0}", cd.Namespace); Console.WriteLine(); }

Page 74: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

98

ServiceContract Attributes (Cont’d)

• Here is the output from running the client: Contract info: Name: IHelloContract Namespace: http://oi.com

• Without applying the attributes we’ll have the default values.

− This can be seen with the aid of the same helper method in the preceding HelloString example.

− Run the Console client program.

Contract info: Name: IHelloService Namespace: http://tempuri.org/

Page 75: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

99

Attributes in WSDL

• The target Namespace and friendly contract Name show up in the WSDL specification.

<?xml version="1.0" encoding="utf-8"?> <wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/... ... targetNamespace="http://oi.com" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"> ... <wsdl:message name="HelloContract_SayHello_InputMessage"> ... <wsdl:message name="HelloContract_SayHello_OutputMessage"> <wsdl:portType name="HelloContract"> <wsdl:operation name="SayHello"> ... </wsdl:definitions>

Page 76: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

100

Viewing WSDL Files

• To view the WSDL for a self-hosted application, make sure that you have httpGetEnabled="true" in the <serviceMetadata> element of the host’s configuration file.

<behavior name="serviceBehavior"> <serviceMetadata httpGetEnabled="true"/> </behavior>

• You can then view the WSDL for the service by appending ?wsdl to the URI of the service.

Page 77: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

101

Contract Inheritance

• Contract interfaces can inherit from each, letting you define a hierarchy of contracts.

− But the ServiceContract attribute cannot be inherited. You must explicitly provide it at every level of the hierarchy.

[ServiceContract(Namespace = "http://oi.com")] public interface IHelloService { [OperationContract] string SayHello(string name); } [ServiceContract(Namespace = "http://oi.com")] public interface IFlexHello : IHelloService { [OperationContract] string Greet(string greeting, string name); }

• A single class can implement the whole hierarchy. public class HelloService : IFlexHello { public string SayHello(string name) { return "Hello: " + name; } public string Greet(string greeting, string name) { return greeting + ": " + name; } }

Page 78: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

102

Contract Inheritance (Cont’d)

• The configuration file for the host can provide a single endpoint for the interface at the bottom of the hierarchy.

<endpoint address="HelloService" binding="basicHttpBinding" contract="HelloLib.IFlexHello" />

• The client proxy provides a flattened hierarchy.

− There is a single contract, named after the bottom interface, which includes all the methods of the hierarchy.

• For a complete example, see InheritHello.

private void btnFlexGreet_Click(object sender, EventArgs e) { FlexHelloClient proxy = new FlexHelloClient(); txtResponse.Text = proxy.Greet(txtGreeting.Text, txtName.Text); }

Page 79: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

103

Operation Overloading

• In languages like C# you can overload method names as long as the parameter lists are different.

• But in WCF it is illegal to have operations with the same name in a contract.

• Thus the following example won’t work: [ServiceContract(Namespace = "http://oi.com")] public interface IHelloService { [OperationContract] string SayHello(string name); [OperationContract] string SayHello(string greeting, string name); }

• It will compile, but an InvalidOperationException will be thrown at the time the service host loads.

− OverloadHello\Step0 illustrates this problem.

Page 80: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

104

Enabling Operation Overloading

• You can enable operation overloading by using the Name property of the OperationContract to set up aliases for the operations having the same name.

− See OverloadHello\Step1.

[ServiceContract(Namespace = "http://oi.com")] public interface IHelloService { [OperationContract(Name = "Greet")] string SayHello(string name); [OperationContract(Name = "FlexGreet")] string SayHello(string greeting, string name); } public class HelloService : IHelloService { public string SayHello(string name) { return "Hello: " + name; } public string SayHello(string greeting, string name) { return greeting + ": " + name; } }

Page 81: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

105

Operation Overloading Client

• The client proxy will use the aliased names of the operation.

private void btnGreet_Click(object sender, EventArgs e) { HelloServiceClient proxy = new HelloServiceClient(); txtResponse.Text = proxy.Greet(txtName.Text); } private void btnFlexGreet_Click(object sender, EventArgs e) { HelloServiceClient proxy = new HelloServiceClient(); txtResponse.Text = proxy.FlexGreet( txtGreeting.Text, txtName.Text); }

• Here is the user interface of the client program:

Page 82: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

106

Lab 3

Working with Service Contracts

In this lab, you will create several variations of our simple math service to illustrate a number of the features of service contracts that we’ve been discussing.

Detailed instructions are contained in the Lab 3 write-up at the end of the chapter.

Suggested time: 60 minutes

Page 83: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

107

Summary

• A service contract can be defined at either the class or interface level.

• You can implement a service with multiple contracts.

• Service contracts can be inherited.

• Operations can be overloaded by using the Name property of the OperationContract attribute.

Page 84: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

108

Lab 3

Working with Service Contracts

Introduction In this lab, you will create several variations of our simple math service to illustrate a number of the features of service contracts that we’ve been discussing.

Suggested Time: 60 minutes Root Directory: OIC\WcfCs Directories: Labs\Lab3\MathOverload (do Parts 1 & 2 work here) Chap03\MathOverload\Step0 (Part 1 starter code backup) Chap03\MathOverload\Step1 (answer to Part 1) Chap03\MathOverload\Step2 (answer to Part 2) Labs\Lab3\MathInterfaces (do Parts 3 & 4 work here) Chap03\MathInterfaces\Step0 (Part 3 starter code backup) Chap03\MathInterfaces\Step1 (answer to Part 3) Chap03\MathInterfaces\Step2 (answer to Part 4) Part 1: Class-Level Definition versus Interface-Level Definition 1. Open the starter solution in Visual Studio. There are three projects:

• A WCF service library • A console service host • A Windows Forms client with the user interface shown above.

2. Build the solution.

Page 85: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

109

3. Start the host project. (Right-click on Host in Solution Explorer and choose Debug | Start new instance from the context menu.) Wait until the message giving instructions to terminate appears.

4. Start the Windows client program. Verify that you can add and subtract integers.

5. Examine the code for the MathService class in the MathLib project. Observe that the ServiceContract and OperationContract attributes are applied directly to the class.

[ServiceContract(Namespace = "http://oi.com")] public class MathService { [OperationContract] public int Add(int x, int y) { return x + y; } [OperationContract] public int Subtract(int x, int y) { return x - y; } } 6. Add a new class file to the MathLib project (right-click it and select Add, then New

Item, then select the Class template) named IAddMath.cs, that defines a service contract by an interface IAddMath. You will also need to import the namespace System.ServiceModel.

[ServiceContract(Namespace = "http://oi.com")] public interface IAddMath { [OperationContract] int Add(int x, int y); [OperationContract] int Subtract(int x, int y); } 7. Modify the MathService class to implement the contract through a class that derives

from IAddMath.

public class MathService : IAddMath { public int Add(int x, int y) { return x + y; } public int Subtract(int x, int y) { return x - y; } }

Page 86: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

110

8. Modify the App.config file in the Host project to refer to the contract as IAddMath rather than MathService.

<services> <service name="MathLib.MathService"> <endpoint address="MathService" binding="wsHttpBinding" contract="MathLib.IAddMath"> </endpoint> <host> <baseAddresses> <add baseAddress="http://localhost:8000/" /> </baseAddresses> </host> </service> </services> 9. We’ll need a new proxy and modified client code. Delete ServiceReference1 from

the Service References in the MathWin project. This will also cause the file Reference.cs to be deleted.

10. Build the service library and host projects. (Right-click over the Host project in Solution Explorer and choose Build from the context menu. This will automatically build the service library project as well, since the host has a reference to it.)

11. Start the Host project outside Visual Studio. To do this, open Windows Explorer, navigate to the bin\debug folder of the Host project and run Host.exe as administrator. Wait until the message giving instructions to terminate appears.

12. Add a new service reference to the WinClient project. For the service URI specify http://localhost:8000/. (You may copy this base address from the App.config file in the Host project.) Terminate the host.

13. With the Show All Files button activated, examine the file Reference.cs under Service References to see the name of the proxy class. It is AddMathClient.

14. Modify the handlers of the Add and Subtract button to use this proxy class name.

using (AddMathClient proxy = new AddMathClient()) { int x = Convert.ToInt32(txtX.Text); int y = Convert.ToInt32(txtY.Text); ... 15. Build the solution. Run the host. Run the Windows client program. Verify that it

works.

Page 87: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

111

Part 2: Operation Overloading 1. In the service library project, add definitions to the interface for adding and

subtracting floats. Do not provide new names for the method but overload the method names Add() and Subtract().

[ServiceContract(Namespace = "http://oi.com")] public interface IAddMath { [OperationContract] int Add(int x, int y); [OperationContract] float Add(float x, float y); [OperationContract] int Subtract(int x, int y); [OperationContract] float Subtract(float x, float y); } 2. Provide code in the class to implement these overloaded methods.

public class MathService : IAddMath { public int Add(int x, int y) { return x + y; } public float Add(float x, float y) { return x + y; } public int Subtract(int x, int y) { return x - y; } public float Subtract(float x, float y) { return x - y; } } 3. Compile the modified project. It will compile fine, as this is perfectly legal C# code.

4. Try to run the host. You will get an InvalidOperation exception, with a message that you cannot have two operations in the same contract with the same name.

5. Modify the code in the service library to disambiguate the operation names using the Name property.

[ServiceContract(Namespace="http://oi.com")] public interface IAddMath { [OperationContract] int Add(int x, int y);

Page 88: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

112

[OperationContract(Name="AddFloat")] float Add(float x, float y); [OperationContract] int Subtract(int x, int y); [OperationContract(Name="SubtractFloat")] float Subtract(float x, float y); } 6. You will continue to get a clean compile, and now you can run the host successfully.

Terminate the host.

7. In the WinClient project delete the service reference.

8. Start up the host outside Visual Studio. In the WinClient project add a service reference to the modified service, continuing to use the URI http://localhost:8000/. Terminate the host.

9. Modify the handler for the Add button to add either integers or floats depending on which radio button is checked, calling the appropriate method of the proxy.

private void btnAdd_Click(object sender, EventArgs e) { using (AddMathClient proxy = new AddMathClient()) { if (radInt.Checked) { int x = Convert.ToInt32(txtX.Text); int y = Convert.ToInt32(txtY.Text); int result = proxy.Add(x, y); txtResult.Text = result.ToString(); } else if (radFloat.Checked) { float x = Convert.ToSingle(txtX.Text); float y = Convert.ToSingle(txtY.Text); float result = proxy.AddFloat(x, y); txtResult.Text = result.ToString(); } } } 10. Modify the handler of the Subtract button in a similar manner.

11. Build the solution. Start the host, and start the Windows client project. You should now be able to add both integers and floats.

Page 89: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

113

Part 3: Interface Inheritance 1. Open the starter solution in Visual Studio. There are three projects:

• A WCF service library • A console service host • A Windows Forms client with the user interface shown below

2. Build and run (do the usual thing with starting the host first). You can add and subtract integers. A user interface is provided for multiply and divide, but these operations are not implemented yet.

3. Examine the starter code for the service library. There is an interface IAddMath with operations Add and Subtract and a class implementing this interface.

4. Add a new class file to the service library project named ICalculator.cs. In this file, define a new interface ICalculator inheriting from IAddMath with new operations Multiply and Divide. Provide suitable service and operation attributes.

[ServiceContract(Namespace = "http://oi.com")] public interface ICalculator : IAddMath { [OperationContract] int Multiply(int x, int y); [OperationContract] int Divide(int x, int y); } 5. Modify the code for the class to implement ICalculator.

public class MathService : ICalculator { public int Add(int x, int y) { return x + y; } public int Subtract(int x, int y) {

Page 90: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

114

return x - y; } public int Multiply(int x, int y) { return x * y; } public int Divide(int x, int y) { return x / y; } } 6. Edit App.config for the host project to refer to the ICalculator interface. Build the

solution.

<endpoint address="MathService" binding="wsHttpBinding" contract="MathLib.ICalculator"> 7. Build the solution.

8. Delete the service reference in the WinClient project.

9. Start up the host outside Visual Studio. In the WinClient project add a service reference to the modified service, continuing to use the URI http://localhost:8000/. Terminate the host.

10. In the WinClient project add handlers for the Multiply and Divide buttons.

11. Implement the handler for the Multiply button. Note that the name of the proxy class is now CalculatorClient.

private void btnMultiply_Click(object sender, EventArgs e) { using (CalculatorClient proxy = new CalculatorClient()) { int x = Convert.ToInt32(txtX.Text); int y = Convert.ToInt32(txtY.Text); int result = proxy.Multiply(x, y); txtResult.Text = result.ToString(); } } 12. Provide a similar handler for the Divide button.

13. Modify the handlers for the Add and Subtract button to use CalculatorClient as the proxy class.

14. Build and run (as usual start the host first). All four operations should now be operational!

Page 91: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

115

Part 4: Multiple Interfaces 1. Rename the file ICalculator.cs to IMultMath.cs. Note that Visual Studio will

automatically rename the interface name to IMultMath and update the references for you inside this project.

2. Modify the IMultMath interface so that it does not inherit from anything, keeping the code that defines the two operations Multiply and Divide.

3. Modify the class to inherit from the two interfaces IAddMath and IMultMath. It should implement all four methods.

4. Edit App.config in the host project to use IAddMath as the contract in the first endpoint. Provide a second endpoint that uses IMultMath as the contract.

<endpoint address="MathService" binding="wsHttpBinding" contract="MathLib.IAddMath"> </endpoint> <endpoint address="MathService" binding="wsHttpBinding" contract="MathLib.IMultMath"> </endpoint> 5. Build the service library and host projects. Verify that you get clean compiles and that

you can load the host. Observe that the helper display methods that we’ve retained in the host show the two endpoints. Terminate the host.

6. Delete the service reference from the WinClient project.

7. Start the host outside Visual Studio, and add a new service reference to the WinClient project, using our usual URI http://localhost:8000/.

8. Examine the proxy code in Reference.cs. Observe that there are proxy classes AddMathClient and MultMathClient corresponding to the two contracts.

9. Modify the handlers for the buttons to use these proxy classes. For example, here is the handler for the Divide button.

private void btnDivide_Click(object sender, EventArgs e) { using (MultMathClient proxy = new MultMathClient()) { int x = Convert.ToInt32(txtX.Text); int y = Convert.ToInt32(txtY.Text); int result = proxy.Divide(x, y); txtResult.Text = result.ToString(); } }

Page 92: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 3

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

116

10. Build and run (as usual start the host first). All four operations should now be operational.

Page 93: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

229

Chapter 7

Handling Errors

Page 94: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

230

Handling Errors

Objectives

After completing this unit you will be able to:

• Explain the use of exceptions and faults in WCF.

• Generate and handle faults in your programs.

• Specify and implement fault contracts.

• Explain the behavior of faults in bindings that maintain a session.

Page 95: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

231

Errors in Distributed Systems

• Effective error handling is critical in distributed.

− An error in servicing a particular client should not take down the whole service. The service should remain available to other clients.

• A key issue is how errors should be reported back to clients.

− Exceptions and exception handling is specific to a particular technology and is not suitable for crossing a service boundary.

• Moreover, in a service-oriented system, the service is encapsulated so that the client has little concern over the internal operations of the service.

− Details about an error on the service have little or no meaning to a client.

• When the details of an error are meaningful to a client, the error should be part of the contract between the client and the service.

Page 96: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

232

Errors in .NET and WCF

• In .NET errors cause an exception to be thrown.

− An unhandled exception causes the process in which the exception occurred to be terminated.

• WCF behavior is different.

− When a service encounters an error on behalf of a client, the whole service must not be taken down.

− Other clients using the service should not be affected.

• The WCF dispatcher silently catches unhandled exceptions and handles it by sending a return message to the client.

− The proxy will then throw an exception on the client side.

− The service remains available to other clients.

Page 97: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

233

Demo of WCF Error Behavior

• Let’s illustrate the behavior of errors in WCF.

− See MathFault\Step0 in the chapter directory.

1. Build the solution.

2. Run the host process outside of Visual Studio. (As usual, run as Administrator.)

3. Wait until the host has started, as evidenced by the message “Press ENTER to terminate the service host.”

4. Run two instances of the client program outside of Visual Studio. They do not have to run as Administrator.

5. In one instance enter a non-zero value for X and zero for Y.

6. Click the Divide button.

Page 98: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

234

Demo of WCF Error Behavior (Cont’d)

7. The Windows shell catches an unhandled exception in the client application.

8. Click Quit.

9. Go to the other running instance of the client and click the Multiply button.

10. It is evident that the host process has continued running, even though the service library code did not handle the DivideByZero exception. Close both the client and the host.

Page 99: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

235

Service Library Code

[ServiceContract(Namespace="http://oi.com")] public interface IMultMath { [OperationContract] int Multiply(int x, int y); [OperationContract(Name = "MultiplyDouble")] double Multiply(double x, double y); [OperationContract] int Divide(int x, int y); [OperationContract(Name = "DivideDouble")] double Divide(double x, double y); } public class MathService : IMultMath { public int Multiply(int x, int y) { return x * y; } public double Multiply(double x, double y) { return x * y; } public int Divide(int x, int y) { return x / y; } public double Divide(double x, double y) { return x / y; } }

• The service provides no exception handling code.

Page 100: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

236

Client Code

private void btnDivide_Click(object sender, EventArgs e) { MultMathClient client = new MultMathClient(); if (radInt.Checked) { int x = Convert.ToInt32(txtX.Text); int y = Convert.ToInt32(txtY.Text); int result = client.Divide(x, y); txtResult.Text = result.ToString(); } else if (radDouble.Checked) { double x = Convert.ToSingle(txtX.Text); double y = Convert.ToSingle(txtY.Text); double result = client.DivideDouble(x, y); txtResult.Text = result.ToString(); } client.Close(); }

• The client also provides no exception handling code.

− This is the reason the exception was only caught by the Windows shell.

Page 101: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

237

Client Exception Handling

• Step 1 provides exception handling in the client. txtResult.Text = ""; txtStatus.Text = ""; MultMathClient client = null; try { client = new MultMathClient(); if (radInt.Checked) { int x = Convert.ToInt32(txtX.Text); int y = Convert.ToInt32(txtY.Text); int result = client.Divide(x, y); txtResult.Text = result.ToString(); } else if (radDouble.Checked) { double x = Convert.ToSingle(txtX.Text); double y = Convert.ToSingle(txtY.Text); double result = client.DivideDouble(x, y); txtResult.Text = result.ToString(); } } catch (Exception ex) { txtStatus.Text = ex.GetType().ToString(); MessageBox.Show(ex.Message, "Exception"); } finally { client.Close(); }

• We show the type of the exception in a text box and the exception message in a message box.

Page 102: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

238

Exception Handling Demo

1. Build the Step 1 solution. Observe that the service library code is identical to Step 0.

2. Start the host process as before and start a single instance of the client program.

3. Again try doing an integer divide by zero. This time we catch an exception.

4. The client user interface now provides a text box docked to the bottom of the main window to display status messages. We show the type of the exception.

Page 103: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

239

Exception Handling Demo (Cont’d)

5. Try entering non-numeric characters for one of the numbers. You will hit a format exception.

6. Try doing a division by zero with double numbers. In floating point arithmetic, according to the IEEE standard, you do not generate an exception but get the result Infinity.

7. Exit the client and the host.

Page 104: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

240

Fault Exceptions

• WCF uses a new kind of exception, FaultException, to pass information about error conditions.

− FaultException is untyped, and the derived generic class FaultException<T> provides strongly typed access to detailed information about a fault.

• The diagram shows the class hierarchy of fault exceptions.

Exception

SystemException

CommunicationException

FaultException

FaultException<T>

Page 105: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

241

Faults

• Exceptions are technology specific and should not be shared across a service boundary.

− What is needed in a distributed environment is a neutral format for error information.

• SOAP faults provide such a neutral format.

− The SOAP specification defines an XML standard format for messages.

− Part of this specification defines SOAP faults, a structure for the contents of the message body in the case of errors.

− Because of its basis in XML, SOAP messages are highly interoperable.

• WCF works with both .NET exceptions and SOAP faults.

− An exception in the service is converted to a SOAP fault for transmission over the wire.

− The client proxy in turn converts the SOAP fault into a fault exception, which can be handled by client code through .NET exception handling.

Page 106: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

242

Exception Details in Faults

• For debugging purposes it may be useful for the fault to carry detailed diagnostic information.

− For security purposes you would normally not want such detailed information to be passed to the client in released code.

• There are several ways to specify in the service that such exception details should be passed in the fault.

− Specify it for the entire service in the configuration file using the <serviceDebug> element.

<behavior name="serviceBehavior"> <serviceDebug includeExceptionDetailInFaults="true"/> <serviceMetadata httpGetEnabled="true"/> </behavior>

− Use the ServiceBehavior attribute in front of a particular class.

[ServiceBehavior( IncludeExceptionDetailInFaults = true)] public class MathService : IMultMath

− In code for a particular method.

DivideByZeroException ex = new DivideByZeroException(); ExceptionDetail detail = new ExceptionDetail(ex); throw new FaultException<ExceptionDetail>( detail, "Division by zero not allowed");

Page 107: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

243

Exception Details

• Step 2 of the MathFault example illustrates two of these techniques for passing detailed exception information.

#if DEBUG [ServiceBehavior( IncludeExceptionDetailInFaults = true)] #endif public class MathService : IMultMath { ... public int Divide(int x, int y) { if (y == 0) { DivideByZeroException ex = new DivideByZeroException(); ExceptionDetail detail = new ExceptionDetail(ex); throw new FaultException<ExceptionDetail> (detail, "Division by zero not allowed"); } return x / y; } public double Divide(double x, double y) { if (y == 0) { DivideByZeroException ex = new DivideByZeroException(); throw ex; } return x / y; }

Page 108: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

244

Exception Details (Cont’d)

• Notice that in the method that does division of double numbers we explicitly throw an exception, but our code does not call for passing exception details.

• The ServiceBehavior attribute is specified conditionally for debug builds.

− Hence, in release builds we will not pass any detailed information that might pose a security risk.

#if DEBUG [ServiceBehavior( IncludeExceptionDetailInFaults = true)] #endif public class MathService : IMultMath

Page 109: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

245

Exceptions Dialog

• Before beginning the following demo, bring up the Exceptions dialog in Visual Studio.

− Use the menu Debug | Exceptions.

− You will see a list of exceptions for which Visual Studio will break when they are not handled by user code.

− Check the box for Common Language Runtime Exceptions.

Page 110: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

246

Exception Details Demo

1. Build the Step 2 solution.

2. This time try starting the host in the debugger from within Visual Studio rather than by the shell from the bin\Debug folder. Then start the client program.

3. Try doing an integer divide by zero. Because of the setting you just made in Visual Studio, you will break within Visual Studio and never hit the client program.

4. Stop debugging the program in Visual Studio.

5. Bring up the Debug | Exceptions dialog again.

Page 111: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

247

Exception Details Demo (Cont’d)

6. This time uncheck the box for Common Language Runtime Exceptions.

7. Now start the host within Visual Studio. Start the client.

8. Again try doing an integer divide by zero. This time you will hit the exception in the client program. Note that your custom error message is displayed.

9. Terminate the program within Visual Studio.

Page 112: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

248

Fault Contracts

• Exceptions thrown by the service reach the client as FaultExceptions.

• To allow clients to distinguish among different types of faults, WPF provides the concept of fault contract.

− The service lists the types of errors it can throw.

− These types are the same as the type parameters used in the generic FaultContract<T>.

• Here is how a service specifies a fault contract: [OperationContract] [FaultContract(typeof(DivideByZeroException))] int Divide(int x, int y);

• Here is how a service throws such a fault: DivideByZeroException ex = new DivideByZeroException(); throw new FaultException<DivideByZeroException>( ex, "Attempted to divide by zero");

• Here is how a client catches such a fault: catch (FaultException<DivideByZeroException> ex) { txtStatus.Text = ex.GetType().ToString(); MessageBox.Show(ex.Message, "DivideByZeroException"); }

Page 113: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

249

Fault Contract Example

• Step 3 of the MathFault example illustrates fault contracts.

• Here is the full contract: public interface IMultMath { [OperationContract] [FaultContract(typeof(OverflowException))] int Multiply(int x, int y); [OperationContract(Name = "MultiplyDouble")] double Multiply(double x, double y); [OperationContract] [FaultContract(typeof(DivideByZeroException))] int Divide(int x, int y); [OperationContract(Name = "DivideDouble")] [FaultContract(typeof(DivideByZeroException))] double Divide(double x, double y); }

• Besides divide by zero, we also check for integer overflow in multiply by using the C# checked arithmetic.

try { result = checked(x * y); } catch (OverflowException ex) { ex = new OverflowException(); throw new FaultException<OverflowException>( ex, "Integer overflow in multiplication"); } return result;

Page 114: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

250

Fault Contract Example – Client

• Here is the client code for multiply: try { client = new MultMathClient(); if (radInt.Checked) { int x = Convert.ToInt32(txtX.Text); int y = Convert.ToInt32(txtY.Text); int result = client.Multiply(x, y); txtResult.Text = result.ToString(); } else if (radDouble.Checked) { double x = Convert.ToSingle(txtX.Text); double y = Convert.ToSingle(txtY.Text); double result = client.MultiplyDouble(x, y); txtResult.Text = result.ToString(); } } catch (FaultException<OverflowException> ex) { txtStatus.Text = ex.GetType().ToString(); MessageBox.Show(ex.Message, "OverflowException"); } catch (Exception ex) { txtStatus.Text = ex.GetType().ToString(); MessageBox.Show(ex.Message, "Exception"); }

Page 115: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

251

Custom Faults

• When a fault is not due to a built-in exception known to the CLR, you may create your own type for the fault and specify a data contract for it.

− For an example, see SessionFault\Step2.

[DataContract] public class BalanceFault { [DataMember] public string Message; [DataMember] public int Shortage; public BalanceFault(string message, int shortage) { this.Message = message; this.Shortage = shortage; } }

• You may now use the BalanceFault type in the service contract to create a fault contract.

[ServiceContract()] public interface IAccount { [OperationContract] void Deposit(int amount); [OperationContract] [FaultContract(typeof(BalanceFault))] void Withdraw(int amount); [OperationContract] int GetBalance(); }

Page 116: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

252

Faulted Channels

• In the MathFault example the service uses the per-call instancing model and the communication channel remains open even after a fault has occurred.

• But in the case of a per-session instancing model, uncaught exceptions on the service will cause the service channel to fault.

− This means that subsequent calls on this channel will fail, with a CommunicationObjectFaultedException.

− See SessionFault\Step1 for an illustration of this behavior.

• You will fully develop this example in the lab.

Page 117: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

253

Lab 7

Custom Faults with a Session

In this lab you will implement fault contracts for a simple bank example where an account balance is stored in session state. You will also experiment with a fault without a contract, including providing detailed exception information to the client. Starter code implements deposit and withdraw operations, and a text box is provided for displaying status information regarding exceptions encountered.

Detailed instructions are contained in the Lab 7 write-up at the end of the chapter.

Suggested time: 45 minutes

Page 118: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

254

Summary

• While exceptions are platform specific, faults are neutral and are a suitable means of propagating error conditions in a distributed environment.

• The .NET Framework provides the FaultException and FaultException<T> classes as a means to encapsulate exceptions in faults.

• A fault contract allows a service to list the type of errors it can throw.

• When a channel maintains a session, uncaught exceptions will cause the channel to fault and subsequent calls on the channel will fail.

Page 119: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

255

Lab 7

Custom Faults with a Session

Introduction In this lab you will implement fault contracts for a simple bank example where an account balance is stored in session state. You will also experiment with a fault without a contract, including providing detailed exception information to the client. Starter code implements deposit and withdraw operations, and a text box is provided for displaying status information regarding exceptions encountered.

Suggested Time: 45 minutes Root Directory: OIC\WcfCs Directories: Labs\Lab7\SessionFault (do your work here) Chap07\SessionFault\Step1 (starter code backup) Chap07\SessionFault\Step2 (answer) Part 1: Examine the Starter Project 1. Run the starter solution. There are three projects: a service library, a host, and a

Windows client program. Build the solution and start the host. Then start the Windows client. You will be able to make deposits and withdrawals. You can overdraw the account, making the balance negative. If you try to deposit a negative amount, you will hit an exception. Terminate the program.

2. If on hitting an exception you are brought into Visual Studio, bring up the Exceptions dialog from the Debug menu and clear the User-unhandled checkbox for Common Language Runtime Exceptions.

3. Examine the file BankService.cs in the BankLib project. Observe that the InstanceContextMode is set to PerSession.

Page 120: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

256

4. Examine the file Form1.cs in the BankWin project. Basic exception handling is implemented, displaying a message box with an exception message.

Part 2: Experiment with Exceptions and Faults 1. Add code in the client to display in the status text box the type of exceptions that are

handled. Here is the code for the Deposit handler, and the code for the Withdraw handler is similar.

private void btnDeposit_Click(object sender, EventArgs e) { txtStatus.Text = ""; try { int amount = Convert.ToInt32(txtAmount.Text); proxy.Deposit(amount); txtBalance.Text = proxy.GetBalance().ToString(); } catch (Exception ex) { txtStatus.Text = ex.GetType().ToString(); MessageBox.Show(ex.Message, "Exception"); } } 2. Build and run. Try making a blank deposit. You will hit a System.Format exception.

Try making a negative deposit. You will hit a System.ServiceModel.FaultException. The message box displays a lengthy explanation about how to display detailed exception information (normally suppressed for security considerations). You may hit another exception when the application closes. We will deal with that later.

3. In the MathFault example we saw two ways of displaying detailed exception information. Now let’s do it by adding a <serviceDebug> element to <behavior> in the host’s configuration file.

<serviceBehaviors> <behavior name="serviceBehavior"> <serviceDebug includeExceptionDetailInFaults="true"/> <serviceMetadata httpGetEnabled="true"/>

Page 121: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

257

</behavior> </serviceBehaviors> 4. Build and run. Now the message box will display a nice descriptive error message.

5. Click OK in the message box and now try to deposit a positive amount. You will hit another exception, because the communication channel is now in the faulted state.

6. Close the message box. Exit the application. You will hit yet another exception in the handler for the FormClosed event when the code tries to close the proxy. Terminate the program in Visual Studio.

7. Add code to the FormClosed handler to check that the communication state is open. For the program to compile you will need to import the System.ServiceModel namespace.

private void Form1_FormClosed(object sender, FormClosedEventArgs e) { // Make sure open (not faulted) before close if (proxy.InnerChannel.State == CommunicationState.Opened) proxy.Close(); } 8. Build and run, repeating the same scenario of hitting an exception by trying to deposit

a negative amount. Now you will be able to close the application cleanly.

Part 3: Implement a Fault Contract 1. In the BankLib project add a new class file Faults.cs. Specify a data contract for a

fault AmountFault. You will need the System.Runtime.Serialization namespace.

Page 122: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

258

[DataContract] public class AmountFault { [DataMember] public string Message; public AmountFault(string message) { this.Message = message; } } 2. In BankService.cs modify the code for the Deposit() to now throw a typed

FaultException when the amount is negative.

public void Deposit(int amount) { if (amount < 0) { AmountFault f = new AmountFault( "Amount is negative"); throw new FaultException<AmountFault>(f); } m_balance += amount; } 3. Remember to use the AmountFault type in the service contract (in the file

IAccount.cs) to create a fault contract (using the FaultContract directive).

[ServiceContract(Namespace = "http://oi.com")] public interface IAccount { [OperationContract] [FaultContract(typeof(AmountFault))] void Deposit(int amount); ... 4. Build the HostCon project.

5. In the BankWin project delete the Service Reference and the app.config file.

6. Start the host outside Visual Studio and add a Service Reference. Use http://localhost:8000 as the Service URI.

7. Stop the host. Edit Form1.cs in the BankWin project to catch the specific exception FaultException<AmountFault> in the Deposit handler. Note that we obtain the exception message from the Detail property of the exception object.

private void btnDeposit_Click(object sender, EventArgs e) { txtStatus.Text = ""; try { int amount = Convert.ToInt32(txtAmount.Text); proxy.Deposit(amount);

Page 123: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

259

txtBalance.Text = proxy.GetBalance().ToString(); } catch (FaultException<AmountFault> ex) { txtStatus.Text = ex.GetType().ToString(); MessageBox.Show(ex.Detail.Message, "Exception"); } catch (Exception ex) { txtStatus.Text = ex.GetType().ToString(); MessageBox.Show(ex.Message, "Exception"); } } 8. Build and run. Try depositing a negative amount. We now get an appropriate error

message, and the communication channel is not faulted, because the exception is an expected one, as specified in the fault contract. Stop the application in Visual Studio.

Part 4: Implement a Second Fault Contract (Optional) 1. If time permits, implement a second fault contract, for a negative balance. In the file

Faults.cs in the service library project specify a data contract for a new type BalanceFault. Besides containing a message, this type has a property Shortage that shows how short the account is.

[DataContract] public class BalanceFault { [DataMember] public string Message; [DataMember] public int Shortage; public BalanceFault(string message, int shortage) { this.Message = message; this.Shortage = shortage; } } 2. In the file IAccount.cs specify fault contracts in the Withdraw() method for both the

previously defined type AmountFault and the new type BalanceFault.

[ServiceContract(Namespace = "http://oi.com")] public interface IAccount { [OperationContract] [FaultContract(typeof(AmountFault))] void Deposit(int amount); [OperationContract] [FaultContract(typeof(AmountFault))] [FaultContract(typeof(BalanceFault))] void Withdraw(int amount); ...

Page 124: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

260

3. In the implementation of Withdraw() check for both fault conditions. Only update

the balance if neither condition obtains.

public void Withdraw(int amount) { if (amount < 0) { AmountFault f = new AmountFault( "Amount is negative"); throw new FaultException<AmountFault>(f); } int newbal = m_balance - amount; if (newbal < 0) { BalanceFault f = new BalanceFault( "The balance cannot be negative", -newbal); throw new FaultException<BalanceFault>(f); } m_balance = newbal; } 4. Build the host project.

5. In the same manner as before, in the client project delete the Service Reference and the app.config file. Then start the host outside Visual Studio and add the Service Reference back in. Stop the host.

6. In the client project provide code in the handler for the Withdraw button to catch both kinds of contracted faults.

private void btnWithdraw_Click(object sender, EventArgs e) { txtStatus.Text = ""; try { int amount = Convert.ToInt32(txtAmount.Text); proxy.Withdraw(amount); txtBalance.Text = proxy.GetBalance().ToString(); } catch (FaultException<AmountFault> ex) { txtStatus.Text = ex.GetType().ToString(); MessageBox.Show(ex.Detail.Message, "Exception"); } catch (FaultException<BalanceFault> ex) { txtStatus.Text = ex.GetType().ToString(); txtStatus.Text += Environment.NewLine + ex.Detail.Message; MessageBox.Show("Please deposit " + ex.Detail.Shortage, "Exception"); } catch (Exception ex) {

Page 125: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

261

txtStatus.Text = ex.GetType().ToString(); MessageBox.Show(ex.Message, "Exception"); } } 7. Build and run. Exercise thoroughly the various exception conditions.

Page 126: Windows Communication Foundation Using C# · Revision 4.0 Windows Communication Foundation Using C#. ... Windows Communication Foundation Using C# Rev. 4.0 Student Guide Information

WcfCs Chapter 7

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC All Rights Reserved

262