public void connect(String url, IAudioServiceCallBack callback, EventHandler openedEvt = null, EventHandler faultEvt = null) //url = "net.tcp://localhost:8080/AudioService"
        {
            try
            {
                 duplex = new DuplexChannelFactory<IAudioService>(callback, new NetTcpBinding(),
                     new EndpointAddress(url));
                
                 service = duplex.CreateChannel();
                 channel = (ICommunicationObject)service;
                 IClientChannel c = (IClientChannel)channel;
                 c.OperationTimeout = TimeSpan.FromSeconds(5);
                 
                 channel.Opened += new EventHandler(delegate(object o, EventArgs e)
                    {
                        Console.WriteLine("Connection ok!");
                    });

                if(openedEvt != null)
                 channel.Opened += openedEvt;
                if(faultEvt != null)
                 channel.Faulted += faultEvt;
                 channel.Faulted += new EventHandler(delegate(object o, EventArgs e)
                    {
                        Console.WriteLine("Connection lost");
                    });

            }
            catch (Exception e)
            {
                Console.WriteLine("Connection error: " + e.Message);
            }
        }
 public void BeginTest()
 {
     repo = new MockRepository();
     channelFactory = repo.StrictMock<ICanCreateChannels<IService>>();
     communicationObject = repo.StrictMultiMock<ICommunicationObject>(typeof(IService));
     manager = new SingleActionChannelManager<IService>(channelFactory);
 }
