Beispiel #1
0
        public async Task <byte[]> ExecuteWcfProcess(byte[] message)
        {
            IService       proxy = null;
            IClientChannel ch    = null;

            byte[] result;
            try
            {
                proxy = _factory.CreateChannel();
                ch    = (IClientChannel)proxy;
                ch.Open();
                result = await proxy.ExecuteWcfProcess(message);

                ch.Close();
            }
            catch (Exception)
            {
                if (ch != null)
                {
                    if (ch.State == CommunicationState.Faulted)
                    {
                        ch.Abort();
                    }
                    else
                    {
                        ch.Close();
                    }
                }

                throw;
            }

            return(result);
        }
 public T Function<T>(Func<T> func)
 {
     try
     {
         var result = func();
         _clientChannel.Close();
         return result;
     }
     catch (Exception ex)
     {
         KTrace.Error(ex);
         _clientChannel.Abort();
         throw;
     }
 }
Beispiel #3
0
        public createMerchantAliasResult CreateMerchantAlias(createMerchantAliasRequest request)
        {
            IClientChannel channel = (IClientChannel)_createMerchantAliasFactory.CreateChannel();

            bool success = false;
            createMerchantAliasResult result = null;

            try
            {
                createMerchantAliasResponse response = null;
                using (OperationContextScope scope = new OperationContextScope(channel))
                {
                    OperationContext.Current.OutgoingMessageHeaders.ReplyTo = new EndpointAddress(_config.AsyncServiceEndpoint);
                    response = ((MerchantAliasWSCreate)channel).createMerchantAlias(new createMerchantAliasRequest1(request));
                    channel.Close();
                }

                result = response.@return;

                success = true;
            }
            finally
            {
                if (!success)
                {
                    channel.Abort();
                }
            }
            return(result);
        }
Beispiel #4
0
        void InvokeEnd(Task response, IClientChannel channel, MethodCallMessageWrapper methodCallWrapper)
        {
            Exception  exception = null;
            MethodInfo method    = methodCallWrapper.MethodBase as MethodInfo;

            try
            {
                FlowContextForTest(methodCallWrapper);

                if (response.IsFaulted)
                {
                    exception = EvaluateException(response.Exception);
                    throw exception;
                }
            }
            finally
            {
                OnPostInvoke(method, exception);
                if (channel.State != CommunicationState.Closed && channel.State != CommunicationState.Faulted)
                {
                    try
                    {
                        channel.Close();
                    }
                    catch
                    {
                        channel.Abort();
                    }
                }
                channel = null;
            }
        }
Beispiel #5
0
        public removeMerchantAliasResult RemoveMerchantAlias(removeMerchantAliasRequest request)
        {
            IClientChannel channel = (IClientChannel)_createMerchantAliasFactory.CreateChannel();

            bool success = false;
            removeMerchantAliasResult result = null;

            try
            {
                removeMerchantAliasResponse response = ((MerchantAliasWSRemove)channel).removeMerchantAlias(new removeMerchantAliasRequest1(request));
                channel.Close();

                result = response.@return;

                success = true;
            }
            finally
            {
                if (!success)
                {
                    channel.Abort();
                }
            }
            return(result);
        }
Beispiel #6
0
 public static TResultType CallFunc(Func <TFuncType, TResultType> func, IClientChannel proxy)
 {
     try
     {
         return(func((TFuncType)proxy));
     }
     catch (CommunicationException ex)
     {
         proxy.Abort();
         throw ex;
     }
     catch (TimeoutException ex)
     {
         proxy.Abort();
         throw ex;
     }
     catch (Exception ex)
     {
         proxy.Abort();
         throw ex;
     }
     finally
     {
         if (proxy.State == CommunicationState.Opened)
         {
             proxy.Close();
         }
     }
 }
