Sunday, March 24, 2013

Fault Contract in WCF

Fault Contract in WCF :

For Handling Exception in WCF , we need to use fault contract
here sample example of fault contract



ex :

In Interface (IService.cs)

using System;
using System.Collection.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Net.Security;


Public interface IService1
{
[OperactionContract]
[FaultContractAttribute(typeof(CustomException), Action="Custom Exception")]
string SampleMethod(string message);
}

[DataContractAttribute]
Public class CustomeException
{
private string report;
public CustomException(string message)
{
this.report=message;
}
[DataMemberAttribute]
Public string Message
{
get{return this.report;}
set{this.report =value;}
}

}

In Service.cs

using System;
using System.Collection.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Net.Security;

Public class Service1: IService1
{

  public string SampleMethod(string msg)
 {
   try
      {
          string strNumber =string.Empty;
          int? num3 =null;
         strNumber=num3.ToString();
         num3=Convert.ToInt16(strNumber);
      }
     catch(Exception ex)
       {
        msg=ex.Message;
        throw new FaultException<CustomException> (new CustomException("SampleMethod : Error Occured -" +msg));

       }
return "The Service successfully returned : " +msg;
 }


In Client Class


 private void GetAdd()
    {
        string msg = string.Empty;
        try
        {
            msg = "hello";
            ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client();
            string name = proxy.SampleMethod(msg);
        }
        catch (FaultException<ServiceReference1.CustomException> ex)
        {
            string message = ex.Detail.Message;
            Response.Write(message);
        }
    }





Amazon.in


Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages

Offers