Esempio n. 3
0
 /// <summary>
 /// Creates a new client channel if the communication object is null or
 /// is faulted, closed or closing.
 /// </summary>
 private void InitChannel()
 {
     lock (_padlock)
     {
         if (_commObj == null || 
             (_commObj.State != CommunicationState.Opened &&
             _commObj.State != CommunicationState.Opening))
         {
             if (!string.IsNullOrEmpty(_configurationName))
             {
                 _client = new ChannelFactory<IProxyTraceService>(_configurationName).CreateChannel();
             }
             else
             {
                 // Todo - is None really the best choice of security mode?
                 // maybe we should secure the transport by default???
                 NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
                 EndpointAddress address = new EndpointAddress(DefaultEndpointAddress);
                 _client = ChannelFactory<IProxyTraceService>.CreateChannel(binding, address);
                 
             }
             _commObj = (ICommunicationObject)_client;
         }
     }
 }
        public static void CloseCommunicationObject(ICommunicationObject communicationObject, TimeSpan timeout)
        {
            if (communicationObject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("communicationObject");
            }

            bool flag = true;
            try
            {
                if (communicationObject.State == CommunicationState.Opened)
                {
                    communicationObject.Close(timeout);
                    flag = false;
                }
            }
            catch (CommunicationException communicatioException)
            {
                DiagnosticUtility.TraceHandledException(communicatioException, TraceEventType.Information);
            }
            catch (TimeoutException timeoutException)
            {
                DiagnosticUtility.TraceHandledException(timeoutException, TraceEventType.Information);
            }
            finally
            {
                if (flag)
                {
                    communicationObject.Abort();
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// The constructor.
        /// </summary>
        /// <param name="binding">The binding.</param>
        /// <param name="endpointAddress">The endpoint address.</param>
        /// <param name="hostReconnectIntervalMilliseconds">The cache host reconnect interval, in milliseconds.</param>
        public CommunicationClient(Binding binding, EndpointAddress endpointAddress, int hostReconnectIntervalMilliseconds)
        {
            // Sanitize
            if (binding == null)
            {
                throw new ArgumentNullException("binding");
            }
            if (endpointAddress == null)
            {
                throw new ArgumentNullException("endpointAddress");
            }
            if (hostReconnectIntervalMilliseconds <= 0)
            {
                throw new ArgumentException("must be greater than 0", "hostReconnectIntervalMilliseconds");
            }

            // Initialize the channel factory with the binding and endpoint address
            _channelFactory = new ChannelFactory<IClientToCacheContract>(binding, endpointAddress);

            // Set the cache host reconnect interval
            _hostReconnectIntervalMilliseconds = hostReconnectIntervalMilliseconds;

            // Initialize WCF
            _proxy = _channelFactory.CreateChannel();
            _proxyComm = _proxy as ICommunicationObject;

            // Set connected before opening to avoid a race
            _isConnected = true;

            // Initialize and configure the reconnect timer to never fire
            _reconnectTimer = new Timer(ReconnectToServer, null, Timeout.Infinite, Timeout.Infinite);
        }
 /// <summary>
 /// Stores the given value into backing store for retrieval later.
 /// </summary>
 /// <param name="newValue">The object being stored.</param>
 protected override void SynchronizedSetValue(object newValue)
 {
     _communicationObject = newValue as ICommunicationObject;
     if (_communicationObject == null)
         throw new InvalidOperationException(
             "newValue is not an ICommunicationObject. The ContainerControlledCommunicationObjectLifetimeManager is only meant to be used for WCF channels and other communication objects.");
 }
        // ReSharper restore MemberCanBePrivate.Global

        #endregion

        #region Protected Methods

        private void CloseProxy(ICommunicationObject co)
        {
            if (!m_Disposed)
            {
                CommunicationProxyHelper.Close(co);
            }
        }
        protected RandomDelaySendsAsyncResult(int numSends, TimeSpan maxDelay, ICommunicationObject channel, Random random, AsyncCallback callback, object state)
            : base(callback, state)
        {
            Fx.Assert(numSends > 0, "The numSends must be positive.");
            Fx.Assert(maxDelay >= TimeSpan.Zero, "The maxDelay must be non negative.");

            this.onTimerCallback = new Action<object>(OnTimer);
            this.onSendCompletedCallback = Fx.ThunkCallback(new AsyncCallback(OnSendCompleted));
            this.channel = channel;
            if (this.channel != null)
            {
                this.onCloseCompletedCallback = Fx.ThunkCallback(new AsyncCallback(OnCloseCompleted));
            }
            this.numSends = numSends;
            this.maxDelay = maxDelay;
            this.completesCounter = 0;
            this.sendCompletesCounter = 0;
            this.cancelled = false;
            this.thisLock = new object();
            if (maxDelay != TimeSpan.Zero)
            {
                this.delaysInTicks = new long[numSends];
                Random innerRandom = (random != null) ? random : new Random();
                for (int i = 0; i < this.numSends; i++)
                {
                    this.delaysInTicks[i] = RandomDelay(innerRandom, maxDelay.Ticks);
                }
                Array.Sort<long>(this.delaysInTicks);
            }
        }
        /// <summary>Disposes the service client. </summary>
        /// <param name="service">The service client. </param>
        /// <param name="isDisposed">The reference to a value indicating whether the service is disposed. </param>
        public static void Dispose(ICommunicationObject service, ref bool isDisposed)
        {
            if (isDisposed)
                return;

            try
            {
                if (service.State == CommunicationState.Faulted)
                    service.Abort();
                else
                {
                    try
                    {
                        service.Close();
                    }
                    catch (Exception closeException)
                    {
                        try
                        {
                            service.Abort();
                        }
                        catch (Exception abortException)
                        {
                            throw new AggregateException(closeException, abortException);
                        }
                        throw;
                    }
                }
            }
            finally
            {
                isDisposed = true;
            }
        }
Esempio n. 10
0
 private static Task OpenAsync(ICommunicationObject commObj)
 {
     return Task.Factory.FromAsync(
         (c, s) => ((ICommunicationObject)s).BeginOpen(c, s),
         r => ((ICommunicationObject)r.AsyncState).EndOpen(r),
         commObj);
 }
Esempio n. 11
0
		public OrationiSlave()
		{
			Binding binding = new NetTcpBinding(SecurityMode.None);
			EndpointAddress defaultEndpointAddress = new EndpointAddress("net.tcp://localhost:57344/Orationi/Master/v1/");
			EndpointAddress discoveredEndpointAddress = DiscoverMaster();
			ContractDescription contractDescription = ContractDescription.GetContract(typeof(IOrationiMasterService));
			ServiceEndpoint serviceEndpoint = new ServiceEndpoint(contractDescription, binding, discoveredEndpointAddress ?? defaultEndpointAddress);
			var channelFactory = new DuplexChannelFactory<IOrationiMasterService>(this, serviceEndpoint);

			try
			{
				channelFactory.Open();
			}
			catch (Exception ex)
			{
				channelFactory?.Abort();
			}

			try
			{
				_masterService = channelFactory.CreateChannel();
				_communicationObject = (ICommunicationObject)_masterService;
				_communicationObject.Open();
			}
			catch (Exception ex)
			{
				if (_communicationObject != null && _communicationObject.State == CommunicationState.Faulted)
					_communicationObject.Abort();
			}
		}
        /// <summary>
        /// Creates a <see cref="Scope"/> that safely closes the specified <see cref="ICommunicationObject"/>.
        /// </summary>
        /// <remarks>The Scope, when disposed, will Close or Abort the session, as appropriate. </remarks>
        /// <param name="client">The client.</param>
        /// <returns></returns>
        public static Scope CreateScope(ICommunicationObject client)
        {
            if (client == null)
                throw new ArgumentNullException("client");

            return Scope.Create(() => client.CloseOrAbort());
        }
Esempio n. 13
0
 protected override void OnStop()
 {
     if (CommunicationObject != null)
     {
         CommunicationObject.Close();
         CommunicationObject = null;
     }
     base.OnStop();
 }
 public void Init()
 {
     _browserApi = Substitute.For<IBrowsersManagerApi, ICommunicationObject>();
     _serviceStarter = Substitute.For<IServiceBuilder<IBrowsersManagerApi>>();
     _serviceStarter.CreateServiceAndTryToConnect().Returns(_browserApi);
     _uiHelper = Substitute.For<IUiHelper>();
     _log = Substitute.For<ILogger>();
     _communicationObject = (ICommunicationObject)_browserApi;
     _browserWindowsCommunicator = new BrowserWindowsCommunicator(_serviceStarter, _uiHelper, _log);
 }
        internal static void Abort(ICommunicationObject commObj, object identifier)
        {
            if (TD.RoutingServiceAbortingChannelIsEnabled())
            {
                TD.RoutingServiceAbortingChannel(identifier != null ? identifier.ToString() : string.Empty);
            }

            //The Exception contract for ICommunicationObject.Abort is to never throw, anything else is a fatal error.
            commObj.Abort();
        }
Esempio n. 16
0
 public void Init()
 {
     _service = Substitute.For<IBrowsersManagerApi, ICommunicationObject>();
     _serviceStarter = Substitute.For<IServiceBuilder<IBrowsersManagerApi>>();
     _serviceStarter.CreateServiceAndTryToConnect().Returns(_service);
     _uiHelper = Substitute.For<IUiHelper>();
     _log = Substitute.For<ILogger>();
     _communicationObject = (ICommunicationObject)_service;
     _serviceClient = new AbstractServiceClient<IBrowsersManagerApi>(_serviceStarter, _uiHelper, _log);
 }
Esempio n. 17
0
 public static void CloseClient(ICommunicationObject client)
 {
     if (client != null && client.State == CommunicationState.Faulted)
     {
         client.Abort();
     }
     else
     {
         client.Close();
     }
 }
Esempio n. 18
0
 public FileSaver(Entity.UserIdentity userIdentity, IFileInfoProvider fileInfoProvider, bool useTempFile)
 {
     _userIdentity = userIdentity;
     _fileInfoProvider = fileInfoProvider;
     _useTempFile = useTempFile;
     if (OperationContext.Current != null && OperationContext.Current.Channel != null)
     {
         _communicationObject = OperationContext.Current.Channel;
         _communicationObject.Faulted += new EventHandler(Abort);
     }
     _beginTime = DateTime.Now;
 }
 /// <summary>
 /// Disposes the Lifetime manager an the attached communication object.
 /// </summary>
 /// <param name="disposing"></param>
 protected virtual void Dispose(bool disposing)
 {
     if (_communicationObject != null)
     {
         ChannelHelper.ProperClose(_communicationObject);
         var disposable = _communicationObject as IDisposable;
         if (disposable != null)
         {
             disposable.Dispose();
         }
         _communicationObject = null;
     }
 }
Esempio n. 20
0
        /// <summary>
        /// 查找记录表中最旧的一条记录
        /// </summary>
        /// <returns></returns>
        public virtual T FindFirst()
        {
            T result = null;

            IBaseService <T>     service = CreateClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.FindFirst();
            });

            return(result);
        }
    public void CreateNewChannel()
    {
        Channel = _factory.CreateChannel();
        ICommunicationObject c = Channel as ICommunicationObject;

        if (null == c)
        {
            throw new ArgumentException(
                      typeof(T) + " Can not be used as an ICommunicationObject");
        }
        c.Closed  += OnClose;
        c.Faulted += OnFaulted;
        c.Open();
    }
Esempio n. 22
0
        public List <MenuInfo> GetTopMenu(string systemType)
        {
            List <MenuInfo> result = new List <MenuInfo>();

            IMenuService         service = CreateSubClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.GetTopMenu(systemType);
            });

            return(result);
        }
