Fault Contract in WCF – Exception Handling using Fault Contract

By adminLast updated: Sunday, December 22, 2013 • Save & ShareLeave a Comment

Fault Contract In WCF

Fault Contract in WCF – Sample Download

Fault Contract in WCF – Interview Questions and Answers and other interview Questions



For the beginners to WCF the toughest question is, what is fault contract in WCF ? Is it one of the important concept in WCF?  Why frequently asked by interviewers ?


In fact the answer is very easy Handling the service side exceptions nothing but a Fault Contract in WCF. It is always very important that exception occurred at WCF service side need to carry to client side (who is consumed the service)

For example in C# if you get a Divide by Zero exception how do you handle in C# in simplest way by using Try { } and Catch(Exception ex) {}

But for handling the Service Side exceptions we need to understand what is FaultContract attribute and what is the FaultException class.

Below this concept clearly explained step by step with complete screen shots and find the source code like above.

FaultContract in WCF:

However we have ServiceContract, DataContract, OperationContract like wise we have Fault Contract in WCF. You have to decorate Fault Contract attribute to the definition of the operation contract method.

Now we are going to see simple example. In this example I am going create two projects.

 

Sample code:

In below code AddCustomer() has been decorated by Service Contract attribute. It taking Customer Details and return’s a Boolean value if customer added successfully. Here if you have to decorate the Fault Contract attribute on top of the AddCustomer() method. Here it is mandatory to put a DataContract class in Fault Contract attribute.

[ServiceContract]

public interface ICustomerService

{

[OperationContract]

//Here you have to and Fault Contract in WCF service interface.

[FaultContract(typeof(CustomerDetails))]
bool
AddCustomer(CustomerDetails customerDtls);

}

It has the below DataContract class with properties Customer Name, Customer Address, Error Message and Error Id decorated with DataMember attribute.

 

[DataContract]
public class CustomerDetails
{

[DataMember]
public string CustomerName { get; set;}

[DataMember]

public string CustomerAddress { get; set; }

[DataMember]

public string ErrorMessage { get; set;}

[DataMember]

public string ErrorId { get; set;}
}

Implementation of CustomerService Class (CustomerService.svc)

Here you are throughing exception when Customer Name or Customer Address is null. In some of the scenario’s like  SQL server downtime problems/Data overflow we have to changing Error Message and Error Id. Fault Exception tightly related to Fault Contract in WCF. Without Fault Contract attribute client can not catch Fault Exception.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.Data.SqlClient;

using System.ServiceModel;

using System.Text;

namespace Fault_Contract_In_WCF

{

public class CustomerService : ICustomerService

{

public bool AddCustomer(CustomerDetails customerDtls)

{

try

{

if (string.IsNullOrEmpty(customerDtls.CustomerName ))

{

customerDtls.ErrorId = “E110″;

customerDtls.ErrorMessage = “Customer name can not be null”;

throw new FaultException<CustomerDetails>(customerDtls);

}


if (string.IsNullOrEmpty(customerDtls.CustomerAddress))

{

customerDtls.ErrorId = “E111″;

customerDtls.ErrorMessage = “Customer number can not be null”;

throw new FaultException<CustomerDetails>(customerDtls);

}


string sqlCommand=string.Format(“insert into tblCustomerDetails(CutomerName,CustomerAddress) values(‘{0}’,'{1}’)”,customerDtls.CustomerName.Trim(),customerDtls.CustomerAddress.Trim());


using (SqlConnection con=new
SqlConnection
(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))

{

//con.Open();
using (SqlCommand cmd = new SqlCommand(sqlCommand,con))

{

cmd.ExecuteNonQuery();

return true;
}

}

}


catch (Exception ex)

{

if (string.IsNullOrEmpty(customerDtls.ErrorId) && string.IsNullOrEmpty(customerDtls.ErrorMessage))

{

//For connection failures or any other
exceptions it will handle genericlly

customerDtls.ErrorId = “E112″;
customerDtls.ErrorMessage = ex.Message;


}


throw new FaultException<CustomerDetails>(customerDtls);


}


}

}

}

Client Side Implementation:

Here you need to create object for Service class and assign all the properties to DataContract class(CustomerDetails) and call the AddCustomer Method.

try  {

 

CustomerServiceClient client =new CustomerServiceClient();

CustomerDetails cusDetails =new CustomerDetails();

cusDetails.CustomerName = txtCustomerName.Text.Trim();

cusDetails.CustomerAddress = txtCustomerAddress.Text.Trim();

bool flag=client.AddCustomer(cusDetails);

if(flag) {

          MessageBox.Show(“Customer added successfully”);

   }

}

catch (FaultException<CustomerDetails> ex) {

MessageBox.Show(string.Format(“Error Ocuured: Error Id:{0} and Error Message:{1}”, ex.Detail.ErrorId,
ex.Detail.ErrorMessage));
}

Step By Step Implementation

 

Step 1: Open the Visual Studio and Create a New Project

Step 2: Select the WCF Template and Name the project Fault_Contract_In_WCF

Fault Contract in WCF

Step 3: Rename the service Service1 to CustomerService. Open CustomerService.SVC markup and change new class name with namespace for Service attribute in ServiceHost

Fault Contract in WCF

 

Fault Contract in WCF

Step 4: Define the AddCustomer() method in the ICustomerService interface. Here it is mandatory to define FaultContract attribute with type of CustomerDetails class. Fault Contract in WCF topic related questions and answers covered in another blog. Please find the link above.

Fault Contract in WCF

Step 5: Implement the ICustomerService in CustomerService class.

 

Check the Service in Browser.

Step 6: Test the service by using View in Browser option.

Check the Service in Browser.

 

Step 7: Test the service by using View in Browser option.
View in browser

Step 8: Create the Client/Consumer Project(Windows Project)

 

Fault Contract in WCF - Client

Step 9: Create a Design to Enter Customer Name and Customer Address.
Design to Enter Customer Name and Customer Address

Step 10: Add Service Reference to the Windows project.
Check the Service in Browser.

 

Step 11: Click on Discover Button. It will show available WCF service. Change the Reference name and click OK button
Check the Service in Browser.

 

Step 12: In Button click event write code to call AddCustomer() Method by passing customer details object.
Check the Service in Browser.

Step 13: Set the Windows project as start up project. Run the application by using F5 keyword.
Run the application by using F5 keyword.

Step 14: Don’t provide any customer name and address. Click on Add customer button. Message box show’s Fault Exception details
Click on Add customer button. Message box show's Fault Exception details.

 

Summary:
As mentioned above Fault Contract in WCF is very important. If we want to pass exceptions occurred at service side to client we need to use Fault Contracts.
You can through logical exceptions, Business exceptions& expected exceptions by using Fault Exception. Download source code here

Interview questions on this topic
Refer more on Fault Contract in WCF topic

Leave a Reply