How to Implement Fault Contract in WCF

What is fault Contract?

A Fault Contract is a way to handle an error/exception in WCF. In C# we can handle the error using try and catch blocks at the client side. The purpose of a Fault Contract is to handle an error by the service class and display in the client side. Whenever the client makes a call to a service class and an unexpected exception comes such as, SQL Server is not responding, or Divide by zero; in this case the service class throws an exception to the client using the Fault Contract.

By default when we throw an exception from a service, it will not reach the client. WCF provides the option to handle and convey the error message to the client from a service using a SOAP Fault Contract.

To support SOAP Faults, WCF provides the FaultException class. This class has two forms:

  1. FaultException: to send an untyped fault back to the caller
  2. FaultException<T>: to send a typed fault data to the client. It is basically a Generic Type.

Syntax

    [OperationContract]
    [FaultContract(typeof(MyException))]
    string getDetails(int value);


The Fault Contract sample demonstrates how to communicate error information from a service to a client. The sample is based on the, with some additional code added to the servie to convert an internal exception to a fault.

What is the use of FaultContract?

In ASP.Net, C# and VB.Net it's very simple to hande an exception just by adding the simple Try & Catch blocks. But when you talk about the WCF Service if an unexpected error occurrs (like Server not responding properly and divide by zero) in a WCF Service then the exception details can be passed to the client using a Fault Contract.

FaultContract inherits from the FaultContractAttribute Class.

WCF.jpg

Now we are going to implement the Fault Contract with database connectivity

Step 1: Database Setup

Create a table named EMPLOYEE with column names EMP_ID and EMP_NAME. We will create a service to input the user id and get the name of the employee.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO

CREATE TABLE [DBO].[EMPLOYEE](

          [EMP_ID] [INT] NULL,

          [EMP_NAME] [VARCHAR](50) NULL

) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO

INSERT INTO EMPLOYEE(EMP_ID,EMP_NAME)

VALUES(1,'AMIT')

INSERT INTO EMPLOYEE(EMP_ID,EMP_NAME)

VALUES(2,'KIRTI')


Step 2: Open Visual Studio then select "File" -> "New" -> "Project..." -> "WCF" -> "WCF Service Application".

1. Create IService.cs and Service.cs.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

[ServiceContract]

public interface IService

{

    [OperationContract]

    [FaultContract(typeof(MyException))]

    string getDetails(int value);

}

[DataContract]

public class MyException

{

    private string strReason;

    public string Reason

    {

        get { return strReason; }

        set { Reason = value; }

    }

}

Service.cs
 

    public class Service : IService

    {

 

        public string GetData(int value)

        {

            return string.Format("You entered: {0}", value);

        }

 

        string r = null;

 

        public string getDetails(int id)

        {

            try

            {

 

                SqlConnection con = new SqlConnection(@"Data Source=AMIT-PC\MIND;Initial Catalog=wcf;Integrated Security=False;uid=sa;pwd=Mind1234");

                con.Open();

                SqlCommand cmd = new SqlCommand("SELECT EMP_NAME FROM EMPLOYEE WHERE EMP_ID= " + id + "", con);

                SqlDataReader rd = cmd.ExecuteReader();

                while (rd.Read())

                {

                    if (rd == null)

                    {

 

                    }

                    else

                    {

                        r = rd["EMP_NAME"].ToString();

                    }

 

                }

                return r;

            }

            catch (Exception e)

            {

                MyException m = new MyException();

                m.Reason = "Some Problem";

                throw new FaultException<MyException>(m);

 

            }

 

        } 
    }

 

Up Next
    Ebook Download
    View all
    Learn
    View all