Tuesday, 9 February 2016

Fault Contract - Handling Errors in WCF


Error Handling :

Whenever  we  writes a computer program we must curious about the Unexpected Exceptions.
An exception can  stops our entire program or may be it can cause performance degradation . So handling the exceptions are very important. In asp.net we have lot of exception handling mechanisms. But WCF is not that much straight forward.
The main problem is WCF is a service which is apart from our client so if any Exceptions are occurred in WCF code then we cannot able to find that through normal Exception handling in client side , if any error happens in our program then normally we need to propagate a user-friendly error message to the client, who consumes the WCF Service. For handling exceptions in WCF we are using Exception handling mechanism called Fault Contract
  
What is Fault Contract  ???

Fault Contract  is an exception handling mechanism which will help us to pass WCF Service errors/Exceptions to the client (Service consumer). In other words Fault Contract is mechanism to communicate error information between server and client
We can go through a simple example that demonstrate the use of Fault Contract .

Think in our WCF  Service Library we have a method like below
IService.cs

    [ServiceContract]
    public interface IService1
    {
       

        [OperationContract]
        int Divide(int Number1, int Number2);
    }
[DataContract]
    public class DivideClass
    {
        [DataMember]
        public  bool Result { get; set; }
        [DataMember]
        public  string ErrorMessage { get; set; }
        [DataMember]
        public  string ErrorDetails { get; set; }

    }
Service.cs
      public int Divide(int Number1,int Number2)
        {
            DivideClass objdiv = new DivideClass();
           
                int Result = Number1 / Number2;
                return Result;
           
        }
And we are try to use this service from a client like below
try
            {
                ExampleService.Service1Client obj = new ExampleService.Service1Client();
               
                int Result = obj.Divide(10, 0);
                            }
            catch (Exception e)
            {
           }
In the above code we are passing two variables 10,0 to the service and our service will divide the first number with second. Our second number is 0 so there should be a divided by zero exception. But we are using this service from a client so we don't have any idea about what is happening in WCF code, we don't have any information about the error and all. How can we get the error details from WCF??? for that purpose we are using Fault Contract.
See the below code
IService.cs

    [ServiceContract]
    public interface IService1
    {
       
        //Fault Contract Handling
        [OperationContract]
        [FaultContract(typeof(DivideClass))]
        int Divide(int Number1, int Number2);
    }

Service.cs
public int Divide(int Number1,int Number2)
        {
            DivideClass objdiv = new DivideClass();
            try
            {
                int Result = Number1 / Number2;
                return Result;
            }
            catch (Exception ex)
            {
                objdiv.Result = false;
                objdiv.ErrorMessage = "error occurred. Please try later.";
                objdiv.ErrorDetails = ex.ToString();
                throw new FaultException<DivideClass>(objdiv, ex.ToString());
            }
        }

In our Client Side
try
            {
               
                ExampleService.Service1Client obj = new ExampleService.Service1Client();
               
                int Result = obj.Divide(10, 0);
                            }
            catch (FaultException<ExampleService.DivideClass> Fex)
            {
                string ErrorDetails = Fex.Detail.ErrorMessage + "ErrorDetails::" +                Fex.Detail.ErrorDetails;
               
            }

Using the above method we can simply pass the error from WCF Service to our client (Service Consumer)



Thursday, 7 January 2016

Use of new,override and virtual In C#

C#, provide full support for object-oriented programming including encapsulation, inheritance, and polymorphism. As a beginners perspective the most confusing concept in C# is the use of keywords new,override,virtual.These keywords used in c# for achieving polymorphism.
The override modifier extends the base class method, and the new modifier hides it.
By using new, you are asserting that you are aware that the member that it modifies hides a member that is inherited from the base class, the new keyword explicitly hides a member that is inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base class version. Although you can hide members without using the new modifier, you get a compiler warning. If you use new to explicitly hide a member, it suppresses this warning.

We are going for detailed explanation and usage of new,virtual and override using some examples.

Note : Example programs are in asp.net MVC