Esempio n. 23
0
        /// <summary>
        /// 医疗绩效奖金明细表
        /// </summary>
        public List <YljxkhInfo> Yljxkh_FWP(int intRecordCount, int intPageSize, int intPageCount, string where)
        {
            List <YljxkhInfo> result = new List <YljxkhInfo>();

            IYljxkhService       service = CreateSubClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.Yljxkh_FWP(intRecordCount, intPageSize, intPageCount, where);
            });

            return(result);
        }
Esempio n. 24
0
 /// <summary>
 /// Checks that the service is initialized and raises an exception when it isn't
 /// </summary>
 /// <param name="comObject">The communication object to verify initialization</param>
 /// <returns>True if the object is initialized, false if the object was opened</returns>
 /// <exception cref="InvalidOperationException">When the client didn't initialize
 /// </exception>
 private bool CheckInitialized(ICommunicationObject comObject)
 {
     if (comObject == null)
     {
         throw new InvalidOperationException("Must call Initialize first");
     }
     else if (comObject.State == CommunicationState.Created)
     {
         comObject.Open();
         proxies.Add(comObject);
         return(false);
     }
     return(true);
 }
        /// <summary>
        /// Returns an observable sequence of terminating state changes for the <see cref="ICommunicationObject"/>.
        /// </summary>
        /// <param name="obj">An object that transitions between states.</param>
        /// <returns>An observable sequence that contains <see cref="CommunicationState"/> values representing the
        /// terminating states (<see cref="CommunicationState.Closing"/>, <see cref="CommunicationState.Closed"/>
        /// and <see cref="CommunicationState.Faulted"/>) of the <see cref="ICommunicationObject"/> as it transitions
        /// between them.</returns>
        /// <seealso href="http://msdn.microsoft.com/en-us/library/ms789041.aspx"/>
        public static IObservable <CommunicationState> TerminationObservable(this ICommunicationObject obj)
        {
            Contract.Requires(obj != null);
            Contract.Ensures(Contract.Result <IObservable <CommunicationState> >() != null);

            return(Observable.Defer(() =>
            {
                var closed = obj.ClosedObservable().PublishLast().RefCount();
                var closing = obj.ClosingObservable().TakeUntil(closed).PublishLast().RefCount();
                var faulted = obj.FaultedObservable().TakeUntil(closing.Amb(closed)).PublishLast().RefCount();

                return faulted.Merge(closing.Concat(closed));
            }));
        }