Beispiel #7
0
 /// <summary>
 /// Invoke method implementation
 /// </summary>
 private T Invoke <T>(string operationName, string uri, ExecuteOptions options, InvokeDelegate <T> operation)
 {
     using (new SPMonitoredScope("Invoke :" + operationName + "_" + uri))
     {
         string ep = FindLoadBalancerEndPoint(uri);
         if (!string.IsNullOrEmpty(ep))
         {
             Uri xu = new Uri(ep);
             IIdentityServiceContract identityapplication = GetChannel(xu, options);
             IClientChannel           clientChannel       = identityapplication as IClientChannel;
             try
             {
                 operation(identityapplication);
                 clientChannel.Close();
             }
             finally
             {
                 if (clientChannel.State != CommunicationState.Closed)
                 {
                     clientChannel.Abort();
                 }
             }
         }
     }
     return(default(T));
 }
Beispiel #8
0
        /// <summary>显式关闭和销毁当前的WCF通道</summary>
        public static void Close()
        {
            lock (_ans)
            {
                IClientChannel channel = _backupsClass as IClientChannel;

                try
                {
                    if (null == channel)
                    {
                        return;
                    }

                    ClearAllEvents(channel);

                    if (channel.State == CommunicationState.Opened ||
                        channel.State == CommunicationState.Opening ||
                        channel.State == CommunicationState.Created)
                    {
                        channel.Close();
                    }
                }
                catch { }
                finally { _backupsClass = null; _channelState = false; }
            }
        }
Beispiel #9
0
 public void unregisterSeller(Uri request, string name)
 {
     if (FlightSearchLogic.Instance.delegates.ContainsKey(name))
     {
         ISellerService tsqs;
         bool           gotValue = FlightSearchLogic.Instance.delegates.TryGetValue(name, out tsqs);
         if (gotValue)
         {
             IClientChannel currChannel = (IClientChannel)tsqs;
             try
             {
                 currChannel.Close();
                 currChannel.Abort();
             }
             catch (Exception)
             {
                 currChannel.Abort();
                 Console.WriteLine("Closing of stale channel {0} failed, ignoring", currChannel.RemoteAddress.Uri.ToString());
             }
             ISellerService victimChannel;
             FlightSearchLogic.Instance.delegates.TryRemove(name, out victimChannel);
             Console.WriteLine("Successfully remove old seller {0} by name", name);
         }
     }
 }
Beispiel #10
0
 private static void CloseTaskRequestChannel(IClientChannel channel)
 {
     if (channel != null && channel.State != CommunicationState.Faulted)
     {
         channel.Close();
     }
 }
Beispiel #11
0
        public static void Using <T>(Action <T> action)
        {
            BasicHttpBinding   bindnig     = new BasicHttpBinding();
            string             endpointUri = GetServiceEndpoint(typeof(T));
            ChannelFactory <T> factory     = new ChannelFactory <T>(bindnig, new EndpointAddress(new Uri(endpointUri)));

            //ChannelFactory<T> factory = new ChannelFactory<T>("*");

            T client = factory.CreateChannel();

            try
            {
                action(client);
                ((IClientChannel)client).Close();
                factory.Close();
            }
            catch (Exception ex)
            {
                IClientChannel clientInstance = ((IClientChannel)client);
                if (clientInstance.State == System.ServiceModel.CommunicationState.Faulted)

                {
                    clientInstance.Abort();
                    factory.Abort();
                }
                else if (clientInstance.State != System.ServiceModel.CommunicationState.Closed)
                {
                    clientInstance.Close();
                    factory.Close();
                }
                throw (ex);
            }
        }
Beispiel #12
0
        // Token: 0x06000010 RID: 16 RVA: 0x00002588 File Offset: 0x00000788
        public static void Use(Action <T> codeBlock, string RemoteIP)
        {
            IClientChannel clientChannel = (IClientChannel)((object)new ChannelFactory <T>(GenericService <T> .binding).CreateChannel(new EndpointAddress(string.Format("http://{0}/{1}{2}{3}", new object[]
            {
                RemoteIP,
                "IRemo",
                "te",
                "Panel"
            }))));
            bool flag = false;

            try
            {
                codeBlock((T)((object)clientChannel));
                clientChannel.Close();
                flag = true;
            }
            finally
            {
                if (!flag)
                {
                    clientChannel.Abort();
                }
            }
        }
