WCF + Enterprise Library + ValidationFault - wcf

I am trying to catch the ValidationFault exceptions of my service and return a instance of MyClass with the property Message filled with the validation error provided by EntLib when my client calls one of my service methods without the correct parameters (I can't use complex types).
I tried to implement two interfaces to accomplish this task: IParameterInspector and IOperationInvoker. The problem is after the method BeforeCall is called (of the IParameterInspector interface), EntLib throws the ValidationFault exception but I can't catch it and my code doesn't reach the Invoke method of my IOperationInvoker class and because of that I can't replace the return value with a instance of MyClass.
Remember, my client is not based on .NET platform and there's no such thing as catch(FaultException<ValidationFault> ex) there. That's why I MUST work with a default object on my service responses.
I appreciate the help.

Can you use an IErrorHandler implementation similar to Enterprise Library's WCF ExceptionShielding? Basically catch all exceptions and if it's a FaultException<ValidationFault> then convert the ValidationFault to your custom message and return it.
It looks like the output of ProvideFault is a Message so you could return a message instead of a fault. This posting seems to give the approach.

Related

How to fix 'System.ServiceModel.Channels.ReceivedFault' cannot be serialized

I have a workflow service. I also use workflow persistence in that service. But after I deployed workflow in IIS, from client I make a request to workflow service, in log file on server. I see a message
The execution of the InstancePersistenceCommand named {urn:schemas-microsoft-com:System.Activities.Persistence/command}SaveWorkflow was interrupted by an error.InnerException Message: Type 'System.ServiceModel.Channels.ReceivedFault' cannot be serialized.
Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.
If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.
I tried research about this exception, but I didn't find anything.
How to fix this problem ? or let me know what is the reason about above exception ?
System.ServiceModel.Channels.ReceivedFault is a non-serializable internal .NET framework class, so unfortunately there is nothing you can do to correct the actual root cause (i.e. making said class serializable).
You are probably calling an external service via WCF which faults, i.e. a System.ServiceModel.FaultException is thrown. IIRC, somewhere deep down in that FaultException object is a reference to the culprit, a ReceivedFault instance.
Solution: Catch all FaultExceptions, transfer the information you need to know from the FaultException into a serializable exception, and throw the latter:
try
{
CallService();
}
catch (FaultException ex)
{
// Gather all info you need from the FaultException
// and transport it in a serializable exception type.
// I'm just using Exception and the message as an example.
throw new Exception(ex.Message);
}

Is it possible to configure a WCF service client to throw a custom FaultException?

I was wondering if it was possible to configure a WCF service client to use a custom type instead of FaultException when throwing faults. The custom type would inherit from FaultException, but also have some additional details about the error.
The reason I want to use a custom FaultException is so I can store a GUID from the SOAP Header which is otherwise lost.
I know I could manually catch and rethrow any faults my service client returns, but that's flimsy. I have no way of guaranteeing future developers will do the same.
I've thought about subclassing the generated service client class and putting the error handling in there, but that generates a lot of work whenever the target service changes.
So, is it possible to configure a WCF service client to throw a custom FaultException type for Faults?
You can create your own IErrorHandler implementation:
http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx
Override ProvideFault and then do conversion from regular exceptions (including plain FaultException) to your own custom based FaultException<T>, where T is your own type that you can define to include custom properties.
After that, you have to register your implementation of IErrorHandler as service behavior, either in code or in web/app config.

Include exception information in return values in WCF

I am implementing an IErrorHandler for a set of WCF services. I configure the WCF services to use this error handler via the configuration file, using a custom behavior.
All methods in all services return a value that is derived from a common base class.
What I want to do is to include information about the error in the return value if the error handler gets called.
Any ideas on how to do this elegantly would be much appreciated.
You just need to create the message manually which complies with your return SOAP data. You can implement your own body writer and use it for the Message.Create function. Here is a good example of how to accomplish what you basically need Simple custom error handler for webHttpBinding in WCF
However if I were you I would choose fault approach when you just return void or some data if everything succeeds and fault message if it fails. Of course if there are no strict requirements to return operation status in the response object or if you are not refactoring an existing system.
Hope it helps.

WCF/WebService: Interoperable exception handling

I understand that WCF will convert an exception into a fault and send it back as a SOAP message, but I was wondering if this is truly interoperable. I guess I'm having a tough time trying to figure out this possible scenario:
Client (Java) calls a WCF Service
(LoginService).
Server checks for proper authorization, user authorization fails.
Server throws an UnauthorizedAccessException.
WCF converts this into a Fault somehow. (* - See Below As Well)
Client has to be able to know how to read this Fault.
I guess I'm just having a tough time understanding how this could still be interoperable because it is expecting Java to know how to translate a SOAP Fault that .NET encodes from an UnauthorizedAccessException.
Also, how does .NET actually convert the exception to a fault, what goes in as the fault code, name, etc. Some of the things seem to be "duh"s like perhaps the Fault Name is "UnauthorizedAccessException", but I'd rather know for sure than guess.
There is no "automatic conversion". WCF will return a fault (I forget which one) when you have an unhandled exception. But since you didn't declare that fault, many, if not most, clients will fail if you return it.
You are meant to define your own faults and to return them instead. Consider:
[DataContract]
public class MySpecialFault
{
public string MyMessage { get; set; }
}
[ServiceContract]
public interface IMyService
{
[FaultContract(typeof (MySpecialFault))]
[OperationContract]
void MyOperation();
}
public class MyService : IMyService
{
public void MyOperation()
{
try
{
// Do something interesting
}
catch (SomeExpectedException ex)
{
throw new FaultException<MySpecialFault>(
new MySpecialFault {MyMessage = String.Format("Sorry, but {0}", ex.Message)});
}
}
}
Any client capable of handling faults will deal with this. The WSDL will define the fault, and they will see a fault with the Detail element containing a serialized version of the MySpecialFault instance that was sent. They'll be able to read all the properties of that instance.
Faults have been part of the SOAP specification since v1.1. They are explained in the SOAP Specification.
It is up to implementations (WCF, Java etc) to ensure that Faults are handled according to the specification.
Since WCF converts FaultExceptions to Faults according to the SOAP specification, FaultExceptions thrown from WCF are interoperable.
SOAP faults are interoperable but .Net exception classes are not good to be used in SOAP faults. Instead define your own DataContract class (e.g. AccessFault) and then use it in a FaultContract.
see http://msdn.microsoft.com/en-us/library/ms733841.aspx
Whenever there is a UnauthorizedAccessException thrown at service boundary convert it to FaultException.
This can be done in several ways like using Microsoft Enterprise Library Exception Handling Block or implementing the IErrorHandler interface.

WCF OperationContext

I'm developing a WCF service and if there is an error I want to serialize the incoming parameter from the original method that was called on the service. I am using IErrorHandler to catch all exceptions.
My initial thoughts were that I will store the serialized parameter in OperationContext.IncomingMessageProperties so that I can access it from the HandleError method. However, as this isn't run on the original thread I believe the OperationContext will be null, so I am considering accessing it from the ProvideFault method.
Does this seem feasible? And will it work with OneWay service calls?
Not sure I can really help you much here, but let me try:
on your client, your code basically calls a method and passes it parameters. The WCF stack on the client side then converts that into a SOAP message (typically with an XML body, but could be binary, too) with headers and all and then sends that message across the wire to the server to be processed.
The server then attempts to deserialize that message into an object and attempts to call a message on a server implementation object. That method on the server object will most likely have the same parameters again, as the client - however, there's a possibility that the call will fail before that method even gets called.
So what I'm trying to say is: you can't rely on the fact that your server-side method with its parameters really gets called - there might have been a problem with e.g. authentication, the message format, a missing header or something else, that causes the server side to fail and throw an exception even before the server-side method ever gets called.
In the end, in the IErrorHandler, there's no way I would know of to get a hold of the message and/or the method and its parameters - all you can get are the error that occured on the server, and you can use that to turn it into a SOAP fault.
What you could do - both on the client and the server side - is create a new behavior that plugs into the WCF stack, and that records the methods being called and the parameters being passed into them - by implementing a class that implements the IParameterInspector interface of WCF. But that only will get called if the message on the client and the server will get properly deserialized and the server-side method really gets called.
Check out some of these links for more info on WCF extensibility:
How to: Inspect or Modify Parameters
WCF Extensibility: Parameter Inspectors
IParameterInspector in WCF
Extending WCF with custom behaviors
Hope this helps a bit!
Marc