Esempio n. 26
0
        /// <summary>
        /// 根据指定条件,从数据库中删除指定对象
        /// </summary>
        /// <param name="condition">删除记录的条件语句</param>
        /// <returns>执行成功返回<c>true</c>,否则为<c>false</c>。</returns>
        public virtual bool DeleteByCondition(string condition)
        {
            bool result = false;

            IBaseService <T>     service = CreateClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.DeleteByCondition(condition);
            });

            return(result);
        }
        private static IObservable <CommunicationState> CreatedObservable(this ICommunicationObject obj)
        {
            Contract.Requires(obj != null);
            Contract.Ensures(Contract.Result <IObservable <CommunicationState> >() != null);

            if (obj.State == CommunicationState.Created)
            {
                return(Observable.Return(CommunicationState.Created));
            }
            else
            {
                return(Observable.Empty <CommunicationState>());
            }
        }
Esempio n. 28
0
        public List <MenuNodeInfo> GetTreeByID(string mainMenuID)
        {
            List <MenuNodeInfo> result = new List <MenuNodeInfo>();

            IMenuService         service = CreateSubClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.GetTreeByID(mainMenuID);
            });

            return(result);
        }
Esempio n. 29
0
        public bool SaveExcelData(List <TableMappingInfo> list)
        {
            bool result = false;

            ITableMappingService service = CreateSubClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.SaveExcelData(list);
            });

            return(result);
        }
Esempio n. 30
0
        /// <summary>
        /// 根据条件查询数据库,如果存在返回第一个对象
        /// </summary>
        /// <param name="condition">查询的条件</param>
        /// <param name="orderBy">排序条件</param>
        /// <returns>指定的对象</returns>
        public virtual T FindSingle2(string condition, string orderBy)
        {
            T result = null;

            IBaseService <T>     service = CreateClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.FindSingle2(condition, orderBy);
            });

            return(result);
        }
Esempio n. 31
0
        /// <summary>
        /// 插入指定对象到数据库中
        /// </summary>
        /// <param name="obj">指定的对象</param>
        /// <returns>执行成功返回新增记录的自增长ID。</returns>
        public virtual int Insert2(T obj)
        {
            int result = -1;

            IBaseService <T>     service = CreateClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.Insert2(obj);
            });

            return(result);
        }
Esempio n. 32
0
        /// <summary>
        /// 更新某个表一条记录(只适用于用单键)
        /// </summary>
        /// <param name="recordField">Hashtable:键[key]为字段名;值[value]为字段对应的值</param>
        /// <param name="primaryKeyValue">主键的值</param>
        public virtual bool UpdateFields(Hashtable recordField, object primaryKeyValue)
        {
            bool result = false;

            IBaseService <T>     service = CreateClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.UpdateFields(recordField, primaryKeyValue);
            });

            return(result);
        }
Esempio n. 33
0
        /// <summary>
        /// 如果不存在记录,则插入对象属性到数据库中
        /// </summary>
        /// <param name="obj">指定的对象</param>
        /// <param name="primaryKeyValue">主键的值</param>
        /// <returns>执行插入成功返回<c>true</c>,否则为<c>false</c>。</returns>
        public virtual bool InsertIfNew(T obj, object primaryKeyValue)
        {
            bool result = false;

            IBaseService <T>     service = CreateClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.InsertIfNew(obj, primaryKeyValue);
            });

            return(result);
        }
