One of the projects I am currently working on, uses both Windows Communication Foundation and Enterprise Library 2.0. While there is no out-of-the-box integration between those two, we ran into some points where some work had to be done.
One of them is to create an exception handling policy for Enterprise Library that replaces an .net exception with a fault contract exception.
I'll take this post to go throw the need and the solution we came up for it.
So here goes…
WCF Fault Handling
When an exception occurs in a WCF service, the wire cuts off and the client receives a communication exception saying that a response was never received from the server.
If you want your client to receive exceptions from the server you can explicitly enable receiving exception details (using configuration) or declaring a Fault Contract. A Fault Contract is an attribute you place above a service operation, that means that the operation can return a fault of the a certain type. Examine this service contract:
[ServiceContract]
public interface IEchoService
{
[OperationContract]
[FaultContract(typeof(ServiceException))]
void Echo(string message);
}
This definition of a service contacts means that the Echo operation can return Faults of type ServiceException. ServiceException can be any serializable class or any class decorated with DataContract attribute.
As an implementation for this operation, in order to return a Fault in the same model that we throw .net exceptions, you can use the following way:
public class EchoService : IEchoService
{
#region IEchoService Members
public void Echo(string message)
{
try
{
Console.WriteLine("Echo: " + message);
throw new ApplicationException("Echo: " + message);
}
catch (Exception ex)
{
throw new FaultException<ServiceException>(new ServiceException(ex.Message));
}
}
#endregion
}
In order to catch the exception in the client side, use this following code:
try
{
// Call the Echo sevice
}
catch (FaultException<ServiceException> ex)
{
ServiceException sex = ex.Detail;
Console.WriteLine(sex.GetType().FullName + "\n" + sex.Message);
}
Enterprise Library Exception Handling
To handle an exception when using Enterprise Library, you should configure a policy using the configuration file or tool.
A policy has its unique name, the exception types it applies to (similar to catch block) and the exception handlers. For each exception type you configure an action that should be done after all the handlers were executed. This post action can be None, ThrowNewException or NotifyRethrow.
To get more details about the configuration of exception handling policies, refer to the exception handling quickstart (ships with Enterprise Library), or to the Enterprise Library Hands-On Labs.
To handle an exception using a configured policy, use the following piece of code:
try
{
// Your code here...
catch (Exception ex)
{
if (ExceptionPolicy.HandleException(ex, "MyPolicy")) throw;
}
Creating a custom Exception Handler
There are few exception handlers that ship with Enterprise Library for example – ReplaceHandler that replaces the exception new exception and WrapHandler that wraps the exception with a new exception of a specified type.
To create a custom exception handler, you should simply create a class that inherits the IExceptionHandler interface:
public interface IExceptionHandler
{
Exception HandleException(Exception exception, Guid handlingInstanceId);
}
While creating a custom exception handler is very easy and straight forward, creating what it takes to configure it is a bit more complicated, but rather interesting in my opinion. In general, one should create an custom Exception Handler Data class (that inherits from ExceptionHandlerData) that represents the configuration data for the custom handler. Additionally one should create and assembler , that instantiates the custom handler with the configuration data.
I think that the Enterprise Library Polymorphic configuration collection mechanism is a very interesting and useful infrastructure, and I can only advise the reader to explore more deeply into it.
Creating a Fault Exception
To use the ServiceFaultHandler you should configure it in the following way:
<exceptionHandlers>
<add name="ServiceFaultHandler"
type="Bursteg.Samples.ExceptionHandling.ServiceFaultHandler, Echo.Service"
exceptionMessage="Service Fault Exception: The service operation threw an exception."
detailsExceptionType=" Bursteg.Samples.ExceptionHandling.ServiceException, Echo.Interfaces"/>
</exceptionHandlers>
Notice that in addition to the name and type of the handler the configuration element takes the exception message and detailsExceptionType attributes. At runtime, the handler will create FaultException<T> where T is the detailsExceptionType supplied here. Notice that this exception type should also be declared in the FaultContractAttribute in the service contract.
The real interesting code which is the core implementation for this component can be found in the WrapException method in the ServiceFaultHandler class:
private Exception WrapException(Exception originalException, string detailsExceptionMessage)
{
// Create the detail exception
object[] extraParameters = new object[] { detailsExceptionMessage };
Exception detail = (Exception)Activator.CreateInstance(DetailExceptionType, extraParameters);
Type faultExceptionType = typeof(FaultException<>);
Type faultBindedExceptionType = faultExceptionType.MakeGenericType(DetailExceptionType);
// Create a meaningful fault reason
FaultReason reason = new FaultReason(originalException.Message);
// Construct a new fualtException with generic type
extraParameters = new object[] { detail, reason };
Exception detail2 = (Exception)Activator.CreateInstance(faultBindedExceptionType, extraParameters);
return detail2;
}
The above code creates an instance of the exception that was defined in the configuration and in the FaultContract with the input error message.
Than the method create an instance of FaultException<T> where T is that detailed exception. Finally that exception is thrown back to the caller.
Hope you find this useful, I'd love to get any comments and questions for this post and sample.
You can download a sample project that demonstrates the ServiceFaultHalder.
Enjoy!
Partial classes are a great new feature in Visual Studio 2005. They allow the definition of a class, struct or interface to be split into multiple files.
You usually find partial classes when using some kind of a designer, such as Windows Forms Designer, or DataSet Designer, but sometimes you just want to split your class to separate files (maybe to allow some developers work simultaneously on the same file in source control).
In order to arrange the solution a little bit, Instead of keeping all files of the same partial class in the same tree level, you can nest them under a single file name, like the following example:

It turns out that there is no easy way for doing that from the Visual Studio IDE. But, If you follow these steps, you can do it on your own:
-
Create a new Console application. The solution opens with the project that contains a code file called Program.cs (of Program.vb)
-
Open the Program.cs file, and add the partial keyword before the class definition. Your class definition should look like:
partial class Program
{
...
}
-
Add a new class to the project, call it Program.Extention.cs. (You can replace the .Extension with any other naming convention you have in your project).
-
Open the Program.Extention.cs file and notice that the class name is also Program. Add the partial keyword before the class definition.
And now for the real stuff:
-
Right click the header of the tab that displays the code for Program.cs and choose “Open Containing Folder”. This will open the folder in with the files are stored.
-
Notice that this folder also contains the .csproj file of your project. Open this file with a text editor (Notepad should do it..) and search for the following block:
<Compile Include="Program.cs" />
<Compile Include="Program.Extension.cs" />
<Compile Include="Program.cs" />
<Compile Include="Program.Extension.cs">
<DependentUpon>Program.cs</DependentUpon>
</Compile>
Enjoy!