using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using Aitex.Core.RT.Log; using System.Windows; using Aitex.Core.Utilities; using System.Threading; namespace Aitex.Core.WCF { public class ServiceClientWrapper { ChannelFactory _factory; T _proxy; bool _isInError = false; string _serviceName; Retry _retryConnect = new Retry(); public ServiceClientWrapper(string endpointConfigurationName, string name) { _serviceName = name; try { _factory = new ChannelFactory(endpointConfigurationName); } catch (Exception ex) { MessageBox.Show("Cannot create Service " + name + ",Check configuration:" + endpointConfigurationName); LOG.Error("Cannot create Service " + name + ",Check configuration:" +endpointConfigurationName, ex); } } public ServiceClientWrapper(string endpointConfigurationName, string name, EndpointAddress address) { _serviceName = name; try { _factory = new ChannelFactory(endpointConfigurationName, address); } catch (Exception ex) { MessageBox.Show("Cannot create Service " + name + ",Check configuration:" + endpointConfigurationName); LOG.Error("Cannot create Service " + name + ",Check configuration:" + endpointConfigurationName, ex); } } public void Invoke(Action action) { if (_factory == null) return; if (_proxy == null) { _proxy = _factory.CreateChannel(); } for (int i = 0; i < 2; i++) { if (Do(action)) break; Thread.Sleep(10); } } bool Do(Action action) { if (_proxy != null && ((IClientChannel)_proxy).State == CommunicationState.Faulted) { ((IClientChannel)_proxy).Abort(); _proxy = _factory.CreateChannel(); } try { action(_proxy); if (_isInError) { _isInError = false; LOG.Info(_serviceName + " Service Recovery"); } return true; } catch (EndpointNotFoundException ex) { if (!_isInError) { _isInError = true; LOG.Error(_serviceName + " The connection has been disconnected。", ex); } } catch (ProtocolException ex) { if (!_isInError) { _isInError = true; LOG.Error(_serviceName + " Service program exception。", ex); } } catch (Exception ex) { if (!_isInError) { _isInError = true; LOG.Error(_serviceName + " Service exception", ex); } } ((IClientChannel)_proxy).Abort(); _proxy = _factory.CreateChannel(); return false; } } }