Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications - Juntao Cheng - E-Book

Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications E-Book

Juntao Cheng

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

The Windows Communication Foundation 4.0 (WCF 4.0) is a .NET-based application programming interface for building and running connected systems. It enables secure and reliable communication among systems within an organization or across the Internet. This book deals with the difficult issues faced by a .NET developer while working with WCF.WCF 4.0 is a communications infrastructure that unifies a broad array of distributed systems' capabilities in a composable, extensible architecture that supports multiple transports, messaging patterns, encodings, network topologies, and hosting models. This book is a collection of focused real-world recipes and covers basic recipes on topics such as working with contracts to more advanced topics such as extending WCF runtime. By the end of this book you will have valuable information that helps transform the potentially unproductive habits of .Net developers who work with WCF.This book will take you through many concepts starting with complete support for contract-related design for WCF service development. You will learn to use WCF's built-in feature for building various service endpoints. Service hosting and configuration are important areas for building WCF services, especially at the service deployment stage, and are detailed in this book. You will find it easy to work with WCF client proxy generation and metadata publishing and discovery when you go through recipes such as customizing auto-generated service proxies.The author then discusses the exchange of data in WCF service operation features, related to WCF data serialization. You will discover some useful tips for security in WCF service development and built-in features for developing concurrency control for your services built upon it.One big plus is that you will learn to extend the existing WCF framework to achieve advanced functionality. You will find a dedicated chapter for RESTful and AJAX-enabled service development. Moving on, you will find several useful WCF service interoperability cases, which are important for a distributed service development platform. Towards the end of this book you will find some handy and useful diagnostic methods for troubleshooting.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 310