Beispiel #13
0
 public static void CallAction(Action <TActionType> action, IClientChannel proxy)
 {
     try
     {
         action((TActionType)proxy);
     }
     catch (CommunicationException ex)
     {
         proxy.Abort();
         throw ex;
     }
     catch (TimeoutException ex)
     {
         proxy.Abort();
         throw ex;
     }
     catch (Exception ex)
     {
         proxy.Abort();
         throw ex;
     }
     finally
     {
         if (proxy.State == CommunicationState.Opened)
         {
             proxy.Close();
         }
     }
 }
Beispiel #14
0
        public static async Task <TResult> ExecuteAsync <TResult>(Func <T, Task <TResult> > action)
        {
            IClientChannel clientChannel = (IClientChannel)ChannelFactory.CreateChannel();

            bool success = false;
            TaskCompletionSource <TResult> taskCompletionSource = new TaskCompletionSource <TResult>();

            try
            {
                taskCompletionSource.TrySetResult(await action((T)clientChannel));
                clientChannel.Close();
                success = true;
            }
            catch (Exception ex)
            {
                taskCompletionSource.TrySetException(ex);
            }
            finally
            {
                if (!success)
                {
                    clientChannel.Abort();
                }
            }
            return(await taskCompletionSource.Task);
        }
Beispiel #15
0
    public static void Using <TServiceContract>(Action <TServiceContract> action, string endpointConfigurationName) where TServiceContract : class
    {
        ChannelFactoryCacheKey            cacheKey       = new ChannelFactoryCacheKey(typeof(TServiceContract), endpointConfigurationName);
        ChannelFactory <TServiceContract> channelFactory = (ChannelFactory <TServiceContract>)SvcHelper.ChannelFactories.GetOrAdd(
            cacheKey,
            cacheKey => new ChannelFactory <TServiceContract>(cacheKey.EndpointConfigurationName));
        TServiceContract typedChannel  = channelFactory.CreateChannel();
        IClientChannel   clientChannel = (IClientChannel)typedChannel;

        try
        {
            using (new OperationContextScope((IContextChannel)typedChannel))
            {
                action(typedChannel);
            }
        }
        finally
        {
            try
            {
                clientChannel.Close();
            }
            catch
            {
                clientChannel.Abort();
            }
        }
    }