Esempio n. 34
0
        /// <summary>
        /// 医疗绩效奖金明细表Calculate
        /// </summary>
        public DataTable Yljxjjmx_Cal(string strYear, string strMonth, string strKSID, string strZXZD_ID)
        {
            DataTable result = new DataTable();

            IYljxjjmxService     service = CreateSubClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.Yljxjjmx_Cal(strYear, strMonth, strKSID, strZXZD_ID);
            });

            return(result);
        }
Esempio n. 35
0
        /// <summary>
        /// 根据ID字符串(逗号分隔)获取对象列表
        /// </summary>
        /// <param name="idString">ID字符串(逗号分隔)</param>
        /// <returns>符合条件的对象列表</returns>
        public virtual List <T> FindByIDs(string idString)
        {
            List <T> result = new List <T>();

            IBaseService <T>     service = CreateClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.FindByIDs(idString);
            });

            return(result);
        }
Esempio n. 36
0
        /// <summary>
        /// 返回数据库所有的对象集合
        /// </summary>
        /// <param name="orderBy">自定义排序语句,如Order By Name Desc;如不指定,则使用默认排序</param>
        /// <returns>指定对象的集合</returns>
        public virtual List <T> GetAll2(string orderBy)
        {
            List <T> result = new List <T>();

            IBaseService <T>     service = CreateClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.GetAll2(orderBy);
            });

            return(result);
        }
Esempio n. 37
0
        /// <summary>
        /// 获取表的所有记录数量
        /// </summary>
        /// <returns></returns>
        public virtual int GetRecordCount()
        {
            int result = 0;

            IBaseService <T>     service = CreateClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.GetRecordCount();
            });

            return(result);
        }
Esempio n. 38
0
        /// <summary>
        /// 执行SQL查询语句,返回所有记录的DataTable集合。
        /// </summary>
        /// <param name="sql">SQL查询语句</param>
        /// <returns></returns>
        public virtual DataTable SqlTable(string sql)
        {
            DataTable result = new DataTable();

            IBaseService <T>     service = CreateClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.SqlTable(sql);
            });

            return(result);
        }
Esempio n. 39
0
 private void CloseChannel(ICommunicationObject channel)
 {
     try
     {
         channel.Close();
     }
     catch (Exception ex)
     {
     }
     finally
     {
         channel.Abort();
     }
 }
Esempio n. 40
0
        public List <MenuNodeInfo> GetTreeFunction(string systemType, string Functions)
        {
            List <MenuNodeInfo> result = new List <MenuNodeInfo>();

            IMenuService         service = CreateSubClient();
            ICommunicationObject comm    = service as ICommunicationObject;

            comm.Using(client =>
            {
                result = service.GetTreeFunction(systemType, Functions);
            });

            return(result);
        }
Esempio n. 41
0
        public ServerSideFileReceive(UserIdentity userIdentity, /*IResourceEx<T> resourceEx*/IFileInfoProvider provider)
        {
            //_resourceEx = resourceEx;
            _userIdentity = userIdentity;
            //Resource = resource;
            _provider = provider;
            //_resourceFileInfo = _resource.ResourceInfo as ResourceFileInfo;
            if (OperationContext.Current != null && OperationContext.Current.Channel != null)
            {
                _communicationObject = OperationContext.Current.Channel;
                _communicationObject.Faulted += new EventHandler(Abort);
            }

        }
Esempio n. 42
0
        /// <summary>
        /// Safely disposes the channel by either closing or aborting it.
        /// </summary>
        /// <param name="communicationObject">The channel to dispose.</param>
        /// <param name="logger">A logger to be used for logging purposes.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="communicationObject"/> is null.</exception>
        public static async Task DisposeChannelAsync(this ICommunicationObject communicationObject, ILogger?logger = null)
        {
            _ = communicationObject ?? throw new ArgumentNullException(nameof(communicationObject));

            logger ??= NullLogger.Instance;

            try
            {
                switch (communicationObject.State)
                {
                case CommunicationState.Opened:
                    logger.LogDebug("Closing connection");
                    await communicationObject.CloseAsync().ConfigureAwait(false);

                    break;

                case CommunicationState.Faulted:
                    logger.LogDebug("Aborting connection");
                    communicationObject.Abort();
                    break;

                case CommunicationState.Closed:
                case CommunicationState.Closing:
                case CommunicationState.Created:
                case CommunicationState.Opening:
                    break;

                default:
                    throw new InvalidOperationException($"The channel is in an unexpected state: {communicationObject.State:G}");
                }
            }
            catch (CommunicationException ex)
            {
                logger.LogError(ex, "An error occurred while closing the connection");
                communicationObject.Abort();
            }
            catch (TimeoutException ex)
            {
                logger.LogError(ex, "An error occurred while closing the connection");
                communicationObject.Abort();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "An error occurred while closing the connection");
                communicationObject.Abort();

                throw;
            }
        }
