I’ve just realized that if I want to properly communicate with a WCF server, I have to handle separately a set of exceptions.

Also, the WCF framework requires somebody to explicitly call the Close method on the proxy at the end of the operation (instead of using a ‘using’ block -sic!).

The original code is at the end of the post. So far I have three proposed methods to write the exception handling code and the cleanup code in a single location:

  • wrap the proxy generated by svcutil in a ‘SafeProxy’ class and use only this class to call the server
  • consolidate all exception handling code in a method; also, the cleanup code must be consolidated somewhere (it may be the exception handling method)
  • write a generic ‘SafeCall’ method to call server operations.

I have tried the ‘SafeCall’ method so far, but I do not have a good solution yet.

<pre>        private static T Operation( ... )
        {
            var client = null as ServiceProxy;
            try
            {
               client = new ServiceProxy();
               return OperationNoExceptionHandling( client, ...);
            }

            // Exception handling sequence common to all methods communicating
            // with the server.
            catch( MessageSecurityException ex )
            {
                Console.WriteLine( "Invalid client credentials" );
                Console.WriteLine( ex );
            }

            catch( CommunicationException ex )
            {
                Console.WriteLine( ex );
            }

            catch( TimeoutException ex )
            {
                Console.WriteLine( ex );
            }

            catch( Exception ex )
            {
                Console.WriteLine( ex );
                throw;
            }

            finally
            {
                if( client != null )
                {
                    if( client.State == CommunicationState.Faulted )
                    {
                        client.Abort();
                    }
                    else
                    {
                        client.Close();
                    }
                }
            }

            return default(T);
        }</pre>
Advertisements