Beispiel #16
0
        /// <summary>
        /// After sending, we check if the write was successful or if it was a fire-and-forget.
        /// </summary>
        /// <param name="sendTask">The task of the send operation.</param>
        /// <param name="tcsResponse"></param>
        /// <param name="isFireAndForget">True, if we don't expect a response message.</param>
        /// <param name="channel"></param>
        private async Task AfterSendAsync(Task sendTask, TaskCompletionSource <Message.Message> tcsResponse, bool isFireAndForget, IClientChannel channel)
        {
            // TODO use for UDP connections, too
            await sendTask;

            if (sendTask.IsFaulted)
            {
                string msg = String.Format("Failed to write channel the request {0} {1}.", tcsResponse.Task.AsyncState,
                                           sendTask.Exception);
                Logger.Warn(msg);
                tcsResponse.SetException(sendTask.TryGetException());
            }
            if (isFireAndForget)
            {
                Logger.Debug("Fire and forget message {0} sent. Close channel {1} now. {0}", tcsResponse.Task.AsyncState, channel);
                tcsResponse.SetResult(null); // set FF result
                // close channel now
            }
            else
            {
                //.NET specific, we wait here for the response
                // receive response message
                // processes client-side inbound pipeline
                await channel.ReceiveMessageAsync();
            }
            channel.Close(); // TODO not needed, receive method closes...
        }
        /// <summary>
        /// 关闭通道连接并释放资源
        /// </summary>
        /// <example>WcfClientProxy.CloseAndDispose((IClientChannel)_IService);</example>
        /// <param name="serviceProxy">代理实例</param>
        public static void CloseAndDispose(IClientChannel serviceProxy)
        {
            if (serviceProxy == null)
            {
                return;
            }

            try
            {
                if (serviceProxy.State == CommunicationState.Opened)
                {
                    serviceProxy.Close();
                }
                serviceProxy.Dispose();
            }
            catch (CommunicationException) { serviceProxy.Abort(); }
            catch (TimeoutException) { serviceProxy.Abort(); }
            catch (Exception)
            {
                serviceProxy.Abort();
                //throw;
                ///todo:未知异常,暂不抛出,考虑记录日志
            }
            finally
            {
                serviceProxy = null;
            }
        }
        /// <summary>
        /// Executes the specified action.
        /// </summary>
        /// <typeparam name="TResult">The type of the result.</typeparam>
        /// <param name="action">The action.</param>
        /// <returns>the result</returns>
        public TResult Execute <TResult>(Func <T, TResult> action)
        {
            IClientChannel clientChannel = (IClientChannel)ChannelFactory.CreateChannel();
            TResult        result        = default(TResult);

            try
            {
                result = action((T)clientChannel);
                clientChannel.Close();
            }
            catch (FaultException e)
            {
                Console.WriteLine(e.Message);
                clientChannel.Abort();
            }
            catch (CommunicationException e)
            {
            }
            catch (Exception e)
            {
                clientChannel.Abort();
            }
            finally
            {
            }
            return(result);
        }
    public static void Use(UseServiceDelegate <T> codeBlock)
    {
        IClientChannel proxy   = (IClientChannel)_channelFactory.CreateChannel();
        bool           success = false;

        Exception mostRecentEx = null;

        for (int i = 0; i < 5; i++) // Attempt a maximum of 5 times
        {
            try
            {
                codeBlock((T)proxy);
                proxy.Close();
                success = true;
                break;
            }
            // The following is typically thrown on the client when a channel is terminated due to the server closing the connection.
            catch (ChannelTerminatedException cte)
            {
                mostRecentEx = cte;
                proxy.Abort();
                //  delay (backoff) and retry
                Thread.Sleep(1000 * (i + 1));
            }

            // The following is thrown when a remote endpoint could not be found or reached.  The endpoint may not be found or
            // reachable because the remote endpoint is down, the remote endpoint is unreachable, or because the remote network is unreachable.
            catch (EndpointNotFoundException enfe)
            {
                mostRecentEx = enfe;
                proxy.Abort();
                //  delay (backoff) and retry
                Thread.Sleep(1000 * (i + 1));
            }

            // The following exception that is thrown when a server is too busy to accept a message.
            catch (ServerTooBusyException stbe)
            {
                mostRecentEx = stbe;
                proxy.Abort();
                //  delay (backoff) and retry
                Thread.Sleep(1000 * (i + 1));
            }

            catch (Exception)
            {
                // rethrow any other exception not defined here
                // You may want to define a custom Exception class to pass information such as failure count, and failure type
                proxy.Abort();
                throw;
            }
        }
        if (mostRecentEx != null)
        {
            proxy.Abort();
            throw new Exception("WCF call failed after 5 retries.", mostRecentEx);
        }
    }
Beispiel #20
0
        public static async Task <TResult> UseAsync <TResult>(UseServiceDelegate <TResult> codeBlock)
        {
            return(await Task.Run(() =>
            {
                IClientChannel proxy = (IClientChannel)_channelFactory.CreateChannel();
                bool success = false;
                bool getResultSuccess = false;
                TResult result = default(TResult);

                try
                {
                    result = codeBlock((IImoutoWCFService)proxy);
                    getResultSuccess = true;

                    proxy.Close();
                    success = true;
                }
                catch (Exception ex)
                {
                    try
                    {
                        proxy.Close();
                        success = true;
                    }
                    catch
                    {
                    }

                    if (!getResultSuccess)
                    {
                        throw ex;
                    }
                }
                finally
                {
                    if (!success)
                    {
                        proxy.Abort();
                    }
                }

                return result;
            }));
        }
