Handling ObjectDisposedExceptions on disconnected WCF channels - wcf

When a method is called on a WCF channel that has been disconnected for some reason, it raises an ObjectDisposedException.
Now is normal operation this should not happen, but if for some reason it did, I would like to be able to handle the exception nicely by showing an error to the user like "An operation failed because the service is not connected".
The problem is I just get a generic disposed exception in my appwide exception handler, so I have no way of determining whether WCF threw it.
to get around this I currently have a wrapper class that simply wraps all service method calls with try/catch and rethrows any ObjectDisposedException's as a custom comms exception that my global handler can deal with. this is a load of boilerplate stuff I could do without though.
Is there any way of determining whether WCF threw the exception?
Cheers

I used to encounter such problem, it seems it's difficult to determine whether the WCF throws exception. You can't use the CommunicationObject.Status for this problem, only when you try to use that channel, it throws exception to tell you that the channel is faulted.
Therefore, I used the way like yours.

Related

How to hide Fault error description(WCF and Silverlight)

I have silverlight application which uses WCF for database operations. Using Fiddler I am able to tamper the parameters required for a particular method used in WCF and getting an exception "a:DeserializationFailedThe formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:parameters. The InnerException message was 'There was an error deserializing the object of type........". My security team does not like this and saying it is exposing the real exception. Is there any way to handle this type of exception and show some user define message? If yes then please provide the complete sample. I went through so many articles in internet but none of them is having complete solution.
You need to implement a custom error handler. See
http://msdn.microsoft.com/en-us/library/ms599828
For lots of reference details and this
http://www.neovolve.com/post/2008/04/07/implementing-ierrorhandler.aspx
For an example that implements (in a basic, but instructive way) exactly the exception shielding behaviour you are looking for.

WCF: use or not to use exception from service to client in production? any alternative?

I am thinking in use some exceptions to from service to client.
I am thinking for example in this case. The client try to insert a register in the database. This register has a value for e filed that exists in the database, and how it has a unique constraint, when I do the savechanges I get an updateException.
I am thinking to use exceptions (faultException) to warn to client of the error, and use a custom class to send to the client the actual data of the register, so in this way the client does not to make other query for the register.
However, in this link, it says that exceptions only should be used in development, no in production, so, without exceptions, how could I do what I want to do?
Perhaps I could use a custom class, that have one list property for each type of entities, and a property bool, that indicates if the operation is right or wrong, other property with an arbitrary code to indicate the type of error... etc. This is a good alternative?
In summary, really is better avoid exceptions in production? how I could communicate to the client errors from the service?
You have 2 options:
Throw exceptions and return WCF faults
Attach error information to you return objects
I personally favour throwing exceptions and returning WCF faults. I dont like the idea of attaching error information to return objects, I feel it violoates object oriented principals. For example a field called 'ErrorCode' has no place on a 'CustomerAddress' object.
I believe that if exceptional circustances arise, then an exception should be thrown. This will also simplfy your code as you wont have to wrap everything in try catch blocks in order to attach error information to your return object. Although you may want to catch unexpected exceptions and then throw a more appropriate exception with a more useful message.

What is the easiest way to log exceptions from a WCF service to a the Windows Event Log?

I want to log all exceptions (including serialization exception stack traces) in a WCF server to the Windows Event Log (log4net logging would also be acceptable).
What is the easiest way to do this?
Specifically all errors in serialization, in the service itself, etc. Right now I'm using tracing to get serialization errors during development. Tracing was the only way I could find out what object was actually have a problem with serialization. See Quickly finding WCF Serialization/Deserialization Issues for an example of getting the serialization stack trace.
I can handle errors in the service code itself. However, errors in the WCF machinery don't propagate to my service code (like serialization errors).
I don't need to send the errors to the client.
I just want to get the errors into one location (like the Event Log).
Right now (from my research) it appears that the IErrorHandler Interface with some custom code might be the best way to proceed. Will using the IErrorHandling interace catch the serialization exceptions?
Edit:
This may be the answer I'm looking for:
How do I create a global exception handler for a WCF Services?
I'd just like a confirmation that this will catch serialization errors and more importantly the details of those errors, also.
More Info:
How do I create a global exception handler for a WCF Services?
Yes, IErrorHandler will also catch serialization exceptions. You will get all information stored in the exception. Whether or not this enough detail for you, I can't say.
Note that there may be client-side errors (serialization and others) which will never make it to the server. You will not see those with the IErrorHandler.