Esempio n. 43
0
        /// <summary>
        /// 获取座位使用状态
        /// </summary>
        /// <param name="seatNo"></param>
        /// <returns></returns>
        public static EnterOutLogType GetSeatUsedState(string seatNo)
        {
            IWCFService.ISeatManageService seatService = WcfAccessProxy.ServiceProxy.CreateChannelSeatManageService();
            bool error = false;

            try
            {
                EnterOutLogInfo model = seatService.GetEnterOutLogInfoWithBookWaitBySeatNum(seatNo);
                if (model != null)
                {
                    SeatManage.EnumType.EnterOutLogType type = model.EnterOutState;
                    return(type);
                }
                else
                {
                    List <BespeakLogInfo> bespeakLogs = seatService.GetBespeakLogInfoBySeatNo(seatNo, DateTime.Now);
                    if (bespeakLogs.Count > 0 && bespeakLogs[0].BsepeakState == SeatManage.EnumType.BookingStatus.Waiting)
                    {
                        return(EnterOutLogType.BespeakWaiting);
                    }
                    return(EnterOutLogType.None);
                }
            }
            catch (Exception ex)
            {
                error = true;
                SeatManageComm.WriteLog.Write("获取座位状态失败:" + ex.Message);
                return(EnterOutLogType.None);
            }
            finally
            {
                ICommunicationObject ICommObjectService = seatService as ICommunicationObject;
                try
                {
                    if (ICommObjectService.State == CommunicationState.Faulted)
                    {
                        ICommObjectService.Abort();
                    }
                    else
                    {
                        ICommObjectService.Close();
                    }
                }
                catch
                {
                    ICommObjectService.Abort();
                }
            }
        }
Esempio n. 44
0
        public void Subscribe(SubscribeArg arg)
        {
            var newClientInfo = GetClientInfo();

            var callback = OperationContext.Current.GetCallbackChannel <IEventCallback>();

            arg.Username = arg.Username.ToLower();
            if (!_Subscribers.ContainsKey(arg.Username))
            {
                _Subscribers[arg.Username] = new SubscribeContext()
                {
                    Arg = arg, Callback = callback, Address = newClientInfo.Item1, Port = newClientInfo.Item2
                };
            }
            else
            {
                if (_Subscribers[arg.Username].Address != newClientInfo.Item1 || _Subscribers[arg.Username].Port != newClientInfo.Item2)
                {
                    _Subscribers[arg.Username] = new SubscribeContext()
                    {
                        Arg = arg, Callback = callback, Address = newClientInfo.Item1, Port = newClientInfo.Item2
                    };
                }
            }
            ICommunicationObject obj = (ICommunicationObject)callback;

            obj.Closed += (sender, args) =>
            {
                //current client closed, do nothing.
            };
            obj.Faulted += (sender, args) =>
            {
                //To do:
                //Record error
            };
            obj.Closing += (sender, args) =>
            {
                var currentCallback = sender as IEventCallback;
                _Subscribers.ToList().ForEach(context =>
                {
                    if (context.Value.Callback == currentCallback)
                    {
                        RemoveSubscriber(context.Value.Arg.Username);
                        ClientLostEvent?.Invoke(arg);
                    }
                });
            };
            NewClientSubscribedEvent?.Invoke(arg);
        }
        private void CloseOrAbortServiceChannelAndPerformExceptionBehaviours(ICommunicationObject communicationObject)
        {
            // Stop recursive or multiple calls
            if (this.isClosing || communicationObject == null || communicationObject.State == CommunicationState.Closed)
            {
                return;
            }

            this.isClosing = true;

            bool      isClosed       = false;
            Exception closeException = null;

            try
            {
                if (communicationObject.State != CommunicationState.Faulted)
                {
                    this.OnClosingChannel();

                    communicationObject.Close();
                    isClosed = true;

                    this.OnClosedChannel();
                }
            }
            catch (Exception ex)
            {
                // Handle the race condition where it might have faulted just after the If above.
                closeException = ex;
            }
            finally
            {
                if (closeException != null)
                {
                    this.TryToPerformCloseExceptionBehaviours(closeException);
                }

                // If the channel has not been closed yet because:
                // - State was Faulted; or
                // - An exception occurred while doing the Close()
                // Then do an Abort()
                if (!isClosed)
                {
                    this.AbortServiceChannel(communicationObject);
                }

                this.DisposeChannel();
            }
        }
Esempio n. 46
0
        private void CloseOrAbortService()
        {
            if (this._wcfService == null)
            {
                return;
            }

            ICommunicationObject wcfService = this._wcfService as ICommunicationObject;

            try
            {
                if (wcfService != null)
                {
                    if (wcfService.State != CommunicationState.Faulted)
                    {
                        wcfService.Close();
                    }
                    else
                    {
                        wcfService.Abort();
                    }
                }
            }
            catch (CommunicationException)
            {
                if (wcfService != null)
                {
                    wcfService.Abort();
                }
            }
            catch (TimeoutException)
            {
                if (wcfService != null)
                {
                    wcfService.Abort();
                }
            }
            catch
            {
                if (wcfService != null)
                {
                    wcfService.Abort();
                }
            }
            finally
            {
                this._wcfService = null;
            }
        }
