Skip to main content

Fault contract

 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.

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);

            }

        }
    }

 

Comments

Popular posts from this blog

Claims Class For security in .NET4.5 with C#

What is Claim ? A claim in the world of authentication and authorization can be defined as a statement about an entity, typically a user. A claim can be very fine grained: Ram is an admin Ram’s email address is Ram@yahoo.com Ram lives in Mumbai Tom’s allowed to view sales figures between 2009 and 2012 Tom’s allowed to wipe out the universe Claims originate from a trusted entity other than the one that is being described. This means that it is not enough that Tom says that he is an administrator. If your company’s intranet runs on Windows then Tom will most likely figure in Active Directory/Email server/Sales authorisation system and it will be these systems that will hold these claims about Tom.  The idea is that if a trusted entity such as AD tells us things about Tom then we believe them a lot more than if Tom himself comes with the same claims . This external trusted entity is called an  Issuer . The KEY in the key-value pairs is called a  Typ...

Design Patterns

                                                      Design pattern 1. Factory Design Pattern  In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface. Step 1 Create an interface IShape.cs public interface I Shape { void draw (); } Step 2 Create concrete classes implementing the same interface. Rectangle.cs public class Rectangle : I Shape { @Override public void draw () { C onsole.WriteLine ( "Inside Rectangle::draw() method." ); } } Square.cs public class Square : I Shape { @Override public void draw () { C onsole.WriteLine ( "Inside Square::draw() method." ); } } Circle.cs public class Circle : I Shape { @Override public void draw () ...

Paytm integration

How to integrate Paytm to asp.net site   You will need to create an Checksum on your server. Kindly refer the dll file for the attachment.  Usage of CheckSum API: ·         Add provided “paytm.dll” as a “Reference” in your project. ·         Import namespace “paytm” in your Class with statement “using paytm”. ·         Now Generate CheckSum API as well as Verify CheckSum API are available as follows: o   String CheckSum.generateCheckSum(String masterKey, Dictionary<String, String> parameters) o   Boolean CheckSum.verifyCheckSum(String masterKey, Dictionary<String, String> parameters, StringcheckSum) ·         For Generating CheckSum, use following snippet code: String masterKey = “merchantKey” ; Dictionary<String, String> parameters = new Dictionary<string, string>(); p...