Implement 'Ping' functionality using Message Inspector causes WCF runtime to throw NullReferenceException

I'm using WCF to implement a web service. This web service requires a 'ping' feature as a health monitor for each service. This functionality has been implemented using IDispatchMessageInspector and is configured for each endpoint of a service. This is due to a business requirement for the 'ping' to be as near the actual service code as possible. At the same time, I did not want to tie it to each service implementation's code and IDispatchMessageInspector seems to be a good fit.
The service uses a Request-Reply MEP. Each request message contains an element that specifies what processing is required. The service will then use this value to determine how to process the data in the message. The same element is used to define a request message as a 'heartbeat' check.
The 'ping' message inspector will pre-process a request message in the AfterReceiveRequest() method and if it determines the request is a 'heartbeat', it will then generate the correct response and pass that on to the BeforeSendReply() method via a correlation object returned from AfterReceiveRequest(). The request message parameter of AfterReceiveRequest(), which is by reference, is then set to null to prevent the message from being processed by the service implementation code.
The technique of setting request message to null was found in a web site or blog which I can't remember nor find the URL for. This technique works great on it's own and I can prevent service implementation code from being executed if it's a 'heartbeat' request.
Unfortunately, setting the request message to null in a message inspector will cause the WCF runtime to always throw a NullReferenceException. From the stack trace, I gather the runtime will still pass the message object (which will be null after going through 'Ping' message inspector) to the dispatcher and when the dispatcher tries to deserialise a null message object, causes the NullReferenceException.
However, my system also implements IErrorHandler to catch any unhandled exceptions in the service and log it. This means every successful 'heartbeat' request will generate a log entry for the NullReferenceException and the 'heartbeat' could be as frequent as every minute.
The Question :
What can I do to prevent logging of 'useless' NullReferenceException thrown when 'Ping' prevents service implementation code from running by setting request to null.
Many thanks in advance.
~hg
Not the most graceful solution but potential workarounds (that i've not tested), but where you detect your ping calls in the inspector code, could you not throw your own custom exception type i.e. PingRequestException, and handle this when it returns to the client? Would that avoid you hitting the WCF Runtime code, thus avoiding the logging of unhandled exceptions.
Otherwise you could try to use a base service, inherited by all of your services (the other side of the wcf runtime code) that detects and handles ping requests in the constructor before hitting the actual service code.

WCF - Overhead of throwing FaultExceptions within your service

I posted a question about using Messages versus Fault Exceptions to communicate business rules between services.
I was under the impression it carried overhead to throw this exception over the wire, but considering it's just a message that get serialized and deserialized, they were in fact one and the same.
But this got me thinking about throwing exceptions in general or more specifically throwing FaultExceptions.
Now within my service, if i use
throw new FaultException
to communicate a simple business rule like "Your account has not been activated",
What overhead does this now carry?
Is it the same overhead as throwing regular exceptions in .NET? or does WCF service handle these more efficiently with the use of Fault Contracts.
So in my user example, which is the optimal/preferred way to write my service method
option a
public void AuthenticateUser()
{
throw new FaultException("Your account has not been activated");
}
option b
public AutheticateDto AutheticateUser()
{
return new AutheticateDto() {
Success = false,
Message = "Your account has not been activated"};
}
Well... In general you shouldn't be throwing exceptions for expected conditions, or anything you expect to happen regularly. They are massively slower than doing normal methods. E.g., if you expect a file open to fail, don't throw a that exception up to your caller, pass the back a failure code, or provide a "CanOpenFile" method to do the test.
True, the message text itself isn't much, but a real exception is thrown and handled (possibly more expensively because of IIS), and then real exception is again thrown on the client when the fault is deserialized. So, double hit.
Honestly, if it is a low volume of calls, then you probably won't take any noticeable hit, but is not a good idea anyway. Who wants to put business logic in a catch block :)
Microsoft : Exceptions And Performance, & Alternatives
Developer Fusion: Performance, with example
It's just like a normal exception, and uses the same wrapping code as a normal exception would to marshal into a fault, including unwinding the stack.
Like exceptions SOAP faults shouldn't, to my mind, be used for program flow, but to indicate errors.