Esempio n. 47
0
        /// <summary>
        /// 根据查询条件删除违规记录
        /// </summary>
        /// <param name="begDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <param name="roomNo">阅览室编号</param>
        /// <returns></returns>
        public static int DelBySearch(string begDate, string endDate, string roomNo)
        {
            IWCFService.ISeatManageService seatService = WcfAccessProxy.ServiceProxy.CreateChannelSeatManageService();
            List <ViolationRecordsLogInfo> vlists      = seatService.GetViolationRecordsLogs(null, roomNo, begDate + " 0:00:00", endDate + " 23:59:59", SeatManage.EnumType.LogStatus.Valid, SeatManage.EnumType.LogStatus.None);
            bool       error = false;
            List <int> lst   = new List <int>();

            try
            {
                if (vlists.Count > 0)
                {
                    foreach (ViolationRecordsLogInfo vlist in vlists)
                    {
                        vlist.Flag = SeatManage.EnumType.LogStatus.Fail;
                        seatService.UpdateViolationRecordsLog(vlist);
                        //SeatManage.ClassModel.ReaderNoticeInfo rni = new SeatManage.ClassModel.ReaderNoticeInfo();
                        //rni.CardNo = vlist.CardNo;
                        //rni.Note = string.Format("{0}记录的违规,{1},被管理员手动移除", vlist.EnterOutTime, vlist.Remark);
                        //SeatManage.Bll.T_SM_ReaderNotice.AddReaderNotice(rni);
                    }
                }
                return(vlists.Count);
            }
            catch (Exception ex)
            {
                error = true;
                SeatManageComm.WriteLog.Write("修改违规记录失败:" + ex.Message);
                return(-1);
            }
            finally
            {
                ICommunicationObject ICommObjectService = seatService as ICommunicationObject;
                try
                {
                    if (ICommObjectService.State == CommunicationState.Faulted)
                    {
                        ICommObjectService.Abort();
                    }
                    else
                    {
                        ICommObjectService.Close();
                    }
                }
                catch
                {
                    ICommObjectService.Abort();
                }
            }
        }
Esempio n. 48
0
        /// <summary>
        /// 返回数据库所有的对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="info">分页实体信息</param>
        /// <returns>指定对象的集合</returns>
        public virtual List <T> GetAllWithPager(ref PagerInfo info)
        {
            List <T>             result    = new List <T>();
            IBaseService <T>     service   = CreateClient();
            ICommunicationObject comm      = service as ICommunicationObject;
            PagerInfo            pagerInfo = info;

            comm.Using(client =>
            {
                result = service.GetAllWithPager(ref pagerInfo);
            });
            info.RecordCount = pagerInfo.RecordCount;

            return(result);
        }
 // TODO - document
 public static void DisposeSafely(this ICommunicationObject communicationObject)
 {
     if (communicationObject.State == CommunicationState.Faulted)
     {
         communicationObject.Abort();
     }
     else
     {
         communicationObject.Close();
     }
     if (communicationObject is IDisposable disposable)
     {
         disposable.Dispose();
     }
 }
Esempio n. 50
0
 private void CloseProxy(ICommunicationObject proxy)
 {
     if (proxy == null)
     {
         throw new ArgumentNullException();
     }
     if (proxy.State == CommunicationState.Faulted)
     {
         proxy.Abort();
     }
     else
     {
         proxy.Close();
     }
 }
Esempio n. 51
0
        void ICommunicationObject1_Faulted(object sender, EventArgs e)
        {
            Program.AASServiceClient = new AASServiceReference.AASServiceClient(Program.callbackInstance, Program.NetTcpBinding, Program.EndpointAddress);

            Program.AASServiceClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
            Program.AASServiceClient.ClientCredentials.UserName.UserName = this.comboBox用户名.Text;
            Program.AASServiceClient.ClientCredentials.UserName.Password = this.textBox密码.Text + "\t" + this.MAC;



            ICommunicationObject ICommunicationObject1 = Program.AASServiceClient as ICommunicationObject;

            ICommunicationObject1.Faulted += ICommunicationObject1_Faulted;
            ICommunicationObject1.Closed  += ICommunicationObject1_Closed;
        }
Esempio n. 52
0
 private static void CloseClient(ICommunicationObject client)
 {
     if (client.State == CommunicationState.Opened)
     {
         try
         {
             client.Close();
         }
         catch (CommunicationException)
         {
             client.Abort();
         }
         catch (TimeoutException)
         {
             client.Abort();
         }
     }
 }
