Book Image

Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications

By : Juntao Cheng
Book Image

Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications

By: Juntao Cheng

Overview of this book

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.
Table of Contents (20 chapters)
Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications
Credits
Foreword
About the Author
About the Reviewers
Preface
Index

Return custom exception data through FaultContract


In an XML Web Service and WCF service, the server side will return any unhandled exception as SoapFault in the returned message. For WCF service operations, exceptions are returned to the client through two steps:

  • Map exception conditions to custom SOAP faults

  • Services and client send and receive SOAP faults as exceptions

By default, WCF will return the simple error message or complete exception information (including Callstack) as the Fault content. However, sometimes we want to encapsulate the raw exception information or return some user-friendly error to the client side. To support this kind of customized exception-information format, WCF has provided the FaultContract and FaultException features. FaultException is a new exception type that uses Generic to help WCF service encapsulate various kinds of custom error data objects in a unified way. FaultContract is used to formally specify the type of FaultException that will be returned from the target WCF service operation, so that the client consumers can properly handle and parse it.

How to do it...

  1. First, create the custom error type that will be returned to the service client as exception information. The custom error type is defined as a standard DataContract type.

  2. Then, apply the custom error type to the service operation (which will return this custom error type) through a FaultContractAttribute.

  3. The following code shows a sample custom error type and the service operation that applies it:

      [DataContract]
        public class UserFriendlyError
        {
            [DataMember]
            public string Message
            { get;set; }
        }
    
    [ServiceContract]
        public interface ICalcService
        {
            [OperationContract]
            int Divide(int lv, int rv);
    
            [OperationContract]
            [FaultContract(typeof(UserFriendlyError))]
            int DivideWithCustomException(int lv, int rv);
    }
  4. Finally, we need to add our exception handling code in the service operation's implementation and return the custom error type through the FaultException<T> type (see DivideWithCustomException method shown as follows):

    public int Divide(int lv, int rv)
    {
        if (rv == 0) throw new Exception("Divided by Zero is not allowed!");
        return lv / rv;
            }
    
    public int DivideWithCustomException(int lv, int rv)
    {
        if (rv == 0) throw new FaultException<UserFriendlyError>(new UserFriendlyError() { Message = "Divided by Zero is not allowed!" }
           );
        return lv / rv; 
    }

How it works...

The FaultContractAttribute applied on the service operation will make the runtime generate corresponding metadata entries in the WSDL document (as shown in the next screenshot). Thus, the generated client proxy knows how to handle this custom error type.

When invoking the operation, we can add code to handle the specific FaultException and get user-friendly error information from the Exception.Detail property.

try
{
     //call the operation with invalid parameter
}
catch (FaultException<UserFriendlyError> fex)
{
     Console.WriteLine("Error: {0}", fex.Detail.Message);
}

If we use Fiddler or message logging to inspect the underlying SOAP message, we can also find the custom error data in XML-serialized format:

There's more...

Since the custom error type used by FaultContract supports any valid DataContract type, we can define various kinds of custom exception data content (from simple primitive types to complex nested classes).

See also

  • Generating DataContract from XML Schema

  • Capturing a WCF request/response message via Fiddler tool in Chapter 12

  • Complete source code for this recipe can be found in the \Chapter 1\recipe7\ folder