Veröffentlichungsjahr: 2010

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications
Credits
Foreword
About the Author
About the Reviewers
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Working with Contracts
Introduction
Defining a one-way Contract
How to do it...
How it works...
There's more...
See also
Make DataContract forward-compatible
How to do it...
How it works...
There's more...
See also
Generate DataContract from an XML Schema
Getting ready
How to do it...
How it works...
There's more...
See also
Using XMLSerializer to control message serialization
How to do it...
How it works...
See also
Using MessageContract to control the SOAP message
How to do it...
How it works...
See also
Adding a custom SoapHeader via Contract
How to do it...
How it works...
There's more...
See also
Return custom exception data through FaultContract
How to do it...
How it works...
There's more...
See also
2. Endpoint, Binding, and Behavior
Introduction
Configuring Default Endpoints
How to do it...
How it works...
There’s more...
See also
Setting up two-way communication over MSMQ
Getting ready
How to do it...
How it works...
There’s more...
See also
Building a Publish-Subscribe service with dual binding
Getting ready
How to do it...
How it works...
There’s more...
See also
Creating a multiple-endpoint service
How to do it...
How it works...
See also
Implementing a POX HTTP service
How to do it...
How it works...
There’s more...
See also
Defining a CustomBinding without a timestamp header
How to do it...
How it works...
See also
Suppressing mustUnderstand validation on unknown SoapHeaders
Getting ready
How to do it...
How it works...
There’s more...
See also
Sharing a physical address between multiple endpoints
How to do it...
How it works...
There’s more...
See also
3. Hosting and Configuration
Introduction
Hosting a service in a console application
How to do it...
How it works...
See also
Hosting a service in Windows Service
How to do it...
How it works...
See also
Hosting a HTTP service with ASP.NET-compatible context
How to do it...
How it works...
There's more...
See also
Hosting a non-HTTP service in IIS 7
How to do it...
How it works...
See also
Customizing IIS ServiceHost via ServiceHostFactory
How to do it...
How it works...
See also
Specifying a dedicated service instance for a singleton service
Getting ready
How to do it...
How it works...
There's more...
See also
Hosting a service in WSS 3.0
How to do it...
How it works...
See also
4. Service Discovery and Proxy Generation
Introduction
Creating a typed service client
How to do it...
How it works...
See also
Choosing a specific type for representing a collection parameter
How to do it...
How it works...
There's more...
See also
Reusing types between service and client
How to do it...
How it works...
See also
Customizing an auto-generated service proxy class in Visual Studio
How to do it...
How it works...
See also
Building an ad-hoc auto-discoverable service
Getting ready
How to do it...
How it works...
See also
Using managed ServiceDiscovery
How to do it...
How it works...
See also
Generating a service proxy in code
How to do it...
How it works...
There's more...
See also
Customizing auto-generated service metadata
How to do it...
How it works...
See also
5. Channel and Messaging
Introduction
Using ChannelFactory to consume a WCF service
How to do it...
How it works...
There's more...
See also
Invoking async operation viaChannelFactory
How to do it...
How it works...
There's more...
See also
Creating a service via ChannelListener
How to do it...
How it works...
There's more...
See also
Getting the IP address of a client consumer of a WCF service
How to do it...
How it works...
See also
Adding a dynamic SoapHeader into a message
How to do it...
How it works...
See also
6. Dealing with Data in Service
Introduction
Binding a WPF element with data from a WCF service
How to do it...
How it works...
There's more...
See also
Returning ReadOnlyCollection data
How to do it...
How it works...
See also
Using raw XML as an operation parameter
How to do it...
How it works...
There's more...
See also
Returning a DataTable/DataSet in a service operation
Getting ready
How to do it...
See also
Transferring binary data with MTOM encoding
Getting ready
How to do it...
See also
Specifying ServiceKnownType information in a programmatic way
How to do it...
How it works...
See also
Using XmlSerializer for custom data serialization
How to do it...
How it works...
See also
7. Security
Introduction
Setting up ad hoc Windows authentication over plain HTTP
How to do it...
How it works...
See also
Getting an authenticated client identity in a service operation
How to do it...
See also
Using username authentication with an ASP.NET membership provider
How to do it...
How it works...
See also
Sending a clear text username token over unsecured HTTP transport
Getting ready
How to do it...
How it works...
See also
Using transport and message security at the same time
How to do it...
How it works...
See also
Authorizing through declarative role-based access control
How to do it...
How it works...
See also
Impersonating with a client caller identity
Getting ready
How to do it...
How it works...
There's more...
See also
Adding multiple tokens in a service request (supportingToken)
How to do it...
How it works...
There's more...
See also
Supplying dedicated credentials for firewall or proxy authentication
Getting ready
How to do it...
Securing a dynamic SoapHeader
How to do it...
How it works...
See also
8. Concurrency
Introduction
Hosting a singleton instance service
How to do it...
How it works...
See also
Invoking a WCF service without blocking the front UI
How to do it...
How it works...
See also
Using throttling to control service concurrency
How to do it...
How it works...
There's more...
See also
Ensuring termination of a client session
How to do it...
How it works...
There's more...
See also
Tuning WCF concurrency performance via Visual Studio testing tools
How to do it...
How it works...
There's more...
See also
9. Extending WCF Runtime
Introduction
Using a custom ServiceHost
How to do it...
How it works...
See also
Intercepting operation parameters in a strong-type manner
How to do it...
How it works...
See also
Filtering operation requests based on message
How to do it...
How it works...
See also
Generic operation error handling with OperationInvoker
How to do it...
How it works...
There's more...
See also
Altering operation messages via MessageInspector
How to do it...
How it works...
See also
Building a custom MessageEncoder
How to do it...
How it works...
There's more...
See also
Centralizing authorization through a custom ServiceAuthorizationManager
How to do it...
How it works...
See also
10. RESTful and AJAX-enabled WCF Services
Introduction
Building a self-hosted REST service
How to do it...
How it works...
See also
Using an auto-generated Help page
How to do it...
How it works...
See also
Mapping URL suffix to operation parameters
How to do it...
How it works...
There’s more...
See also
Applying OutputCache in a REST service
How to do it...
How it works...
There’s more...
See also
Implementing file download via REST endpoint
How to do it...
How it works...
See also
Consuming a WCF service from an ASP.NET AJAX client
How to do it...
How it works...
There’s more...
See also
Accessing a remote REST service in an AJAX client
How to do it...
There’s more...
See also
11. Interoperability
Introduction
Building a WS-I Basic Profile 1.1 compatible service
Getting ready
How to do it...
How it works...
See also
Consuming an ASMX Web Service from a WCF client
How to do it...
How it works...
See also
Accessing a WCF service via the WebRequest component
How to do it...
How it works...
See also
Consuming a WCF service with a raw MSMQ program
How to do it...
How it works...
See also
Using a WCF Service in Microsoft Office
How to do it...
How it works...
See also
12. Diagnostics
Introduction
Using the WCF Test Client tool to test a service
How to do it...
There’s more...
See also
Capturing WCF request/response messages via Fiddler tool
How to do it...
See also
Using built-in tracing and message logging
How to do it...
How it works...
Debugging in a Windows service host
Getting ready
How to do it...
See also
Creating a custom Visual Studio Debugger Visualizer for WCF debugging
How to do it...
There’s more...
See also
Using PerformanceCounters for WCF service monitoring
How to do it...
13. Miscellaneous WCF Development Tips
Introduction
Creating test X.509 certificates for WCF Service
How to do it...
There's more...
Managing X.509 certificates installed on service machine
How to do it...
There's more...
Building an RSS feed service
How to do it...
There's more...
See also
Building a routing service
How to do it...
How it works...
There's more...
See also
Registering WCF components manually in IIS server
How to do it...
There's more...
Index

Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications

Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications

Copyright © 2010 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: October 2010

Production Reference: 1141010

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-849680-76-9

www.packtpub.com

Cover Image by Vinayak Chittar ( <[email protected] >)

Credits

Author

Steven Cheng

Reviewers

Frank Xu Lei

Kris van der Mast

Dong Qi

Acquisition Editor

Rashmi Phadnis

Development Editor

Dhwani Devater

Technical Editor

Vinodhan Nair

Copy Editor

Janki Mathuria

Indexer

Rekha Nair

Monica Ajmera Mehta

Editorial Team Leader

Gagandeep Singh

Project Team Leader

Lata Basantani

Project Coordinator

Jovita Pinto

Proofreader

Sandra Hopper

Graphics

Geetanjali Sawant

Production Coordinators

Alwin Roy

Adline Swetha Jesuthas

Cover Work

Alwin Roy

Foreword

In the process of development and integration of enterprise applications and systems, SOA is a flexible set of design principles and is becoming more and more popular.

Windows Communication Foundation (WCF) is a framework for building service-oriented applications, which are based on .NET.

WCF 4 comes with a wide range of specific features as follows:

Simplified configuration Standard endpoints IIS hosting without an SVC file WS-Discovery Routing service (previously included with Dublin) REST caching and Help page Workflow services Non-destructive queue receive Simple byte stream encoding ETW tracing

Besides giving an introduction of the basic WCF concepts (such as endpoint, contract, binding, and address), this book also covers advanced topics such as security, extensions of Runtime, and diagnostics. By the way, this book also introduces the new features of WCF 4.0. Every section is excellent and is based on a real WCF application. It also provides a lot of sample code to help the readers understand how to implement it. It's really a good handbook for WCF learners.

Thanks Steven for your hard work on this book.

Frank Xu Lei

MVP of Connected System Developer

About the Author

Steven Cheng is a senior support engineer at Microsoft Global Technical Support Center, where he has been supporting Microsoft software development technologies for more than five years. Currently, as a community leader, he is working actively in the MSDN newsgroup and forum communities.

Steven Cheng's technical specialties cover many popular areas of Microsoft development technologies, including .NET framework, ASP.NET, XML Web Service, Windows Communication Foundation, SharePoint development, and so on. His blog can be found at http://blogs.msdn.com/stcheng.

The publication of this book could not have been possible without the efforts put in by a large number of individuals. I would like to thank my colleague Andrew Zhu, who has helped me during the entire book authoring lifecycle. And thanks to my friends, Mian Li and Le Fei, who have given me lots of suggestions on the book recipes.

Lastly, I offer my regards and blessings to all of those who supported me in any respect during the completion of this book.

About the Reviewers

Frank Xu Lei is the Microsoft MVP of Connected System Developer. He is also the moderator of Microsoft's Chinese WCF Forum. He has translated the book Inside Windows Communication Foundation into Chinese.

He always focuses on Distributed Applications Development and EAI, based on .NET. Besides this, he is also a fan of NBA and sometimes, he goes to KTV with his friends. You can visit his blog at www.frankxulei.com.

Dong Qi is an experienced .NET developer and has four years experience in .NET development. He worked at Microsoft as a development support engineer in the MSDN team. He now works at the Agree company as a .NET developer for Agree's frontend finance products. Agree is a leading financial consulting, software, and service provider company in China. He has written on .NET debugging and .NET security.

Kris van der Mast, an active and dedicated moderator at the official ASP.NET forums, is a Microsoft MVP and ASP Insider. He's a well-known community member of several Belgian user groups. Kris is also a speaker for user groups in Belgium and abroad. You can find his blog at http://blog.krisvandermast.com.

Kris currently works for Ordina Belgium, a consultancy company, as a senior .NET developer and architect. He also provides courses to clients in his specialization and technical interest—web technologies.

Preface

Windows Communication Foundation 4.0 (WCF 4.0) is a .NET-based application programming interface for building and running connected systems. It enables secure and reliable communication among systems within an organization or across the Internet. This book deals with the difficult issues faced by a .NET developer while working with WCF.

What this book covers

Chapter 1, Working with Contracts, shows how we can use Contract in WCF service development, including use cases of ServiceContract, DataContract, MessageContract, FaultContract, and so on.

