Learning Builder Pattern using C#

Introduction

Design patterns are very useful and helps in resolving many real time issues, In this article we will try to understand Builder Pattern with the help of a Sample C# Program.

Background

Builder Pattern belongs to Creational Pattern as it deals with object creation, this pattern is used multiple times in .NET Framework. One example would be ConnectionStringBuilder. Builder Pattern comes into picture when we need to create a product using a series of complex process where each process can be separated , that means we can separate each step of object creation and the same object mechanism can be used for creating similar products or objects.

GoF describes Builder Pattern as Separate the construction of a complex object from its representation so that the same construction process can create different representations. Builder Pattern consists of below items.

Director: Director is responsible for creation of object using Builder interface or base class.

Builder: Base class or Interface which has different steps mentioned for creating a Product.

ConcreteBuilder: Defines the concrete builder which is an implementation of above Builder. Concrete Builder will help us to create and get the below Product using series of steps mentioned in Builder.

Product: The final Product, which will be created through many complex steps.

BuilderPattern

Using the code

To start with th sample program, I have created a Television (Product) class as below, this Product will be constructed by the Builder. Added different properties to show the different parts of product.

[code language=”csharp”]
///
<summary>
/// Television – Product
/// </summary>

class Television
{
public string Code { get; set; }
public string DisplayTechnology { get; set; }
public string HDFormat { get; set; }
public string ScreenType { get; set; }
public string Size { get; set; }
public string Feature { get; set; }
}
[/code]

Now we will create the TelevisionBuilder (Builder), which will define the complex steps for creating the Product. We can create the Builder as an Interface or Base Class. If you look at the below class definition, you can see the steps for creating the Product and Property or Method to access the created Product.

[code language=”csharp”]
///
<summary>
/// TelevisionBuilder – Builder
/// </summary>

abstract class TelevisionBuilder
{
protected Television television;

public abstract void SetCode();//ProductCode
public abstract void SetDisplayTechnology(); //LCD, LED, OLED, Plasma, CRT
public abstract void SetHDFormat(); // Full HD, HD Ready, Ultra HD, None
public abstract void SetScreenType(); //Curved, Flat, Standard
public abstract void SetSize(); // 22, 32, 40, 42, 54
public abstract void SetFeature(); //3D, Smart, Standard , HDMI Ports, USB Ports, Built in WIFI, Ethernet, Remote

//GetProduct
public Television Television
{
get { return television; }
}

}
[/code]

Defining FullHD40TVBuilder (ConcreteBuilder1) with respective implementation.

[code language=”csharp”]
///
<summary>
/// FullHD40TVBuilder – ConcreteBuilder1
/// </summary>

class FullHD40TVBuilder : TelevisionBuilder
{

public FullHD40TVBuilder()
{
television = new Television();
}

public override void SetCode()
{
television.Code = “FullHD40TV”;
}

public override void SetDisplayTechnology()
{
television.DisplayTechnology = “LCD”;
}

public override void SetHDFormat()
{
television.HDFormat = “FullHD”;
}

public override void SetScreenType()
{
television.ScreenType=”Flat”;
}

public override void SetSize()
{
television.Size=”40″;
}

public override void SetFeature()
{
television.Feature = “1 HDMI Ports, 1 USB Ports, Remote”;
}
}
[/code]

Defining SMARTLED54TVBuilder (ConcreteBuilder2) with respective implementation.

[code language=”csharp”]
///
<summary>
/// SMARTLED54TVBuilder – ConcreteBuilder2
/// </summary>

class SMARTLED54TVBuilder : TelevisionBuilder
{
public SMARTLED54TVBuilder()
{
television = new Television();
}

public override void SetCode()
{
television.Code = “SMARTLED54TV”;
}

public override void SetDisplayTechnology()
{
television.DisplayTechnology = “LED”;
}

public override void SetHDFormat()
{
television.HDFormat = “FullHD”;
}

public override void SetScreenType()
{
television.ScreenType=”Flat”;
}

public override void SetSize()
{
television.Size=”54″;
}

public override void SetFeature()
{
television.Feature=”2 HDMI Ports, 2 USB Ports, Built in WIFI, Ethernet, Remote”;
}
}
[/code]

Defining Curved4K65LEDTVBuilder (ConcreteBuilder3) with respective implementation.

