Handling Exception in Silverlight application from WCF

Handling Exception in Silverlight application from WCF



This article explains about handling the exception in

Silverlight application from WCF. I have created the sample Silverlight application, which uses the WCF service for process the data. While testing the application I came to know that exception message thrown from WCF cannot be received at the client side(Silverlight application) even after using the FaultException. I was always getting System.ServiceModel.CommunicationException: The remote server returned an error: NotFound.


Later I came to know that WCF throws the HTTP 500 series Fault message but Silverlight can handle only 200 series. So we need to convert the 500 series to 200 error message for Silverlight. Here is the sample application for exception handling between WCF and Silverlight.

Step 1: We can customize the Endpoint behavior of the WCF service by inheriting the Beha and implementing the IEndpointBehavior. Actual code for converting the 500 error serice to 200 serivce in BeforeSendReply method.

Create a ClassLibrary project and name it as “S

ilverlight_WCF_FaultBehavior” and name the class as “SilverlightFaultBehavior”. Copy and paste the follwing code inside the SilverlightFaultBehavior class.

Imports System.ServiceModel.ConfigurationrviceModel.Configuration
Imports System.ServiceModel.Description Imports System.ServiceModel.Dispatcher
Imports System.ServiceModel.Channels Imports System.ServiceModel
Public Class SilverlightFaultBehavior
Inherits BehaviorExtensionElement Implements IEndpointBehavior
Public Overrides ReadOnly Property BehaviorType() As System.Type
Get Return GetType(SilverlightFaultBehavior)
End Get End Property
Protected Overrides Function CreateBehavior() As Object
Return New SilverlightFaultBehavior End Function
Public Sub AddBindingParameters(ByVal endpoint As ServiceEndpoint,
ByVal bindingParameters As BindingParameterCollection)
Implements IEndpointBehavior.AddBindingParameters End Sub
Public Sub ApplyClientBehavior(ByVal endpoint As ServiceEndpoint,
ByVal clientRuntime As ClientRuntime)
Implements IEndpointBehavior.ApplyClientBehavior End Sub
Public Sub ApplyDispatchBehavior(ByVal endpoint As ServiceEndpoint,
ByVal endpointDispatcher As EndpointDispatcher) Implements IEndpointBehavior.ApplyDispatchBehavior Dim inspector As New SilverlightFaultMessageInspector() endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector) End Sub Public Sub Validate(ByVal endpoint As ServiceEndpoint) Implements IEndpointBehavior.Validate End Sub Public Class SilverlightFaultMessageInspector Implements IDispatchMessageInspector Public Function AfterReceiveRequest(ByRef request As Message, ByVal channel As IClientChannel, ByVal instanceContext As InstanceContext) As Object Implements IDispatchMessageInspector.AfterReceiveRequest ' Do nothing to the incoming message. Return Nothing End Function Public Sub BeforeSendReply(ByRef reply As System.ServiceModel.Channels.Message, ByVal correlationState As Object) Implements IDispatchMessageInspector.BeforeSendReply If reply.IsFault Then Dim [property] As New HttpResponseMessageProperty() ' Here the response code is changed to 200. [property].StatusCode = System.Net.HttpStatusCode.OK reply.Properties(HttpResponseMessageProperty.Name) = [property]
End If
End Sub End Class End Class

Note: Highlighted code shows the conver

sion for 500 serices to 200 series error code.

Step 2: Build the project

Step 3: Create a new WCF service with Interface and implementation class as follows

Interface

