How to detect a WCF session crash before calling a contract method? - wcf

I am using a session mode for my WCF service. The problem is the following: if session is broken and no longer exists, client can't know it before calling a contract.
For example, if the service has been restarted, the client's session id is invalid, because that session has been closed on the server side.
I check the channel state before calling the contract and its value is CommunicationState.Opened even if session is already broken. So, when I call the contract after this check I get a CommunicationException with this message:
The remote endpoint no longer recognizes this sequence. This is most likely due to an abort on the remote endpoint. The value of wsrm:Identifier is not a known Sequence identifier. The reliable session was faulted.
Is there any workaround? I need a way to get an appropriate session state before calling a contract so that I can restore it without getting an exception.
P.S. The CommunicationException type is general, so I can't detect a session crash by catching this exception.
P.P.S. I have asked the similar question here, but in that case I didn't know the reason, now I don't know how to evade it.

No, there is no workaround - all you can (and should do) is use proper defensive programming principles to be able to catch and handle those kind of exceptions as they happen.
If the server crashes or the network goes down, unfortunately, there's no mechanism to inform all potential clients of this case - they'll just find out the next time they try to call.
Update: yes, the CommunicationException is just the common base class for all exceptions related to WCF - check out the MSDN docs to see about all the descendant exceptions you can catch to be more specific - EndpointNotFoundException, FaultException (or FaultException<T>), ProtocolException and many many more!

Related

"The session was closed before message transfer was complete" with WCF reliable sessions

I've got a WCF service that uses reliable sessions. In my tests, I tend to open a channel, call a method and then close the channel.
I often get a The session was closed before message transfer was complete. exception during Close().
Given that my method is synchronous, the message transfer should be complete. If it's reliable sessions causing this problem (because it's still doing something under the hood), surely it's responsible for either blocking my Close() call, or for giving up without throwing an exception?
How do I avoid this exception?
You should find what caused the connection close. Add diagnostics to you server and client config files by using the WCF Service Configuration Editor.
Repro the error and open your logs in the viewer. You will probably find that the message was to large at the serverside.
I had the same problem, the solution was to change operation contract in my interface definition by marking called method as IsOneWay=false which is default setting.
Make sure you haven't change your operation contract for your method to
[OperationContract(IsOneWay=true)]
What you may want to consider is specifying a timeout value in your call to Close() to allow more time for graceful closing. This can spare you many problems. (Although I agree that finding the cause and trying to prevent it is also important).

WCF: How to diagnose faulted channels?

I'm working on shipping in a change for my lab that will hopefully help diagnose some weird channel-faulting weirdness we're seeing. There's a test application that uses DuplexChannelFactory to connect to a couple windows services, and for some reason the channels on this test application seem to be faulting quite a bit. I have plans to implement some retry logic in there, but it would be great to figure out why exactly they're faulting.
I know that channel factories and proxy objects all implement a lot of interfaces, and I've used reflector to crawl through some of them, but I haven't found anything like what I'm looking for. Is there a way to query these objects after they've faulted in order to get some information about what caused the fault?
Edit: The configuration is very basic--the binding is just the default-constructed NetTcpBinding, the service implementation has [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Reentrant)], and no special attributes are on any of the operations in the service contract. However, I'm asking more about general techniques in diagnosing channel faults, not diagnosing this specific case. I wouldn't expect configuration specifics to have too much impact on that; if anything, the configuration details would be something returned by said diagnostics, right?
Ladislav and Shiraz answers are all good and I have gave them +1.
All I can add to them is that normally a faulted channel is the result of unhandled exception on the server. When that happens, WCF thinks that there is somethig fundamentally wrong with the server and faults the channel so that it cannot be used.
The correct approach - which I believe should have been default and come for free - is for the service to catch the exception and create a FaultException and return it (look at this form example http://www.c-sharpcorner.com/UploadFile/ankithakur/ExceptionHandlingWCF12282007072617AM/ExceptionHandlingWCF.aspx)
The reason WCF does not make as default is that it changes the contract and the WSDL so the client has to get the updated WSDL.
So if I were you, I would catch the exceptions, log them and then return a fault exception and this way I would know what the problem is and channels are not faulted.
First thing is it this test application, or are the specific services used by other clients.
Assuming that it is the test client that is causing the problem. There could be 2 problems:
Not closing proxies, therefore hitting max connections to the server.
Not aborting proxies when they are in a failed state.
Diagnostic tool you are looking for is called WCF Tracing. It usually shows why the channel has faulted. You can configure it on both client and server and use SvcTraceViewer.exe to browse collected traces.
Have you hooked on to the ICommunicationObject.OnFauled

How do I properly handle a faulted WCF connection?

In my client program, there is a WCF connection that is opened at startup and supposedly stays connected til shutdown. However, there is a chance that the server closes due to unforeseeable circumstances (imagine someone pulling the cable).
Since the client uses a lot of contract methods in a lot of places, I don't want to add a try/catch on every method call.
I've got 2 ideas for handling this issue:
Create a method that takes a delegate and executes the delegate inside a try/catch and returns an Exception in case of a known exception, or null else. The caller has to deal with nun-null results.
Listen to the Faulted event of the underlying CommunicationObject. But I don't see how I could handle the event except for displaying some error message and shutting down.
Are there some best practices for faulted WCF connection that exist for app lifetime?
If you do have both ends of the wire under your control - both the server and the client are .NET apps - you could think about this approach instead:
put all your service and data contracts into a shared assembly, that both the server and the client will use
create the ChannelFactory<IYourService> at startup time and cache it; since it needs to have access to the service contract, this only works if you can share the actual service contract between server and client. This operation is the expensive part of building the WCF client
ChannelFactory<IYourService> factory = new ChannelFactory<IYourService>();
create the actual communications channel between client and server each time you make a call, based on the ChannelFactory. This is pretty cheap and doesn't cost much time - and you can totally skip any thoughts about having to detect or deal with faulted channels.....
IYourService client = factory.CreateChannel();
client.CallYourServiceMethod();
Otherwise, what you basically need to do is wrap all service calls into a method, which will first check for a channel's faulted state, and if the client proxy is faulted, aborts the current one and re-creates a new one.
I wrote a blog post on exceptions in WCF that deals with how to handle this: http://jamescbender.com/bendersblog/Default.aspx

WCF Callback Faulted - what happens to the session?

Just trying to get my head around what can happen when things go wrong with WCF. I have an implementation of my service contract declared with an InstanceContextMode of PerSession...
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)]
The calls happen as follows:
My client calls the server and calls GetServerUTC() to return the current UTC time of the server. This is a one way call and the server will call the client back when its ready (trivial in this instance to simply return the current time!)
The server calls back to the client and for test purposes in the callback implementation on the client I throw an exception.
This goes unhandled in the client (for test purposes) and the client crashes and closes down.
On the server I handle the faulted event handler on the ICommunicationObject...
obj.Faulted += new EventHandler(EventService_Faulted);
Questions...
Will this kill off the session for the current connection on the server.
I presume I am free to do what I want in this method e.g. logging or something, but should I do anything specific here to terminate the session or will WCF handle this?
From a best practise view point what should I do when the callback is faulted? Does it mean "something has happened in your client" and thats the end of that or is there something I a missing here?
Additionally, are there any other faulted handlers I should be handling.
Ive done a lot of reading on WCF and it seems sort of vague on what to do when something goes wrong. At present I am implementing a State Machine on my client which will manage the connection and determine if a user action can happen dependant on if a connection exists to the server - or is this overkill.
Any tips would be really appreciated ;)
I found out that the session will time out as per the settings for your sessions. Strangely I noticed that once faulted the client is still able to call other methods on the same session.