[code language=”csharp”]
///
<summary>
/// Curved4K65LEDTVBuilder – ConcreteBuilder3
/// </summary>

class Curved4K65LEDTVBuilder : TelevisionBuilder
{
public Curved4K65LEDTVBuilder()
{
television = new Television();
}

public override void SetCode()
{
television.Code = “Curved4K65LEDTV”;
}

public override void SetDisplayTechnology()
{
television.DisplayTechnology = “LED”;
}

public override void SetHDFormat()
{
television.HDFormat = “4K Ultra HD”;
}

public override void SetScreenType()
{
television.ScreenType=”Curved”;
}

public override void SetSize()
{
television.Size=”65″;
}

public override void SetFeature()
{
television.Feature=”3 HDMI Ports, 2 USB Ports, Built in WIFI, Ethernet, Smart Remote”;
}
}
[/code]

Defining LCD22TVBuilder (ConcreteBuilder4) with respective implementation.

[code language=”csharp”]
///
<summary>
/// LCD22TVBuilder – ConcreteBuilder4
/// </summary>

class LCD22TVBuilder : TelevisionBuilder
{
public LCD22TVBuilder()
{
television = new Television();
}

public override void SetCode()
{
television.Code = “LCD22TV”;
}

public override void SetDisplayTechnology()
{
television.DisplayTechnology = “LCD”;
}

public override void SetHDFormat()
{
television.HDFormat = “None”;
}

public override void SetScreenType()
{
television.ScreenType = “Flat”;
}

public override void SetSize()
{
television.Size = “22”;
}

public override void SetFeature()
{
television.Feature = “Remote”;
}
}
[/code]

As of now we have defined Product, Builder and ConcreteBuilder, Now lets create TelevisionManufacturer as the Director, here the argument is Builder, and the Director takes care of calling the steps based on the requirement.

[code language=”csharp”]
///
<summary>
/// TelevisionManufacturer – Director
/// </summary>

class TelevisionManufacturer
{
//Constructing Product
public void Construct(TelevisionBuilder televisionBuilder)
{
//Series of Complex Process
televisionBuilder.SetCode();
televisionBuilder.SetDisplayTechnology();
televisionBuilder.SetHDFormat();
televisionBuilder.SetScreenType();
televisionBuilder.SetSize();
televisionBuilder.SetFeature();
}
}
[/code]

Have created a console Program to test the Builder Pattern Sample, here the end clinet is not at all worried about the complex object creation.

[code language=”csharp”]
///
/// Program class which demonstrates the builder usage
///

class Program
{
///
/// Main method of Program.cs
///

///static void Main(string[] args)
{
TelevisionBuilder builder;

TelevisionManufacturer director = new TelevisionManufacturer();

builder = new FullHD40TVBuilder();
director.Construct(builder);
Television product1 = builder.Television;

Console.WriteLine(“Code:{0}”, product1.Code);

builder = new SMARTLED54TVBuilder();
director.Construct(builder);
Television product2 = builder.Television;

Console.WriteLine(“Code:{0}”, product2.Code);

builder = new Curved4K65LEDTVBuilder();
director.Construct(builder);
Television product3 = builder.Television;

Console.WriteLine(“Code:{0}”, product3.Code);

builder = new LCD22TVBuilder();
director.Construct(builder);
Television product4 = builder.Television;

Console.WriteLine(“Code:{0}”, product4.Code);
//Wait for UserInteraction
Console.ReadKey();

}
}
[/code]

Output

Some codes are removed from above Console.Writeline to look the code simple. You can refer the Program.cs file in the attached project to see the final version.

BuilderPatternSampleOutput.png

To explore this sample yourself you can download the attached code or create a console project named “BuilderPatternSample” and replace the content of Program.cs with below code block.

Program.cs