Beispiel #21
0
 public static void CloseClientChannel(IClientChannel c)
 {
     try {
         c.Close();
     } catch {
         c.Abort();
     } finally {
         c.Dispose();
     }
 }
Beispiel #22
0
        public static void Close <T>(this T service)
        {
// ReSharper disable once SuspiciousTypeConversion.Global
            IClientChannel channel = service as IClientChannel;

            if (channel != null)
            {
                channel.Close();
            }
        }
Beispiel #23
0
        public static async Task UseAsync(UseServiceDelegate codeBlock)
        {
            await Task.Run(() =>
            {
                IClientChannel proxy  = (IClientChannel)_channelFactory.CreateChannel();
                bool success          = false;
                bool getResultSuccess = false;

                try
                {
                    codeBlock((IImoutoWCFService)proxy);
                    getResultSuccess = true;

                    proxy.Close();
                    success = true;
                }
                catch (Exception ex)
                {
                    try
                    {
                        proxy.Close();
                        success = true;
                    }
                    catch
                    {
                    }

                    if (!getResultSuccess)
                    {
                        throw ex;
                    }
                }
                finally
                {
                    if (!success)
                    {
                        proxy.Abort();
                    }
                }
            });
        }
Beispiel #24
0
 public void Close()
 {
     if (!closed)
     {
         closed = true;
         clientChannel.Close();
         clientChannel.UnbindAllEvents(clientHandlers);
         serverChannel.Close();
         serverChannel.UnbindAllEvents(serverHandlers);
         OnChannelClosed();
     }
 }
Beispiel #25
0
 public static void CleanUp(this IClientChannel proxy)
 {
     try
     {
         proxy.Close();
     }
     catch
     {
         proxy.Abort();
         throw;
     }
 }
Beispiel #26
0
 /// <summary>
 /// Close connection to service and dispose of it
 /// </summary>
 /// <param name="serviceProxy">Hydrated proxy</param>
 public static void CloseAndDispose(IClientChannel serviceProxy)
 {
     if (serviceProxy == null)
     {
         return;
     }
     if (serviceProxy.State == CommunicationState.Opened)
     {
         serviceProxy.Close();
     }
     serviceProxy.Dispose();
 }