<ServiceContract()> _ Public Interface IService  
<OperationContract()> _ Function Add(ByVal num1 As Integer,
ByVal num2 As Integer) As Integer <OperationContract()> _
Function Subtract(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
End Interface

Implementation

Public Class Service     Implements ISe
rvice      Public Sub New()     End Sub     
Public Function Add(ByVal num1 As Integer, ByVal num2 As Integer)
As Integer Implements IService.Add
Throw New FaultException("Error thrown by user for Add operation")
'Return num1 + num2 End Function
Public Function Subtract(ByVal num1 As Integer,

ByVal num2 As Integer) As Integer Implements IService.Subtract
Return num1 - num2 End Function End Class
< Add the Silverlight_WCF_FaultBehavior project dll as reference to WCF Service

Step 5:

Step 5: In WCF we can extend the bin ding and behavior by using <extention> tag. In our case also we are extending the custom endpoint behavior as shown below. In the <behaviorExtensions> tag we need specify the fully qualified name of the cutom behaviour assembly.

Modify the Web.config file as shown be llow

<system.serviceModel>     <services>     
<service name="Service" behaviorConfiguration="ServiceBehavior">
<!-- Service Endpoints -->
<endpoint address="" binding="basicHttpBinding" contract="IService"
behaviorConfiguration="SilverlightFaultBehavior"> <!--
Upon deployment, the following identity element should be removed or replaced
to reflect the identity under which the deployed service runs. If removed,
WCF will infer an appropriate identity automatically.-->
<identity> <dns value="localhost"/>
</identity> </endpoint>
<
endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange"/> </service>
<
/services> <behaviors> <serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- 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>
<endpointBehaviors> <behavior name="SilverlightFaultBehavior">
<silverlightFaults/> </behavior>
</endpointBehaviors
> </behaviorss=“BlueCode”>>
<extensions> <behaviorExtensions>
<add name="silverlightFaults"
type="Silverlight_WCF_FaultBehavior.SilverlightFaultBehavior,
Silverlight_WCF_FaultBehavior, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null"/> </behaviorExtensions
>
<
/extensionss=“BlueCode”>> </system.serviceModel>

Step 6: Create the any sample silverlight application as “Silverlight_WCF_Exception” and add this WCF service as Service Reference.

url: http://localhost/MathService/S ervice.svc

Step 7: Add a button to the MainPage.xaml and call the WCF method as shown below

    Private Sub Button_Click(ByVal     sender As System.Object,                            
ByVal e As System.Windows.RoutedEventArgs)
Dim proxy As New ServiceProxy.ServiceClient
AddHandler proxy.AddCompleted, AddressOf AddOperationCompleted
proxy.AddAsync(5, 6) End Sub
Private Sub AddOperationCompleted(ByVal sender As Object, ByVal e As ServiceProxy.AddCompletedEventArgs) If e.Error IsNot Nothing Then MessageBox.Show(e.Error.Message) Else MessageBox.Show(e.Result) End If End Sub Step 8: Output will look like this

   

Step 8: Output will look like this




Introdution to WCF 4.0

Introdution to WCF 4.0

This article explains about the new features introduced in WCF 4.0.

.Net framework comes with new features and im

proved areas of WCF. It was mainly focused on simplifying the developer experience, enabling more communication scenario and providing rich integration with WWF.

The following items specifies the new features of WCF 4.0

Simplified configuration

This new feature shows simplification of WCF configuration section by providing default endpoint, binding and behavior configuration. It is not mandatory to provide endpoint while hosting service. Service will automatically create new endpoint if it does find any endpoint while hosting service. These changes make it possible

to host configuration-free services.

Discovery service

There are certain scenario in which endpoint address of the service will be keep on changing. In that kind of scenario, client who consume this service also need to change the endpoint address dynamically to identify the service. This can b

e achieved using WS-Discovery protocol.

Routing service

This new feature introduces routing service between client and actual business service. This intermediated service Act as broker or gateways to the actual business services and provides features for content based routing, protocol bridging and error handling

REST Service

There are few features helps while developing RESTful service.

  • Automatic help page that describes REST services to consumer
  • Support for declarative HTTP catching

Workflow service

  • Improves development experience
  • Entire service definition can be define in XAML
  • Hosting workflow service can be done from .xamlx file, without using .svc file
  • Introduce new “Context” bindings like BasicHttpContextBinding, WSHttpContextBinding, or NetTcpContextBinding
  • In .Net4.0, WorkflowServiceHost class for hosting workflow services was redesigned and it is available in System.ServiceModel.Activities assembly. In .Net3.5, WorkflowServiceHost class is available in System.WorkflowServices assembly
  • New messaging activities SendReply and ReceiveReply are added in .Net4.0

Conclusion:

This article explain new featues introduced in WCF 4.0

IIS 5/6 Hosting in WCF


IIS 5/6 Hosting

The main advantage of hosting service in IIS is that, it will automatically launch the host process when it gets the first client request. It uses the features of IIS such as process recycling, idle shutdown, process health monitoring and message based activation. The main disadvantage of using IIS is that, it will support only HTTP protocol.

Let as do some hands on, to create service and host in IIS

Step 1:Start the Visual Studio 2008 and click File->New->Web Site. Select the 'WCF Service' and Location as http. This will directly host the service in IIS and click OK.







Step 2: I have created sample HelloWorld service, which will accept name as input and return with 'Hello' and name. Interface and implementation of the Service is shown below.

IMyService.cs
[ServiceContract] public interface IMyService {     [OperationContract]   
string HelloWorld(string name); }
MyService.cs
public class MyService : IMyService {      #region IMyService Members    
public string HelloWorld(string name) { return "Hello " + name; } #endregion }

Step 3: Service file (.svc) contains name of the service and code behind file name. This file is used to know about the service.

MyService.svc
<%@ ServiceHost Language="C#" Debug="true"
Service="MyService" CodeBehind="~/App_Code/MyService.cs" %>

Step 4: Server side configurations are mentioned in the config file. Here I have mention only one end point which is configured to 'wsHttpBinding', we can also have multiple end point with differnet binding. Since we are going to hosted in IIS. We have to use only http binding. We will come to know more on endpoints and its configuration in later tutorial. Web.Config

<system.serviceModel>   <services>    
<
service behaviorConfiguration="ServiceBehavior"
name="MyService"> <endpoint
address="http://localhost/IISHostedService/MyService.svc"
binding="wsHttpBinding" contract="IMyService"> <identity>
<dns value="localhost"/> </identity> </endpoint>
<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange"/> </service>
</services> <behaviors> <serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- 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> </system.serviceModel>
Note:

You need to mention the service file name, along with the Address mention in the config file. IIS Screen shot



Step 5: Now we successfully hosted the service in IIS. Next we have to consume this service in client application. Before creating the client application, we need to create the proxy for the service. This proxy is used by the client application, to interact with service. To create the proxy, run the Visual Studio 2008 command prompt. Using service utility we can create the proxy class and its configuration information.

svcutil  http://localhost/IISHostedService/MyService.svc






After executing this command we will find two file generated in the default location.

  • MyService.cs - Proxy class for the WCF service

  • output.config - Configuration information about the service.

Step 6: Now we will start creating the Console application using Visual Studio 2008(Client application).




Step 7: Add the reference 'System.ServiceModel'; this is the core dll for WCF.


Step 8: Create the object for the proxy class and call the HelloWorld method.

static void Main(string[] args)         {          
//Creating Proxy for the MyService
MyServiceClient client = new MyServiceClient();
Console.WriteLine("Client calling the service...");
Console.WriteLine(client.HelloWorld("Ram"));
Console.Read(); }

Step 9: If we run the application we will find the output as shown below.





I hope you have enjoyed the Service hosted in IIS. Now let start the look on the self hosted service.

WCF Hosting

WCF Hosting

In this part of the tutorial we are going to see the four different way of hosting the WCF service. WCF service cannot exist on its own; it has to be hosted in windows process called as host process. Single host process can host multiple servers and same service type can be hosted in multiple host process. As we discussed there are mainly four different way of hosting the WCF service.

Multiple hosting and protocols supported by WCF.Microsoft has introduced the WCF concept in order to make distributed application development and deployment simple.

Hosting Environment Supported protocol
Windows console and form application HTTP,net.tcp,net.pipe,net.msmq
Windows service application (formerly known as NT services) HTTP,net.tcp,net.pipe,net.msmq
Web server IIS6 http, wshttp
Web server IIS7 - Windows Process Activation Service (WAS) HTTP,net.tcp,net.pipe,net.msmq

A summary of hosting options and supported features.

Feature Self-Hosting IIS Hosting WAS Hosting
Executable Process/ App Domain Yes Yes Yes
Configuration App.config Web.config Web.config
Activation Manual at startup Message-based Message-based
Idle-Time Management No Yes Yes
Health Monitoring No Yes Yes
Process Recycling No Yes Yes
Management Tools No Yes Yes

WCF Architecture




Contracts

Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.

Service contracts

- Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.

Data contract

- It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.

Message Contract

- Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Policies and Binding

- Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.

Service Runtime

- It contains the behaviors that occur during runtime of service.

  • Throttling Behavior- Controls how many messages are processed.
  • Error Behavior - Specifies what occurs, when internal error occurs on the service.
  • Metadata Behavior - Tells how and whether metadata is available to outside world.
  • Instance Behavior - Specifies how many instance of the service has to be created while running.
  • Transaction Behavior - Enables the rollback of transacted operations if a failure occurs.
  • Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.

Messaging

- Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as

  • Transport Channels

    Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.

  • Protocol Channels

    Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.

Activation and Hosting

- Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism

  • IIS

    Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.

  • Windows Activation Service

    (WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.

  • Self-Hosting

    WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.

  • Windows Service

    WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).