[code language=”csharp”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BuilderPatternSample
{
///
<summary>
/// Program class which demonstrates the builder usage
/// </summary>

class Program
{
///
<summary>
/// Main method of Program.cs
/// </summary>

/// <param name=”args”></param>
static void Main(string[] args)
{
TelevisionBuilder builder;

TelevisionManufacturer director = new TelevisionManufacturer();

builder = new FullHD40TVBuilder();
director.Construct(builder);
Television product1 = builder.Television;

Console.WriteLine(” ┌───────────────────────────────────Code:{0}───────────────────────────────┐”, product1.Code);
Console.WriteLine(” │ DisplayTechnology:{0} │”, product1.DisplayTechnology);
Console.WriteLine(” │ HDFormat:{0} │”, product1.HDFormat);
Console.WriteLine(” │ ScreenType:{0} │”, product1.ScreenType);
Console.WriteLine(” │ Size:{0} │”, product1.Size);
Console.WriteLine(” │ Feature:{0} │”, product1.Feature);
Console.WriteLine(” └─────────────────────────────────────────────────────────────────────────────────┘”);

builder = new SMARTLED54TVBuilder();
director.Construct(builder);
Television product2 = builder.Television;

Console.WriteLine(” ┌──────────────────────────────────Code:{0}──────────────────────────────┐”, product2.Code);
Console.WriteLine(” │ DisplayTechnology:{0} │”, product2.DisplayTechnology);
Console.WriteLine(” │ HDFormat:{0} │”, product2.HDFormat);
Console.WriteLine(” │ ScreenType:{0} │”, product2.ScreenType);
Console.WriteLine(” │ Size:{0} │”, product2.Size);
Console.WriteLine(” │ Feature:{0} │”, product2.Feature);
Console.WriteLine(” └─────────────────────────────────────────────────────────────────────────────────┘”);

builder = new Curved4K65LEDTVBuilder();
director.Construct(builder);
Television product3 = builder.Television;

Console.WriteLine(” ┌─────────────────────────────────Code:{0}────────────────────────────┐”, product3.Code);
Console.WriteLine(” │ DisplayTechnology:{0} │”, product3.DisplayTechnology);
Console.WriteLine(” │ HDFormat:{0} │”, product3.HDFormat);
Console.WriteLine(” │ ScreenType:{0} │”, product3.ScreenType);
Console.WriteLine(” │ Size:{0} │”, product3.Size);
Console.WriteLine(” │ Feature:{0} │”, product3.Feature);
Console.WriteLine(” └─────────────────────────────────────────────────────────────────────────────────┘”);

builder = new LCD22TVBuilder();
director.Construct(builder);
Television product4 = builder.Television;

Console.WriteLine(” ┌────────────────────────────────────Code:{0}─────────────────────────────────┐”, product4.Code);
Console.WriteLine(” │ DisplayTechnology:{0} │”, product4.DisplayTechnology);
Console.WriteLine(” │ HDFormat:{0} │”, product4.HDFormat);
Console.WriteLine(” │ ScreenType:{0} │”, product4.ScreenType);
Console.WriteLine(” │ Size:{0} │”, product4.Size);
Console.WriteLine(” │ Feature:{0} │”, product4.Feature);
Console.WriteLine(” └─────────────────────────────────────────────────────────────────────────────────┘”);

//Wait for UserInteraction
Console.ReadKey();

}
}

///
<summary>
/// Television – Product
/// </summary>

class Television
{
public string Code { get; set; }
public string DisplayTechnology { get; set; }
public string HDFormat { get; set; }
public string ScreenType { get; set; }
public string Size { get; set; }
public string Feature { get; set; }
}

///
<summary>
/// TelevisionBuilder – Builder
/// </summary>

abstract class TelevisionBuilder
{
protected Television television;

public abstract void SetCode();//ProductCode
public abstract void SetDisplayTechnology(); //LCD, LED, OLED, Plasma, CRT
public abstract void SetHDFormat(); // Full HD, HD Ready, Ultra HD, None
public abstract void SetScreenType(); //Curved, Flat, Standard
public abstract void SetSize(); // 22, 32, 40, 42, 54
public abstract void SetFeature(); //3D, Smart, Standard , HDMI Ports, USB Ports, Built in WIFI, Ethernet, Remote

//GetProduct
public Television Television
{
get { return television; }
}

}

///
<summary>
/// FullHD40TVBuilder – ConcreteBuilder1
/// </summary>

class FullHD40TVBuilder : TelevisionBuilder
{

public FullHD40TVBuilder()
{
television = new Television();
}

public override void SetCode()
{
television.Code = “FullHD40TV”;
}

public override void SetDisplayTechnology()
{
television.DisplayTechnology = “LCD”;
}

public override void SetHDFormat()
{
television.HDFormat = “FullHD”;
}

public override void SetScreenType()
{
television.ScreenType = “Flat”;
}

public override void SetSize()
{
television.Size = “40”;
}

public override void SetFeature()
{
television.Feature = “1 HDMI Ports, 1 USB Ports, Remote”;
}
}

///
<summary>
/// SMARTLED54TVBuilder – ConcreteBuilder2
/// </summary>

class SMARTLED54TVBuilder : TelevisionBuilder
{
public SMARTLED54TVBuilder()
{
television = new Television();
}

public override void SetCode()
{
television.Code = “SMARTLED54TV”;
}

public override void SetDisplayTechnology()
{
television.DisplayTechnology = “LED”;
}

public override void SetHDFormat()
{
television.HDFormat = “FullHD”;
}

public override void SetScreenType()
{
television.ScreenType = “Flat”;
}

public override void SetSize()
{
television.Size = “54”;
}

public override void SetFeature()
{
television.Feature = “2 HDMI Ports, 2 USB Ports, Built in WIFI, Ethernet, Remote”;
}
}

///
<summary>
/// Curved4K65LEDTVBuilder – ConcreteBuilder3
/// </summary>

class Curved4K65LEDTVBuilder : TelevisionBuilder
{
public Curved4K65LEDTVBuilder()
{
television = new Television();
}

public override void SetCode()
{
television.Code = “Curved4K65LEDTV”;
}

public override void SetDisplayTechnology()
{
television.DisplayTechnology = “LED”;
}

public override void SetHDFormat()
{
television.HDFormat = “4K Ultra HD”;
}

public override void SetScreenType()
{
television.ScreenType = “Curved”;
}

public override void SetSize()
{
television.Size = “65”;
}

public override void SetFeature()
{
television.Feature = “3 HDMI Ports, 2 USB Ports, Built in WIFI, Ethernet, Smart Remote”;
}
}

///
<summary>
/// LCD22TVBuilder – ConcreteBuilder4
/// </summary>

class LCD22TVBuilder : TelevisionBuilder
{
public LCD22TVBuilder()
{
television = new Television();
}

public override void SetCode()
{
television.Code = “LCD22TV”;
}

public override void SetDisplayTechnology()
{
television.DisplayTechnology = “LCD”;
}

public override void SetHDFormat()
{
television.HDFormat = “None”;
}

public override void SetScreenType()
{
television.ScreenType = “Flat”;
}

public override void SetSize()
{
television.Size = “22”;
}

public override void SetFeature()
{
television.Feature = “Remote”;
}
}

///
<summary>
/// TelevisionManufacturer – Director
/// </summary>

class TelevisionManufacturer
{
//Constructing Product
public void Construct(TelevisionBuilder televisionBuilder)
{
//Series of Complex Process
televisionBuilder.SetCode();
televisionBuilder.SetDisplayTechnology();
televisionBuilder.SetHDFormat();
televisionBuilder.SetScreenType();
televisionBuilder.SetSize();
televisionBuilder.SetFeature();
}
}
}
[/code]

Summary

In this article I have explained Builder Pattern with a simple C# application. I hope you have enjoyed this article and got some value addition to your knowledge. Please don’t forget to mark your votes, suggestions and feedback to improve the quality of this and upcoming articles.

Click here to Download Builder Pattern Sample – 10.2 KB

Learning Factory Pattern using C#

Introduction

Factory pattern is very common in programming. If you check .NET framework or any other frameworks Factory Pattern is widely used which shows its popularity. Factory Pattern belongs to Creational Patterns, and it deals with object creation. In this article we shall try to learn Factory Pattern using a simple C# console application.

Background

When we write codes we used to come across situations like creating objects based on some if conditions or switch case. If this object creation is not based on a proven design pattern then we are really making the object creation complex and future enhancements very tough. At this time we should consider Factory Pattern to abstract the complexity of the object creation logic, and enabling future additions hassle free.

Let’s take a very simple example of logging functionality in a project, If we had the implementation as below, then for adding a new Logging option requires considerable code changes at client code base which is not a good practice.

[code language=”csharp”]
public void Log(string message, string type)
{
switch (type)
{
case “Database”:
DatabaseLogger databaseLogger = new DatabaseLogger();
databaseLogger.Log(message);
break;
case “EventViewer”:
default:
EventViewerLogger eventviewerLogger = new EventViewerLogger();
eventviewerLogger.Log(message);
break;
}
}
[/code]

Factory Pattern is nothing but hiding object creation logic from the client so that the end client doesn’t have to worry about object creational logic, rather the client can refer the factory pattern created object using a common interface.

Using the code

For better understanding we can create a simple Logger Factory which will help the client to log messages to different options based on their choice.

Factory Pattern Sample Logger Factory

To start with, we need to create an Interface or abstract class as the base class for all classes which we are going to create instance in factory. Here I have used an Interface ILogger with a method Log message.

[code language=”csharp”]
interface ILogger
{
void Log(string Message);
}[/code]

Now we are going to implement this ILogger in all classes which we wanted to return from Logger Factory. Here ideally Log method should have the real method to log the message to a file but for demonstrating purpose I’m just adding a console message.

[code language=”csharp”]
class FileLogger : ILogger
{
public void Log(string Message)
{
Console.WriteLine(“{0} – Logged in File.”, Message);
}
}
[/code]

the same way implementing ILogger to DatabaseLogger, also Log method definition added.

[code language=”csharp”]
class DatabaseLogger : ILogger
{
public void Log(string Message)
{
Console.WriteLine(“{0} – Logged in Database.”, Message);
}
}
[/code]

EventViewerLogger also implemented from ILogger and Log method definition added based on the type. We can add new logger classes same as these logger classes.

[code language=”csharp”]
class EventViewerLogger : ILogger
{
public void Log(string Message)
{
Console.WriteLine(“{0} – Logged in EventViewer.”, Message);
}
}
[/code]

Create an enum to easily identify the LoggerType, In case if we have a new LoggerType then we can add it here.

[code language=”csharp”]enum LoggerType
{
File,
Database,
EventViewer
}[/code]

Finally we have reached to the LoggerFactory,now this factory will take care of the object creation based on the enum values, and will return the created instance back to client code which will be a type of ILogger.

[code language=”csharp”]
class LoggerFactory
{
public static ILogger Get(LoggerType type)
{
switch (type)
{
case LoggerType.Database:
return new DatabaseLogger();
case LoggerType.EventViewer:
return new EventViewerLogger();
case LoggerType.File:
default:
return new FileLogger();
}
}
}
[/code]

If you look at the above code you can see that the object creation logic is abstracted in the factory and the objects are created based the kind of object requested, as the return type is an Interface ILogger, the client code need not worry about new addition to the factory.

Have written a client code to make use of this factory as below,

[code language=”csharp”]static void Main(string[] args)
{
ILogger logger1 = LoggerFactory.Get(LoggerType.Database);
logger1.Log(“Message from Main”);

ILogger logger2 = LoggerFactory.Get(LoggerType.File);
logger2.Log(“Message from Main”);

ILogger logger3 = LoggerFactory.Get(LoggerType.EventViewer);
logger3.Log(“Message from Main”);

Console.ReadKey();

/*Output
Message from Main – Logged in Database.
Message from Main – Logged in File.
Message from Main – Logged in EventViewer.
*/
}[/code]

In the above code the client code uses the enum to request a specific object and using that object the log method is called. Objects are created using ILogger and instantiated using factory. Have given the output below,

FactoryPatter_Sample_Output.png

To explore this sample yourself you can download the attached code or create a console project named “FactoryPatternSample” and replace the content of Program.cs with below code block.

Program.cs

[code language=”csharp”]using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryPatternSample
{
class Program
{
interface ILogger
{
void Log(string Message);
}

enum LoggerType
{
File,
Database,
EventViewer
}

class FileLogger : ILogger
{
public void Log(string Message)
{
Console.WriteLine(“{0} – Logged in File.”, Message);
}
}

class DatabaseLogger : ILogger
{
public void Log(string Message)
{
Console.WriteLine(“{0} – Logged in Database.”, Message);
}
}

class EventViewerLogger : ILogger
{
public void Log(string Message)
{
Console.WriteLine(“{0} – Logged in EventViewer.”, Message);
}
}

class LoggerFactory
{
public static ILogger Get(LoggerType type)
{
switch (type)
{
case LoggerType.Database:
return new DatabaseLogger();
case LoggerType.EventViewer:
return new EventViewerLogger();
case LoggerType.File:
default:
return new FileLogger();
}
}
}

static void Main(string[] args)
{
ILogger logger1 = LoggerFactory.Get(LoggerType.Database);
logger1.Log(“Message from Main”);

ILogger logger2 = LoggerFactory.Get(LoggerType.File);
logger2.Log(“Message from Main”);

ILogger logger3 = LoggerFactory.Get(LoggerType.EventViewer);
logger3.Log(“Message from Main”);

Console.ReadKey();

/*Output
Message from Main – Logged in Database.
Message from Main – Logged in File.
Message from Main – Logged in EventViewer.
*/
}
}
}
[/code]

Summary

In this article I have explained Factory Pattern with a simple C# application. I hope you have enjoyed this article and got some value addition to your knowledge. Please don’t forget to mark your votes, suggestions and feedback to improve the quality of this and upcoming articles.

Click here to Download Factory Pattern Sample – 6.7 KB

WCF – REST enabled service

The WCF WEB HTTP Programming Model allows developers to expose Windows Communication Foundation (WCF) Web services through basic HTTP requests without requiring SOAP. The WCF WEB HTTP Programming Model is built on top of the existing WCF extensibility model. Using this article I’m going to explain how to create a REST enabled WCF Service. I have used a simple Patient Sevice to demonstrate the RESFful WCF Service.

What is REST

REST stands for REpresentational State Transfer. The term representational state transfer was introduced and defined in 2000 by Roy Fielding as a concept in his PhD dissertation . The REST is resource based, a resource can be a person, address, user etc and in a RESTful service we will be doing some operations on the resources. The constraints of REST are based on the same underlying principles that govern the Web. Those principles are,

  • User agents interact with resources, and resources are anything that can be named and represented. Each resource can be addressed via a unique Uniform Resource Identifier (URI).
  • Interaction with resources (located through their unique URIs) is accomplished using a uniform interface of the HTTP standard verbs (GET, POST, PUT, and DELETE). Also important in the interaction is the declaration of the resource’s media type, which is designated using the HTTP Content-Type header. (XHTML, XML, JPG, PNG, and JSON are some well-known media types.)
  • Resources are self-descriptive. All the information necessary to process a request on a resource is contained inside the request itself (which allows services to be stateless).
  • Resources contain links to other resources (hyper-media).

WCF and REST

WCF is the Microsoft framework for building applications that communicates over a network, regardless of the style or protocol. The WCF Services has the ability to expose REST services using System.ServiceModel.Web assembly. This ServiceModel gives you two attributes, WebGetAttribute and WebInvokeAttribute and a URI template mechanism that enables you to declare the URI and verb to which each method is going to respond.

Read more from CodeProject.com

WCF RESTful Service

WCF – Message Exchange Patterns (MEPs)

Message Exchange Pattern describes how the client and server should exchange messages, and also the MEP will make clear that the client is going to wait for any response from the service or just simply sending is enough ,or the client is expecting any callbacks from the service.

WCF supports three Message Exchange Patterns (MEPs). They are as follows.

Request-Reply

One-Way

WCF One-Way Message Exchange Pattern

Duplex

The below given diagram show how Duplex (One-Way) works.

Below given diagram shows how a Duplex (Request-Reply) MEP works,

Read more from CodeProject.com

 

WCF – Exception Handling, FaultException,FaultException and FaultContracts

Whenever we write a program we should expect the unexpected and add appropriate code to handle those exceptions.When we write a windows based application we use try/catch blocks in our methods to catch exceptions, and also we show a user friendly message in UI.

But when we work with WCF Service, It is not that much straight forward, So

  • How do we handle exceptions in WCF Service?
  • How to propagate a user-friendly error message to the client, who consumes the WCF Service?
  • How to send business rule validation messages to WCF client?

Handling exceptions in WCF Service is different than usual exceptions in .NET. As the WCF clients may not be based on .NET Technologies we cannot utilize the .NET Exception object to exchange exception details over the wire. For this purpose we should have a generic way to pass exception details to all type of clients, who consumes WCF Service.

For this reason we have SOAP faults, SOAP faults are the way to propagate the exceptions from the service to the client application. .Net has FaultException<T> generic class which can raise SoapFault exception. Service should throw FaultException<T> instead of usual CLR Exception object. T can be any type which can be serialized.

Read more form CodeProject.com

WCF FaultException Caught