Beispiel #27
0
 /// <summary>
 /// 关闭连接
 /// </summary>
 /// <returns></returns>
 public string closeCon(IOAGetData proxy)
 {
     try
     {
         IClientChannel x = (IClientChannel)proxy;
         x.Close();
         return(x.ToString());
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
 }
        public static TResult Use <TResult>(UseCollectionServiceDelegate <TResult> codeBlock)
        {
            IClientChannel proxy            = (IClientChannel)_channelFactory.CreateChannel();
            bool           success          = false;
            bool           getResultSuccess = false;
            TResult        result           = default(TResult);

            try
            {
                result           = codeBlock((IImoutoWCFCollectionService)proxy);
                getResultSuccess = true;

                proxy.Close();
                success = true;
            }
            catch (Exception ex)
            {
                try
                {
                    proxy.Close();
                    success = true;
                }
                catch { }

                if (!getResultSuccess)
                {
                    throw ex;
                }
            }
            finally
            {
                if (!success)
                {
                    proxy.Abort();
                }
            }

            return(result);
        }
Beispiel #29
0
        private void ChannelFaulted(object sender, EventArgs e)
        {
            IClientChannel channel = (IClientChannel)sender;

            try
            {
                channel.Close();
            }
            catch
            {
                channel.Abort();
            }
            throw new ApplicationException("Exc_ChannelFailure");
        }
Beispiel #30
0
        private void RemoveSellerIfExists(Uri request, string name)
        {
            if (FlightSearchLogic.Instance.delegates.ContainsKey(name))
            {
                ISellerService tsqs;
                bool           gotValue = FlightSearchLogic.Instance.delegates.TryGetValue(name, out tsqs);
                if (gotValue)
                {
                    IClientChannel currChannel = (IClientChannel)tsqs;
                    try
                    {
                        currChannel.Close();
                        currChannel.Abort();
                    }
                    catch (Exception)
                    {
                        currChannel.Abort();
                        Console.WriteLine("Closing of stale channel {0} failed, ignoring", currChannel.RemoteAddress.Uri.ToString());
                    }
                    ISellerService victimChannel;
                    FlightSearchLogic.Instance.delegates.TryRemove(name, out victimChannel);
                    Console.WriteLine("Successfully remove old seller {0} by name", name);
                }
            }


            foreach (var seller in FlightSearchLogic.Instance.delegates)
            {
                IClientChannel currChannel = ((IClientChannel)seller.Value);

                if (currChannel.RemoteAddress.Uri.Equals(request))
                {
                    Console.WriteLine("Detected connection retry by {0} from {1} ,removing old connection", name, request.ToString());
                    // Close this channel
                    try
                    {
                        currChannel.Close();
                        currChannel.Abort();
                    }
                    catch (Exception)
                    {
                        currChannel.Abort();
                        Console.WriteLine("Closing of stale channel {0} failed, ignoring", currChannel.RemoteAddress.Uri.ToString());
                    }
                    ISellerService victimChannel;
                    FlightSearchLogic.Instance.delegates.TryRemove(seller.Key, out victimChannel);
                }
            }
        }
        public static void Use(UseCollectionServiceDelegate codeBlock)
        {
            IClientChannel proxy            = (IClientChannel)_channelFactory.CreateChannel();
            bool           success          = false;
            bool           getResultSuccess = false;

            try
            {
                codeBlock((IImoutoWCFCollectionService)proxy);
                getResultSuccess = true;

                proxy.Close();
                success = true;
            }
            catch (Exception ex)
            {
                try
                {
                    proxy.Close();
                    success = true;
                }
                catch { }

                if (!getResultSuccess)
                {
                    throw ex;
                }
            }
            finally
            {
                if (!success)
                {
                    proxy.Abort();
                }
            }
        }
Beispiel #32
0
 /// <summary>
 /// After sending, we check if the write was successful or if it was a fire-and-forget.
 /// </summary>
 /// <param name="sendTask">The task of the send operation.</param>
 /// <param name="tcsResponse"></param>
 /// <param name="isFireAndForget">True, if we don't expect a response message.</param>
 /// <param name="channel"></param>
 private async Task AfterSendAsync(Task sendTask, TaskCompletionSource<Message.Message> tcsResponse, bool isFireAndForget, IClientChannel channel)
 {
     // TODO use for UDP connections, too
     await sendTask;
     if (sendTask.IsFaulted)
     {
         string msg = String.Format("Failed to write channel the request {0} {1}.", tcsResponse.Task.AsyncState,
             sendTask.Exception);
         Logger.Warn(msg);
         tcsResponse.SetException(sendTask.TryGetException());
     }
     if (isFireAndForget)
     {
         Logger.Debug("Fire and forget message {0} sent. Close channel {1} now. {0}", tcsResponse.Task.AsyncState, channel);
         tcsResponse.SetResult(null); // set FF result
         // close channel now
     }
     else
     {
         //.NET specific, we wait here for the response
         // receive response message
         // processes client-side inbound pipeline
         await channel.ReceiveMessageAsync();
     }
     channel.Close(); // TODO not needed, receive method closes...
 }
 private static void CloseChannel(IClientChannel channel)
 {
     try
     {
         channel.Close();
     }
     catch (TimeoutException)
     {
         channel.Abort();
     }
     catch (CommunicationException)
     {
         channel.Abort();
     }
     catch (Exception)
     {
         channel.Abort();
         throw;
     }
 }