Chapter 2, Endpoint, Binding, and Behavior, focuses on the basic building blocks of a WCF service, including endpoint, binding, and behavior. The recipes in this chapter demonstrate how to create various kinds of services by using the proper combination of these building blocks.

Chapter 3, Hosting and Configuration, covers several common and useful WCF service-hosting scenarios, such as hosting a WCF service in a Windows service, IIS web applications, and a WSS 3.0 site.

Chapter 4, Service Discovery and Proxy Generation, covers how to discover and consume WCF services. Recipes here demonstrate various scenarios of generating a WCF service proxy and introduces the service discovery feature in WCF 4.0.

Chapter 5, Channel and Messaging, digs into the channel layer of WCF programming and shows how to build WCF server and client applications through channel-layer components.

Chapter 6, Dealing with Data in Service, covers various data exchange and communication scenarios in WCF development. Recipes here include how to transfer XML and raw binary data or ADO.NET DataTable objects in service operations.

Chapter 7, Security, demonstrates how to utilize the built-in WCF security features such as service authentication, authorization, identity impersonation, message protection, and so on.

Chapter 8, Concurrency, introduces some typical cases about managing the concurrency and performance behaviors of a WCF service, such as how to use throttling settings and how to use Visual Studio testing tools for service performance tuning.

Chapter 9, Extending WCF Runtime, focuses on how to extend the existing components in the WCF programming model, such as customizing the default ServiceHost, using MessageInspector or MessageEncoder to intercept messages, customizing the service authorization logic, and so on.

Chapter 10, RESTful and AJAX-enabled WCF Services, provides several recipes on WCF REST service programming, including building a standard REST service, building an AJAX-enabled REST service, and consuming a remote REST service from an AJAX client.

Chapter 11, Interoperability, shows how to make a WCF service or client work with non-WCF or even non-.NET platform-based applications (such as a WebRequest client, legacy MSMQ client, or Microsoft Office client).

Chapter 12, Diagnostics, introduces some useful tools and skills for troubleshooting and diagnostics in WCF service development, including how to capture WCF messages, how to debug a Windows service host, how to use WCF performance counters, and so on.

Chapter 13, Miscellaneous WCF Development Tips, provides some additional skills and cases in WCF service development such as how to generate and manage test X.509 certificates and how to build an RSS feed and routing services.

What you need for this book

Though all the samples in this book are C# based, you don't have to be a very experienced C# developer. What is required is that you have a development machine with Visual Studio 2010 (Professional or Ultimate edition) and IIS installed, since the sample code is provided as Visual Studio 2010 solutions and some of them use IIS as host.

Who this book is for

If you work with Windows Communication Foundation 4.0 and want to be efficient when working with WCF features such as interoperability, proxy generation, and security, you will find this book very useful. With this book, you will be able to find quick and handy solutions for various kinds of service development scenarios using Microsoft Windows Communication Foundation 4.0. To follow the recipes, you will need to be comfortable with the .NET framework, C# programming, and the basics of SOA and how to develop them.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "There is also a corresponding WebInvokeAttribute for a HTTP POST request."

A block of code is set as follows:

[ServiceContract] public interface IDataService { [OperationContract] string GetData(); }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

[ServiceContract(Namespace="WCF.REST")] public interface IDataService { [OperationContract] [WebGet(ResponseFormat= WebMessageFormat.Json)] SimpleData GetData(); }

Any command-line input or output is written as follows:

certmgr -c -r localmachine -s my

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Selecting Add Service Reference will launch a dialog where one can control the configuration options on how the WCF service proxy gets generated".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Tip

Downloading the example code for this book

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Working with Contracts

In this chapter, we will cover:

Defining a one-way ContractMaking DataContract forward-compatible Generate DataContract from XML SchemaUsing XMLSerializer to control message serializationUsing MessageContract to control the SOAP MessageAdding a custom SoapHeader via ContractReturning custom exception data through FaultContract

Introduction

Contracts often occur in business affairs to restrict the operations between the operators that are working with each other. For distributed communication services, Contracts also play a very important role in making sure that the service consumers can co-operate with the service providers correctly. Looking around, we can see the term SOA (Service-Oriented Architecture) being widely used. Technically speaking, SOAP (Simple Object Access Protocol) can be explained as a set of components that can be invoked, and whose interface descriptions can be published and discovered. From an SOA perspective, with Contracts properly defined, service consumers can get an idea of how to work with the target service without knowing how the service is actually implemented.

