Fault Contract Exception in WCF Hosted on Web App


Fault Contract Exception in WCF Hosted on Web App

Today, in this article let's try to study and implement this interesting concept. It enables to show a friendly message to user when  unexpected values are inputted. It works great. So, we all are good to go and implement this wonderful concept.

Question Arises: What is Fault Contract?

Let's understand this Definition according to scenario wise:

Think for the scenario the client makes some request to WCF Service and WCF Service overlooks at the received request from client. So while processing the request based on user inputted values, in some cases there might be chance of occurrence of errors on service for incorrect inputted values by client. So when the service sends some exception to client, it is not effectively received. So WCF Service provides an effective way of delivering the error message to the client by the usage of FAULT CONTRACT. So, if we implement this we can get a better idea on this:

So, let's get ready to implement this very useful concept.

The Complete Code of IService1.cs looks like this:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

namespace FaultContractException

    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.

    [ServiceContract] public interface IService1

    { [OperationContract] [FaultContract(typeof(Arthimetic))] double add(double a, double b);

    }

}

 

The Complete Code of Service1.svc looks like this:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel; using System.ServiceModel.Web;

using System.Text;

using System.Threading;

 

namespace FaultContractException

{

    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.

   

    public class Service1 : IService1

   

    {

        public double add(double a, double b)

        {

            try {

                if (b == 0) { var objArthimetic = new Arthimetic();

                objArthimetic.Exception = "Fault Contract Exception"; objArthimetic.MethodName = "Add";

                    throw new FaultException<Arthimetic>(objArthimetic, "<b><i>Cannot Divide by zero");

                }

            } catch (DivideByZeroException) { } return a/b;

        }

    }

}

The Complete Code of Web.Config looks like this:

<?xml version="1.0"?>

<configuration>

       <system.web>

              <compilation debug="true" targetFramework="4.0" />

       </system.web>

       <system.serviceModel>

              <behaviors>

                     <serviceBehaviors>

                           <behavior>

                                  <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->

                                  <serviceMetadata httpGetEnabled="true"/>

                                  <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->

                                  <serviceDebug includeExceptionDetailInFaults="false"/>

                           </behavior>

                     </serviceBehaviors>

              </behaviors>

              <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

       </system.serviceModel>

       <system.webServer>

              <modules runAllManagedModulesForAllRequests="true"/>

       </system.webServer>

</configuration>

The Complete Code of WebForm1.aspx looks like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Fault.WebForm1" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:ScriptManager ID="ScriptManager1" runat="server">

        </asp:ScriptManager>

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">

            <ContentTemplate>

                <center>

                    <table>

                        <tr>

                            <td>

                                <asp:Label ID="Label1" runat="server" Text="Please Enter First Number" Font-Bold="true"

                                    Font-Italic="true" Font-Size="Larger" ForeColor="Brown"></asp:Label>

                            </td>

                            <td>

                                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

                            </td>

                        </tr>

                        <tr>

                            <td>

                                <asp:Label ID="Label2" runat="server" Text="Please Enter Second Number" Font-Bold="true"

                                    Font-Italic="true" Font-Size="Larger" ForeColor="Brown"></asp:Label>

                            </td>

                            <td>

                                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

                            </td>

                        </tr>

                        <tr>

                            <td>

                            </td>

                            <td>

                                <asp:Button ID="Button1" runat="server" Text="Click Here" BackColor="CadetBlue" OnClick="Button1_Click" />

                            </td>

                        </tr>

                    </table>

                    <table>

                        <tr>

                            <td>

                            </td>

                            <td>

                                <asp:Label ID="Label3" runat="server" Visible="false" ForeColor="Brown" Font-Size="Large"></asp:Label>

                            </td>

                        </tr>

                    </table>

                </center>

            </ContentTemplate>

        </asp:UpdatePanel>

    </div>

    </form>

</body>

</html>

 

The Complete Code of WebForm1.aspx.cs looks like this:

using System;

using System.Collections.Generic;

using System.Linq;

using System.ServiceModel;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using Fault.ServiceReference1;

namespace Fault

{

    public partial class WebForm1 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

 

        }

 

        protected void Button1_Click(object sender, EventArgs e)

        {

 

            try

            {

                if (TextBox1.Text == "" || TextBox2.Text == "")

                {

                    Label3.Text = "<center><b><i>Please Enter Data";

                    Label3.Visible = true;

                }

                else

                {

 

                    var objClient = new Service1Client();

                    Label3.Text = ("<center> The Result of the Values is <b>" + objClient.add(Convert.ToDouble(TextBox1.Text), Convert.ToDouble(TextBox2.Text)) + "</b></center>");

                    Label3.Visible = true;

                    TextBox1.Text = "";

                    TextBox2.Text = "";

                }

 

 

            }

            catch (FaultException<Arthimetic> exception)

            {

 

                Label3.Text = ("<center>FaultException<Arthimetic>: Arthimetic fault while doing " + exception.Message);

                Label3.Visible = true;

 

            }

 

        }

    }

}

 

The Output of the Application looks like this:

fig 1.gif

The Output of the Application When Fault Contract Exception Arises looks like this:

fig 2.gif

The Nothing Entered Values Output looks like this:

fig 3.gif

I hope this article is useful for you. I look forward for your comments and feedback.


Similar Articles
MVC Corporation
MVC Corporation is consulting and IT services based company.