How to handle low level WCF errors?

I have the standard error handing in place in my service:
I have an IErrorHandler hooked to the service to handle unexpected errors during service execution.
I have try/catch blocks in all my service methods to handle expected cases.
However, there are cases where exceptions are thrown on the server and neither is called.
Here is a case where the server exception is not sent to the IErrorHandler:
Set the receiveTimout on the server binding to 5 seconds.
On the client do this:
.
Service1Client sc = new Service1Client();
ICommunicationObject o = sc as ICommunicationObject;
o.Open(); // open channel
sc.GetData(10); // do a first call
Thread.Sleep(10000); // wait longer than the server receiveTimeout
sc.GetData(10); // Attempt another call: server throws a FaulException
In that case, the error is thrown on the server but I cannot find a way to handle it (and log it). I know an error is raised because if I attach a debugger on the server process and break on all exceptions, the debugger breaks.
I have found other similar cases where low level errors are not passed to my program.
Where can I hook my code to ensure that I can handle ALL exceptions that occur on the server before they are returned to the client app? Should I implement my own IChannel or some other low level interface?
Thanks
UPDATE Sep 21 2009: See this thread on the Microsoft WCF Forum. I'll probably have to implement my own Channel if I want to handle this type of exception. I'll update this post again when I have more info.
After much research and experimentation, the answer is:
At this time (.Net 3.5) there is no mechanism that allows one to handle all possible exceptions that may occur in the context of a WCF call.
Exceptions that happen during the service method execution can easily be handled with:
Try/catch blocks in all service methods to handle expected cases.
IErrorHandler hooked to the services to handle unexpected errors during service execution.
However, for low level WCF infrastructure errors, there is no perfect solution. The best solution that exists seems to be to implement a custom channel to catch more exceptions.
In this Microsoft Connect Bug Report, Microsoft confirms that there is no way to handle all types WCF infrastructure errors.
In this thread on the Microsoft WCF forums, there is a sample on how to implement a custom channel. That solution only works for HTTP, not for HTTPS. Also some WCF infrastructure errors are not caught by the custom channel either (see more details in that specific thread).
Use FaultContracts. Then the fault can be handled at the client end.
http://msdn.microsoft.com/en-us/library/ms732013.aspx
http://www.c-sharpcorner.com/UploadFile/ankithakur/ExceptionHandlingWCF12282007072617AM/ExceptionHandlingWCF.aspx
This is also much better for debugging, since often you will be developing a client and don't want to bring down the server for debugging purposes.
On the client end, use try/catch blocks to catch all exceptions/faults. There are definitely errors that can't be detected on the server end, such as a communication problem, so you need to handle errors on the client end anyways.
If you want centralized error handling, you can create a service that takes messages about all errors, send the error to that server, and have it log that. This can be useful if you want to create a centralized message tracing/performance analysis/logging tool and have a large number of application processors, servers, clients etc.
The point is - if the server is not reachable or can't handle the message, there won't be an error on the server - the error will pop up on the client ("TimeoutException" or others).
So in those cases, having the IErrorHandler on the server really isn't gonna help - since the error really happens on the client (no connection can be made, due to network down, or typo in server's address or sstuff like that).
So on the client side, you definitely also have to use try....catch around all your server calls.
Marc
Set up diagnostic tracing and check the logs with Service Trace Viewer Tool. Link contains information about configuring tracing as well.