Use of new Modifier

namespace TheCodeBehind
{
    public class TestingController : Controller
    {
       

        public ActionResult Testing()
        {

            CodeBehind cb = new CodeBehind();
            string MthodOnedata = cb.Firstmethod();
// will give : One
            InheritedOne io = new InheritedOne();
            string MthodTwodata = io.Firstmethod();
//will give : One

            return View();
        }

    }
  public   class CodeBehind
    {
      public string  Firstmethod()
      {
          return ("One");
      }
    }

  public class InheritedOne : CodeBehind
  {
  }
}

In the above code there is no issue, the issue comes when the derived class contains a function with same name, type and parameters. The below example describes it.


namespace TheCodeBehind
{
    public class TestingController : Controller
    {
      
        public ActionResult Testing()
        {

            CodeBehind cb = new CodeBehind();
            string MthodOnedata = cb.Firstmethod();
// will give :One
            InheritedOne io = new InheritedOne();
            string MthodTwodata = io.Firstmethod();
//it will give : Two
            return View();
        }

    }
  public   class CodeBehind
    {
      public string  Firstmethod()
      {
          return ("One");
      }
    }

  public class InheritedOne : CodeBehind
  {
      public string Firstmethod()
      {
          return ("Two");
      }
  }
}

Here Base class and Derived class have the same function Firstmethod().Because of inheritance the derived class get all the public,protected,internal and protected internal members from base class, in above case derived class have two methods with same type and name. So it will make confusion to the compiler, .net handles this by hiding the base class function using new modifier in derived class. If we are not using new modifiers then also .net automatically hides the base class method and  the code will compiled and executed but it shows a warning likes below.



To avoid this warning we are using the modifier new .it will hide the base class method. The following program explains how to use new modifier.

namespace TheCodeBehind
{
    public class TestingController : Controller
    {
      
        public ActionResult Testing()
        {

            CodeBehind cb = new CodeBehind();
            string MthodOnedata = cb.Firstmethod();
//One
            InheritedOne io = new InheritedOne();
            string MthodTwodata = io.Firstmethod();
//Two
            CodeBehind io1 = new InheritedOne();
            string MthodTwodata = io1.Firstmethod();
//One



            return View();
        }

    }
  public   class CodeBehind
    {
      public string  Firstmethod()
      {
          return ("One");
      }
    }

  public class InheritedOne : CodeBehind
  {
      public  new string Firstmethod()
      {
          return ("Two");
      }
  }
}

The above program will execute without any warning.

 Use of virtual and override
Virtual and override modifiers are used for achieving run time polymorphism in c#
In the above program
            CodeBehind io1 = new InheritedOne();
            string MthodTwodata = io1.Firstmethod();
//One
When we create an object for class InheritedOne with type of CodeBehind
And try to access the method using the object io1 then it will give the base class method .In order to override this base class method we are using virtual & override
Example:

namespace TheCodeBehind
{
    public class TestingController : Controller
    {
      
        public ActionResult Testing()
        {

            CodeBehind cb = new CodeBehind();
            string MthodOnedata = cb.Firstmethod();// One
            Console.WriteLine(MthodOnedata);
            InheritedOne io = new InheritedOne();
            string MthodTwodata = io.Firstmethod();//Two
            CodeBehind io1 = new InheritedOne();
            string MthodThreedata = io1.Firstmethod();//Two
          
            return View();
        }

    }
  public   class CodeBehind
    {
      public virtual string  Firstmethod()
      {
          return ("One");
      }
    }

  public class InheritedOne : CodeBehind
  {
      public  override string Firstmethod()
      {
          return ("Two");
      }
  }
}
The above example will override the base class function and results the derived class when we try to call like below

            CodeBehind io1 = new InheritedOne();
            string MthodThreedata = io1.Firstmethod();//Two

Points to remember:


  •  new modifier is used to achieve compile time polymorphism
  • virtual and override are used to achieve run time polymorphism 
  • We cannot override a non virtual method in c# until the method is not an abstract method.