Tuesday, February 14, 2012

Handling WCF FaultContract & FaultException in Silverlight

What is FaultContract in WCF and how to handle fault exception in a windows application has been posted 1 year ago in this same blog itself. Some time back we one of colleague was trying to implement the same in his Silverlight application and he was not able to leverage my post to accomplish his task as Silverlight uses async pattern to call the service and the binding is basicHttp. The basicHttpBinding uses the SOAP protocol and it returns the fault using the HTTP 500 series status code which cannot be understood by Silverlight. So we modify the WCF response using custom EndPointBehavior and a MessageInspector to return using HTTP 200 code.

All those details are specified in the MSDN itself. What I am doing here is to post a sample in Silverlight 4.0 :-)
http://msdn.microsoft.com/en-us/library/ee844556(v=vs.95).aspx

No its not just a sample. It describes how to write client side code which is not mentioned in the MSDN article.Mainly where to put try catch to catch the fault exception. For the server side code and configurations just look at the MSDN article. Client side code you can get from below section.


   1:  private void GetChar(String ipString, int position)
   2:  {
   3:          MyServiceReference.MyServiceClient client = new MyServiceReference.MyServiceClient();
   4:          client.GetCharCompleted += (sender, e) =>
   5:          {
   6:              try
   7:              {
   8:                  if (e.Error != null) throw e.Error;
   9:                  MessageBox.Show("Extracted character: " + e.Result.ToString());
  10:              }
  11:              catch (FaultException<MyServiceReference.MyException> ex)
  12:              {
  13:                  MessageBox.Show("FaultException occurred " + ex.Detail.ExMessage);
  14:              }
  15:              catch (FaultException ex)
  16:              {
  17:                  MessageBox.Show(ex.Message);
  18:              }
  19:          };
  20:          client.GetCharAsync(ipString, position);
  21:  }

The main difference is the position of try catch blocks .In the sync service calls it will be wrapping the service call itself.Here we have 2 ways as the exception comes through the e.Error property.Either we can check the type in the handler itself or throw to handle by the callers.

No comments: