Use of Fault Contract in WCF
What is the use of Fault Contract?
In ASP.Net, C# and VB.Net it's very simple to handle an exception just by adding the simple Try & Catch blocks. But when you talk about the WCF Service if an unexpected error occurs (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.
Fault Contract inherits from the FaultContractAttribute Class.
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
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
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
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);
}
}
}
}
Comments
Post a Comment