As a unified communication programming platform, WCF provides complete support for Contract-related design in various parts of WCF service development.These include ServiceContract, OperationContract, DataContract, MessageContract, FaultContract, and so on. ServiceContract and OperationContract are used to represent a Service and its operations' definition (such as the operation collection and operation signatures). DataContract is used to represent an agreement of the data that will be exchanged between the service client and server. If the service designer wants to take full control over the data envelope transferred between client and server, they can use MessageContract to control the underlying service messages. WCF also provides FaultContract for the service designer to declaratively associate custom Exception types to certain service operations, and the corresponding fault content will be returned when an error occurs.

This chapter provides seven recipes on how to work with various contracts in WCF service development. These include defining a one-way service operation that helps you get familiar with standard ServiceContract and OperationContract declaration. Next, we will cover how to use FaultContractAttribute to associate a custom SOAP fault data type with certain service operations that need a customized error format. With the third, fourth, and fifth recipes, we will focus on DataContract designing topics, such as DataContract versioning, using XMLSerializer for the DataContract types serialization, and the contract-first approach for DataContract generation. The last two recipes describe how to use MessageContract to perform low-level manipulation on the service operations message formatting, such as returning arbitrary XML data as message content and adding a custom SOAPHeader through MessageContract class members.

Make DataContract forward-compatible

WCF uses a serialization engine called DataContractSerializer by default, to serialize and deserialize data. If we want to add new complex data types (that will be transferred in service operations) in a WCF service, we need to define it as a DataContract type so as to make it friendly to the DataContractSerializer engine. A .NET serialization system supports backward-compatibility on custom data types naturally. However, sometimes we also need forward-compatibility for data types used in a WCF service. Suppose that you have a service that exchanges some custom data types between clients. If one side updates the custom data type (adds some fields or properties) or uses a newer version, it is important to make sure that the other side (without using the updated version of data) can still work correctly with the updated data type instances.

How to do it...

Make the custom data type (we will use in our service communication) implement the IExtensibleDataObject interface.
[DataContract] public class FCQuestion : IExtensibleDataObject { [DataMember] public string Subject { get; set; } [DataMember] public string Answer { get; set; } public ExtensionDataObject ExtensionData { get; set; } }
Make sure you haven't enabled the IgnoreExtensionDataObject property on ServiceBehaviorAttribute applied on your WCF service (this property is disabled by default).

You can have a look at the articleServiceBehaviorAttribute.IgnoreExtensionDataObject Property for more information and is available at:

http://msdn.microsoft.com/en-us/library/system.servicemodel.servicebehaviorattribute.ignoreextensiondataobject.aspx

How it works...

After the DataContract type implements the IExtensibleDataObject interface, an ExtensionDataObject property is added; this property plays an important role in forward-compatible serialization. WCF will use DataContractSerializer for DataContract type serialization/deserialization. When DataContractSerializer finds that a certain type (used for operation parameters or return value) has implemented the IExtensibleDataObject interface, it will store any data (this is obtained from the message stream during deserialization) that doesn't have corresponding property/fields in the type definition into the ExtensionDataObject property so that these data will not get lost. And if the deserialized instance (with some unknown data stored in ExtensionDataObject) is serialized into the message later, DataContractSerializer will write out ExtensionDataObject into the message stream again. This ensures that the data in the new version of DataContract can be consumed by the service/client with the old type definition correctly, instead of raising unexpected type, mismatching, or serialization exceptions.

The following modified data type can be consumed by the service/client that has the old definition, as explained earlier, without synchronizing the DataContract type definition:

[DataContract] public class FCQuestion : IExtensibleDataObject { [DataMember] public string Subject { get; set; } [DataMember] public string Answer { get; set; } [DataMember] public string Comment { get; set; } public ExtensionDataObject ExtensionData { get; set; } }

There's more...

Currently, using the IExtensibleDataObject interface can make the DataContractSerializer preserve unknown data properties/fields when deserializing/serializing custom data types. However, the ExtensionDataObject property is an opaque object to developers and we do not have means to manually read the data stored in it. In case we want to manually extract the additional unknown property/fields, we can consider directly accessing the underlying SOAP message via MessageInspector or other extension points.

See also

Altering an operation message via MessageInspector in Chapter 9.Complete source code for this recipe can be found inthe\Chapter 1\recipe2\folder

Using MessageContract to control the SOAP message

DataContract can help us design the data types used in a WCF service. However, this only covers the data members (variables and parameters used in operation) serialized in the underlying SOAP message. Sometimes we also need to control the structure and format of the entire SOAP message.

WCF introduces a MessageContract concept, which helps service developers to model the structure and format of the entire message of a given service operation. Actually, we can take MessageContract type as a special DataContract type, which is marked by the MessageContractAttribute