Esempio n. 53
0
        public Result Execute(ICommunicationObject client, string service, System.Reflection.MethodBase method, params object[] data)
        {


            RemoteInvokeArgs info = new RemoteInvokeArgs();
            info.Interface = service;
            int index = method.Name.LastIndexOf('.');
            index = index>0?(index+1):0;
            info.Method = method.Name.Substring(index, method.Name.Length - index);
            info.Parameters = data;
            info.CommunicationObject = client;
            info.ParameterInfos = method.GetParameters();
            foreach (System.Reflection.ParameterInfo pi in method.GetParameters())
            {
                info.ParameterTypes.Add(pi.ParameterType.Name);
            }
            return Handler.Execute(info);

        }
        /// <summary>
        /// Initializes an instance of <see cref="WrappedRsaSecurityTokenAuthenticator"/>
        /// </summary>
        /// <param name="sessionTokenHandler">The sessionTokenHandler to wrap</param>
        /// <param name="wcfSessionAuthenticator">The wcf SessionTokenAuthenticator.</param>
        /// <param name="sctClaimsHandler">Handler that converts WCF generated IAuthorizationPolicy to <see cref="AuthorizationPolicy"/></param>
        /// <param name="exceptionMapper">Converts token validation exception to SOAP faults.</param>
        public WrappedSessionSecurityTokenAuthenticator( SessionSecurityTokenHandler sessionTokenHandler,
                                                         SecurityTokenAuthenticator wcfSessionAuthenticator,
                                                         SctClaimsHandler sctClaimsHandler,
                                                         ExceptionMapper exceptionMapper )
            : base()
        {
            if ( sessionTokenHandler == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "sessionTokenHandler" );
            }

            if ( wcfSessionAuthenticator == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "wcfSessionAuthenticator" );
            }

            if ( sctClaimsHandler == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "sctClaimsHandler" );
            }

            if ( exceptionMapper == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "exceptionMapper" );
            }

            _issuanceSecurityTokenAuthenticator = wcfSessionAuthenticator as IIssuanceSecurityTokenAuthenticator;
            if ( _issuanceSecurityTokenAuthenticator == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4244 ) );
            }

            _communicationObject = wcfSessionAuthenticator as ICommunicationObject;
            if ( _communicationObject == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4245 ) );
            }

            _sessionTokenHandler = sessionTokenHandler;
            _sctClaimsHandler = sctClaimsHandler;

            _exceptionMapper = exceptionMapper;
        }
Esempio n. 55
0
        private void CompleteClose(ICommunicationObject communicationObject, IAsyncResult result)
        {
            Exception closeException = null;
            try
            {
                communicationObject.EndClose(result);
            }
#pragma warning suppress 56500 // covered by FxCOP
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                closeException = e;
                communicationObject.Abort();
            }

            Decrement(result.CompletedSynchronously, closeException);
        }
 public static void Close(ICommunicationObject co)
 {
     if (co == null)
     {
         return;
     }
     try
     {
         switch (co.State)
         {
             case CommunicationState.Closed:
             case CommunicationState.Closing:
                 break;
             case CommunicationState.Faulted:
                 co.Abort();
                 break;
             case CommunicationState.Created:
             case CommunicationState.Opened:
             case CommunicationState.Opening:
                 co.Close();
                 break;
             default:
                 co.Abort();
                 break;
         }
     }
     catch (Exception e)
     {
         s_Logger.Fatal(co, e);
         // ReSharper disable EmptyGeneralCatchClause
         try
         {
             co.Abort();
         }
         catch
         {
         }
         // ReSharper restore EmptyGeneralCatchClause
     }
 }
Esempio n. 57
0
        private static async Task CloseAsync(ICommunicationObject commObj)
        {
            try
            {
                await Task.Factory.FromAsync(
                    (c, s) => ((ICommunicationObject)s).BeginClose(c, s),
                    r => ((ICommunicationObject)r.AsyncState).EndClose(r),
                    commObj);
                commObj = null;
            }
            catch (CommunicationException)
            {
            }
            catch (TimeoutException)
            {
            }

            if (commObj != null)
            {
                commObj.Abort();
            }
        }
Esempio n. 58
0
 private void Done()
 {
     if (_communicationObject != null)
     {
         _communicationObject.Faulted -= Abort;
         _communicationObject = null;
     }
 }
Esempio n. 59
0
 public CallbackState(CloseCollectionAsyncResult result, ICommunicationObject instance)
 {
     _result = result;
     _instance = instance;
 }
Esempio n. 60
0
        //public IPresentationDAL PresentationDAL{get; set;}

        #region ILockService Members

        public bool AcquireLock(ICommunicationObject communicationObject, UserIdentity user, ObjectKey objectKey, RequireLock requireLock)
        {
            return _lockingStorage.AcquireLock(communicationObject, user, objectKey, requireLock);
        }