Example #1
0
        private void _LogOut()
        {
            if (LobbyViewModel.Instance.Connection != null)
            {
                try
                {
                    LobbyViewModel.Instance.Connection.Logout();
                    LobbyViewModel.Instance.Connection = null;
                }
                catch (Exception)
                {
                }
            }

            if (_channelFactory != null)
            {
                try
                {
                    _channelFactory.Close();
                }
                catch (Exception)
                {
                    _channelFactory.Abort();
                }
                _channelFactory = null;
            }
        }
        /// <summary>
        /// 发送心跳
        /// </summary>
        /// <returns></returns>
        public static bool Heartbeat()
        {
            try
            {
                bool ret = false;
                IWCFHandlerService _wcfService = AppGlobal.cache.GetData("WCFService") as IWCFHandlerService;
                using (var scope = new OperationContextScope(_wcfService as IContextChannel))
                {
                    var router = System.ServiceModel.Channels.MessageHeader.CreateHeader("routerID", myNamespace, AppGlobal.cache.GetData("routerID").ToString());
                    OperationContext.Current.OutgoingMessageHeaders.Add(router);
                    ret = _wcfService.Heartbeat(AppGlobal.cache.GetData("WCFClientID").ToString());

                    if (WcfClientManage.ServerConfigRequestState == false)
                    {
                        //重新获取服务端配置,如:是否压缩Json、是否加密Json
                        string serverConfig = _wcfService.ServerConfig();
                        WcfClientManage.IsHeartbeat      = serverConfig.Split(new char[] { '#' })[0] == "1" ? true : false;
                        WcfClientManage.HeartbeatTime    = Convert.ToInt32(serverConfig.Split(new char[] { '#' })[1]);
                        WcfClientManage.IsMessage        = serverConfig.Split(new char[] { '#' })[2] == "1" ? true : false;
                        WcfClientManage.MessageTime      = Convert.ToInt32(serverConfig.Split(new char[] { '#' })[3]);
                        WcfClientManage.IsCompressJson   = serverConfig.Split(new char[] { '#' })[4] == "1" ? true : false;
                        WcfClientManage.IsEncryptionJson = serverConfig.Split(new char[] { '#' })[5] == "1" ? true : false;

                        if (WcfClientManage.IsHeartbeat)
                        {
                            //开启发送心跳
                            if (timer == null)
                            {
                                StartTimer();
                            }
                            else
                            {
                                timer.Start();
                            }
                        }
                        else
                        {
                            if (timer != null)
                            {
                                timer.Stop();
                            }
                        }
                        WcfClientManage.ServerConfigRequestState = true;
                    }
                }

                if (ret == false)            //表示服务主机关闭过,丢失了clientId,必须重新创建连接
                {
                    mChannelFactory.Abort(); //关闭原来通道
                    CreateConnection(AppGlobal.cache.GetData("ClientService") as IClientService);
                }
                return(ret);
            }
            catch
            {
                WcfClientManage.ServerConfigRequestState = false;
                ReConnection(false);//连接服务主机失败,重连
                return(false);
            }
        }
Example #3
0
 private void ChannelFactory_Faulted(object sender, EventArgs e)
 {
     try
     {
         ShowCaseUtil.Logger.Log(AppDomain.CurrentDomain.SetupInformation.ApplicationName + " SubscriptionServiceManager Channel Fault", ShowCaseUtil.LogLevel.Verbose);
         m_ChannelFactory.Abort();
     }
     finally
     {
         m_ChannelFactory = null;
         MakeTraceProxy(this, null);
     }
 }
Example #4
0
        bool CheckConnection()
        {
            if (!IsConnected)
            {
                try
                {
                    bool isReconnected = false;
                    if (_channelFactory != null)
                    {
                        _channelFactory.Abort();
                        isReconnected = true;
                    }

                    var ctx = new InstanceContext(this.Implementation);
                    _channelFactory = new DuplexChannelFactory <INovaAlertService>(ctx, "NovaAlertService_NetTcp");
                    _realProxy      = _channelFactory.CreateChannel();
                    if (isReconnected)
                    {
                        System.Threading.Thread.Sleep(1000);
                    }
                    _realProxy.Ping();
                    Application.Current.Dispatcher.Invoke(new Action <bool>(UpdateConnectionInfo), true);
                }
                catch (Exception ex)
                {
                    Application.Current.Dispatcher.Invoke(new Action <bool>(UpdateConnectionInfo), false);
                    LogService.Logger.Error(ex);
                }
            }

            return(this.IsConnected);
        }
    public static void ServiceContract_TypedProxy_AsyncTask_CallbackReturn()
    {
        DuplexChannelFactory<IWcfDuplexTaskReturnService> factory = null;
        Guid guid = Guid.NewGuid();

        NetTcpBinding binding = new NetTcpBinding();
        binding.Security.Mode = SecurityMode.None;

        DuplexTaskReturnServiceCallback callbackService = new DuplexTaskReturnServiceCallback();
        InstanceContext context = new InstanceContext(callbackService);

        try
        {
            factory = new DuplexChannelFactory<IWcfDuplexTaskReturnService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_TaskReturn_Address));
            IWcfDuplexTaskReturnService serviceProxy = factory.CreateChannel();

            Task<Guid> task = serviceProxy.Ping(guid);

            Guid returnedGuid = task.Result;

            Assert.Equal(guid, returnedGuid);

            factory.Close();
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }
    }
        /// <summary>
        /// Use this for contracts which have a callback interface.
        /// </summary>
        public static void UsingDuplex <TServiceContract>(Action <TServiceContract> action, object callbackImplementation, string endpointConfigurationName)
        {
            using (var channelFactory = new DuplexChannelFactory <TServiceContract>(callbackImplementation, endpointConfigurationName))
            {
                channelFactory.Open();
                var success = false;
                try
                {
                    var client = channelFactory.CreateChannel();
                    action(client);

                    if (channelFactory.State != CommunicationState.Faulted)
                    {
                        channelFactory.Close();
                        success = true;
                    }
                }
                finally
                {
                    if (!success)
                    {
                        channelFactory.Abort();
                    }
                }
            }
        }
Example #7
0
    public static void ServiceContract_TypedProxy_AsyncTask_CallbackReturn()
    {
        DuplexChannelFactory <IWcfDuplexTaskReturnService> factory = null;
        Guid guid = Guid.NewGuid();

        NetTcpBinding binding = new NetTcpBinding();

        binding.Security.Mode = SecurityMode.None;

        DuplexTaskReturnServiceCallback callbackService = new DuplexTaskReturnServiceCallback();
        InstanceContext context = new InstanceContext(callbackService);

        try
        {
            factory = new DuplexChannelFactory <IWcfDuplexTaskReturnService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_TaskReturn_Address));
            IWcfDuplexTaskReturnService serviceProxy = factory.CreateChannel();

            Task <Guid> task = serviceProxy.Ping(guid);

            Guid returnedGuid = task.Result;

            Assert.Equal(guid, returnedGuid);

            factory.Close();
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }
    }
Example #8
0
    public static void RequestResponseOverWebSocketManually_Echo_RoundTrips_Guid()
    {
        DuplexChannelFactory<IWcfDuplexService> factory = null;
        Guid guid = Guid.NewGuid();

        NetHttpBinding binding = new NetHttpBinding();
        binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always;

        WcfDuplexServiceCallback callbackService = new WcfDuplexServiceCallback();
        InstanceContext context = new InstanceContext(callbackService);

        try
        {
            factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, new EndpointAddress(Endpoints.NetHttpWebSocketTransport_Address));
            IWcfDuplexService duplexProxy = factory.CreateChannel();

            Task.Run(() => duplexProxy.Ping(guid));
            Guid returnedGuid = callbackService.CallbackGuid;

            Assert.True(guid == returnedGuid, string.Format("The sent GUID does not match the returned GUID. Sent '{0}', Received: '{1}'", guid, returnedGuid));
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }
    }
Example #9
0
        /// <summary>
        /// 释放连接
        /// </summary>
        public void Dispose()
        {
            UnConnection();

            try
            {
                if (mChannelFactory != null)
                {
                    mChannelFactory.Close();
                }
                if (mfileChannelFactory != null)
                {
                    mfileChannelFactory.Close();
                }
            }
            catch
            {
                if (mChannelFactory != null)
                {
                    mChannelFactory.Abort();
                }
                if (mfileChannelFactory != null)
                {
                    mfileChannelFactory.Abort();
                }
            }
        }
Example #10
0
    public static void RequestResponseOverWebSocketManually_Echo_RoundTrips_Guid()
    {
        DuplexChannelFactory <IWcfDuplexService> factory = null;
        Guid guid = Guid.NewGuid();

        NetHttpBinding binding = new NetHttpBinding();

        binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always;

        WcfDuplexServiceCallback callbackService = new WcfDuplexServiceCallback();
        InstanceContext          context         = new InstanceContext(callbackService);

        try
        {
            factory = new DuplexChannelFactory <IWcfDuplexService>(context, binding, new EndpointAddress(Endpoints.NetHttpWebSocketTransport_Address));
            IWcfDuplexService duplexProxy = factory.CreateChannel();

            Task.Run(() => duplexProxy.Ping(guid));
            Guid returnedGuid = callbackService.CallbackGuid;

            Assert.True(guid == returnedGuid, string.Format("The sent GUID does not match the returned GUID. Sent '{0}', Received: '{1}'", guid, returnedGuid));
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }
    }
        public static bool Connect()
        {
            messageHandler = new MessageHandler();

            //create channel
            //InstanceContext represents the running instance of the service.
            //OperationContext is the instance of the client accessing the service.
            InstanceContext instanceContext = new InstanceContext(messageHandler);

            _factory = new DuplexChannelFactory <IChannel>(instanceContext, "GridEndpoint");
            channel  = _factory.CreateChannel();


            try
            {
                ((ICommunicationObject)channel).Open();
            }
            catch (CommunicationException e) {
                ((ICommunicationObject)channel).Abort();
                _factory.Abort();

                XMLLogger.WriteErrorMessage("Connector", "Could not find resolver.  If you are using a custom resolver, please ensure that the service is running.");
                XMLLogger.WriteErrorMessage("Connector", "System Error: " + e.ToString());

                return(false);
            }

            return(true);
        }
        public bool UnInitialize()
        {
            lock (this)
            {
                lock (Clients)
                {
                    Clients.Remove(this);
                }


                if (_proxyServerInterface != null)
                {
                    ((IChannel)_proxyServerInterface).Opened  -= new EventHandler(MessageContainerTransportClient_Opened);
                    ((IChannel)_proxyServerInterface).Opening -= new EventHandler(MessageContainerTransportClient_Opening);
                    ((IChannel)_proxyServerInterface).Faulted -= new EventHandler(MessageContainerTransportClient_Faulted);
                    ((IChannel)_proxyServerInterface).Closing -= new EventHandler(MessageContainerTransportClient_Closing);

                    ((IChannel)_proxyServerInterface).Abort();
                    _proxyServerInterface = null;
                }

                if (_channelFactory != null)
                {
                    _channelFactory.Abort();
                    _channelFactory = null;
                }

                _connectingEvent.Reset();
            }

            return(true);
        }
Example #13
0
        public static string Login(string userName, string password)
        {
            OpenChannel();
            Report.log(DeviceToReport.Client_Proxy, LogLevel.Information, $"Channel opened for client {userName}");
            bool isFault = false;

            try
            {
                LoginError error = proxy.Login(userName, password);
                if (error == LoginError.NoError)
                {
                    StartTimer();
                    Report.log(DeviceToReport.Client_Proxy, LogLevel.Information, $"Client {userName} connected");
                }
                else
                {
                    Report.log(DeviceToReport.Client_Proxy, LogLevel.Information, $"Client {userName} was not connected");
                }

                //Check connection to server every _checkConnectionSeconds

                return(GenerateErrorString(error));
            }
            catch (EndpointNotFoundException)
            {
                isFault = true;
                string message = "Connection error - Unable to connect to server";
                Report.log(DeviceToReport.Client_Proxy, LogLevel.Exception, message);
                throw new EndpointNotFoundException(message);
            }
            catch (Exception e)
            {
                isFault = true;
                Report.log(DeviceToReport.Client_Proxy, LogLevel.Exception, e.Message);
                throw e;
            }
            finally
            {
                if (isFault)
                {
                    factory.Abort();
                    Report.log(DeviceToReport.Client_Proxy, LogLevel.Information, $"Channel closed for client {userName} after exception");
                    OpenChannel();
                    Report.log(DeviceToReport.Client_Proxy, LogLevel.Information, $"Channel opened for client {userName} after exception");
                }
            }
        }
Example #14
0
 private void Close()
 {
     m_working = false;
     try
     {
         if (null != m_clientChannel)
         {
             ((ICommunicationObject)m_clientChannel).Close();
         }
     }
     catch (CommunicationException commEx)
     {
         Error(string.Format("Communication when closing channel: {0}", commEx.Message));
         ((ICommunicationObject)m_clientChannel).Abort();
     }
     catch (Exception ex)
     {
         Error(string.Format("Exception when closing channel: {0}", ex.Message));
         ((ICommunicationObject)m_clientChannel).Abort();
     }
     finally
     {
         m_clientChannel = null;
     }
     try
     {
         if (null != m_factory)
         {
             m_factory.Close();
         }
     }
     catch (CommunicationException commEx)
     {
         Error(string.Format("Communication when closing factory: {0}", commEx.Message));
         m_factory.Abort();
     }
     catch (Exception ex)
     {
         Error(string.Format("Exception when closing factory: {0}", ex.Message));
         m_factory.Abort();
     }
     finally
     {
         m_factory = null;
     }
 }
Example #15
0
        private void _resetDuplexCommunicationChannel()
        {
            if (_duplexChannelFactory == null)
            {
                return;
            }

            _duplexChannelFactory.Abort();
            _duplexChannelFactory.Close();
        }
        virtual internal IWuRemoteService GetInstance(Binding binding, EndpointAddress remoteAddress, CallbackReceiver callback)
        {
            if (binding == null)
            {
                throw new ArgumentNullException(nameof(binding));
            }
            if (remoteAddress == null)
            {
                throw new ArgumentNullException(nameof(remoteAddress));
            }
            if (callback == null)
            {
                throw new ArgumentNullException(nameof(callback));
            }

            IWuRemoteService service;
            DuplexChannelFactory <IWuRemoteService> channelFactory = null;

            try
            {
                Log.Debug($"Creating channel for {remoteAddress.Uri}");
                channelFactory = new DuplexChannelFactory <IWuRemoteService>(callback, binding, remoteAddress);
                service        = channelFactory.CreateChannel();
                ((IChannel)service).Open();
                Log.Debug($"{remoteAddress.Uri}: Register for callbacks.");
                service.RegisterForCallback();
            }
            catch (EndpointNotFoundException e)
            {
                channelFactory?.Abort();
                Log.Warn($"Could not create channel for {remoteAddress.Uri}", e);
                throw new EndpointNotFoundException($"Could not connect to the remote host. Verify that the serivce is installed on the remote host and is not blocked by the firewall. {((e.InnerException != null) ? e.InnerException.Message : e.Message) }", e);
            }
            catch (Exception e)
            {
                Log.Warn($"Could not create channel for {remoteAddress.Uri}", e);
                channelFactory?.Abort();
                throw;
            }

            return(service);
        }
Example #17
0
        //public void AddNewSong(UserPlayer user, string fileName, string genre, string artist, string nameSong,  byte[] fileContents)
        //{
        //    try
        //    {
        //        MessageBox.Show("connector111");
        //        MessageBox.Show(user.ID_user.ToString());
        //        MessageBox.Show(fileName);
        //        MessageBox.Show(genre);
        //        MessageBox.Show(artist);
        //        MessageBox.Show(nameSong);
        //        MessageBox.Show(fileContents.Length.ToString());

        //        service.AddOneSong(user, fileName, genre, artist, nameSong, fileContents);
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //        if (ex.InnerException != null)
        //            MessageBox.Show(ex.InnerException.ToString());
        //    }
        //}

        //    public async void AdminAddSong(ParametrSong parametrSong)
        //{
        //    try
        //    {
        //        await Task.Run(() => service.UploadFileToFtp(parametrSong));
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //    }
        //}

        public void Disconnect()
        {
            try
            {
                service.Disconnect();
                Factory.Abort();
            }
            catch (Exception)
            {
                //MessageBox.Show(ex.Message);
            }
        }
Example #18
0
        /// <summary>
        /// Uninitialize the client from operation.
        /// </summary>
        /// <returns></returns>
        public bool UnInitialize()
        {
            lock (Clients)
            {
                Clients.Remove(this);
            }

            lock (this)
            {
                if (_proxyServerInterface != null)
                {
                    try
                    {
                        ((IChannel)_proxyServerInterface).Opened  -= new EventHandler(MessageContainerTransportClient_Opened);
                        ((IChannel)_proxyServerInterface).Opening -= new EventHandler(MessageContainerTransportClient_Opening);
                        ((IChannel)_proxyServerInterface).Faulted -= new EventHandler(MessageContainerTransportClient_Faulted);
                        ((IChannel)_proxyServerInterface).Closing -= new EventHandler(MessageContainerTransportClient_Closing);

                        ((IChannel)_proxyServerInterface).Abort();
                    }
                    catch (Exception ex)
                    {
                        SystemMonitor.OperationError(string.Empty, ex);
                    }
                    finally
                    {
                        _proxyServerInterface = null;
                    }
                }

                if (_channelFactory != null)
                {
                    try
                    {
                        _channelFactory.Abort();
                    }
                    catch (Exception ex)
                    {
                        SystemMonitor.OperationError(string.Empty, ex);
                    }
                    finally
                    {
                        _channelFactory = null;
                    }
                }

                _connectingEvent.Reset();
            }

            return(true);
        }
Example #19
0
 private void ExceptionFreeAction(Action action, [CallerMemberName] string actionName = null)
 {
     try
     {
         action();
         LastActionToServer = DateTime.Now;
     }
     catch (Exception ex)
     {
         Log.Default.WriteLine(LogLevels.Error, "Exception:{0} {1}", actionName, ex);
         ConnectionLost?.Invoke();
         _factory?.Abort();
     }
 }
    public static void ServiceContract_TypedProxy_DuplexCallback()
    {
        DuplexChannelFactory <IDuplexChannelService> factory = null;
        StringBuilder errorBuilder = new StringBuilder();
        Guid          guid         = Guid.NewGuid();

        try
        {
            NetTcpBinding binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.None;

            DuplexChannelServiceCallback callbackService = new DuplexChannelServiceCallback();
            InstanceContext context = new InstanceContext(callbackService);

            factory = new DuplexChannelFactory <IDuplexChannelService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_DuplexCallback_Address));
            IDuplexChannelService serviceProxy = factory.CreateChannel();

            serviceProxy.Ping(guid);
            Guid returnedGuid = callbackService.CallbackGuid;

            if (guid != returnedGuid)
            {
                errorBuilder.AppendLine(String.Format("The sent GUID does not match the returned GUID. Sent: {0} Received: {1}", guid, returnedGuid));
            }

            factory.Close();
        }
        catch (Exception ex)
        {
            errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
            for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
            {
                errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString()));
            }
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }

        if (errorBuilder.Length != 0)
        {
            Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: ServiceContract_TypedProxy_DuplexCallback FAILED with the following errors: {0}", errorBuilder));
        }
    }
 public void Close()
 {
     if (pipeFactory.State != CommunicationState.Closed &&
         pipeFactory.State != CommunicationState.Closing &&
         pipeFactory.State != CommunicationState.Faulted)
     {
         pipeProxy.Unsubscribe();
     }
     try {
         pipeFactory.Close();
     }
     catch (Exception) {
         pipeFactory.Abort();
     }
     debugOutput.Close();
 }
Example #22
0
        private void Disconnect()
        {
            if (factory != null)
            {
                try
                {
                    factory.Close(TimeSpan.FromSeconds(2.0));
                }
                catch (TimeoutException)
                {
                    factory.Abort();
                }
            }

            factory = null;
        }
        /// <summary>
        /// Disconnect from the server.
        /// </summary>
        /// <returns>The musicplayer.</returns>
        public IMusicPlayer Disconnect()
        {
            if (_factory.State == CommunicationState.Opened)
            {
                try
                {
                    _server.Goodbye();
                    _factory.Close();
                }
                catch { }
            }

            _factory.Abort();
            OnInfoChanged?.Invoke(null);
            base.Dispose();
            return(null);
        }
Example #24
0
        internal static void worker(int loop, string name, InstanceContext context)
        {
            //ThreadPool.QueueUserWorkItem(delegate
            //{
            DuplexChannelFactory <ITest> factory = null;
            ITest channel = null;

            try
            {
                factory = new DuplexChannelFactory <ITest>(context, name);

                channel = factory.CreateChannel();

                using (var scope = new OperationContextScope((IContextChannel)channel))
                {
                    OperationContext.Current.OutgoingMessageHeaders.ReplyTo = ((IClientChannel)channel).LocalAddress;

                    // action
                    channel.Ping("Hello,  " + loop.ToString());

                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine(string.Format("[{0}, {1}]: D O N E, tid={2}", loop, name, Thread.CurrentThread.GetHashCode()));
                    Console.ResetColor();

                    Console.WriteLine("\n+++ press any key to close this channel +++\n");
                    Console.ReadLine();
                }

                ((IChannel)channel).Close();
                factory.Close();
            }
            catch (Exception ex)
            {
                if (channel != null)
                {
                    ((IChannel)channel).Abort();
                }
                if (factory != null)
                {
                    factory.Abort();
                }
                Console.WriteLine(ex.Message);
            }
            //});
        }
Example #25
0
 public bool Disconnect()
 {
     if (_factory == null)
     {
         return(false); // should connect first
     }
     try
     {
         _factory.Close();
     }
     catch (Exception ex)
     {
         Log.Default.WriteLine(LogLevels.Warning, "Exception:{0}", ex);
         _factory.Abort();
     }
     _factory = null;
     return(true);
 }
Example #26
0
        private void Close()
        {
            try
            {
                if (_initializeTask != null && _initializeTask.Status != TaskStatus.RanToCompletion)
                {
                    try
                    {
                        _cancellationTokenSource.Cancel();
                        _initializeTask.Wait();
                    }
                    catch (Exception ex)
                    {
                        LogProvider.Log.Error(this, ex);
                    }
                }

                isInitialized = false;

                _initializeTask          = null;
                _cancellationTokenSource = null;

                if (_namedPipeBindingFactory != null)
                {
                    _namedPipeBindingFactory.Faulted -= Pipe_Faulted;
                    _namedPipeBindingFactory.Opened  -= Pipe_Opened;
                    _namedPipeBindingFactory.Abort();

                    _namedPipeBindingFactory = null;
                    _namedPipeBindingProxy   = null;
                    _callbackService         = null;
                }

                if (hudClient != null && !hudClient.HasExited)
                {
                    hudClient.Kill();
                }
            }
            catch (Exception e)
            {
                LogProvider.Log.Error(this, "HUD transmitter could not be stopped.", e);
            }
        }
Example #27
0
        private void OnClosed(object sender, EventArgs eventArgs)
        {
            if (_service?.State == CommunicationState.Faulted)
            {
                _service?.Abort();
            }
            else
            {
                _service?.Close();
            }

            if (_factory?.State == CommunicationState.Faulted)
            {
                _factory?.Abort();
            }
            else
            {
                _factory?.Close();
            }
        }
    public static void CreateChannel_EndpointAddress_Null_Throws()
    {
        WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
        InstanceContext context = new InstanceContext(callback);
        Binding binding = new NetTcpBinding();
        EndpointAddress remoteAddress = null;

        DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, remoteAddress);
        try {
            Assert.Throws<InvalidOperationException>(() =>
               {
                   factory.Open();
                   factory.CreateChannel();
               });
        }
        finally
        { 
            factory.Abort();
        }
    }
Example #29
0
    public static void CreateChannel_EndpointAddress_Null_Throws()
    {
        WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
        InstanceContext          context  = new InstanceContext(callback);
        Binding         binding           = new NetTcpBinding();
        EndpointAddress remoteAddress     = null;

        DuplexChannelFactory <IWcfDuplexService> factory = new DuplexChannelFactory <IWcfDuplexService>(context, binding, remoteAddress);

        try {
            Assert.Throws <InvalidOperationException>(() =>
            {
                factory.Open();
                factory.CreateChannel();
            });
        }
        finally
        {
            factory.Abort();
        }
    }
Example #30
0
        static void PushMessage()
        {
            DuplexChannelFactory <IPublisherService> duplex = new DuplexChannelFactory <IPublisherService>(instanceContext, typeof(IPublisherService).Name);

            try
            {
                IPublisherService client = duplex.CreateChannel();
                client.Subscriber(LoginInfo.Guid, LoginInfo.Code, LoginInfo.Account);
                while (_isStoped)
                {
                    System.Threading.Thread.Sleep(300000);
                    client.Subscriber(LoginInfo.Guid, LoginInfo.Code, LoginInfo.Account);
                }
            }
            catch (Exception e)
            {
                Logger.WriteLog(LogType.ERROR, "连接失败", e);
                System.Threading.Thread.Sleep(60000);
                duplex.Abort();
                PushMessage();
            }
        }
        public void Dispose()
        {
            if (mDispose)
            {
                return;
            }

            try
            {
                if (mParticipanteP2P != null)
                {
                    mParticipanteP2P.ServicioAbandonarRed(mNombreNodo);
                }

                if (mFabricaDeCanalesDuplex != null)
                {
                    mFabricaDeCanalesDuplex.Close();
                }
            }
            catch (InvalidOperationException)
            {
            }
            catch (CommunicationObjectFaultedException)
            {
                //canal de comuniación en estado Faulted
                mFabricaDeCanalesDuplex.Abort();
            }
            finally
            {
                if (mParticipanteP2P != null)
                {
                    mParticipanteP2P.Abort();
                    mParticipanteP2P.Dispose();
                }
                mParticipanteP2P = null;
                mDispose         = true;
            }
        }
 /// <summary>
 /// Отключение от сервиса
 /// </summary>
 public void Disconnect()
 {
     try
     {
         if (_service != null && _factory.State == CommunicationState.Opened)
         {
             _service.Leave();
             _service = null;
         }
     }
     catch
     {
     }
     finally
     {
         if (_factory != null && _factory.State == CommunicationState.Opened)
         {
             _factory.Abort();
             _factory.Close();
             _factory = null;
         }
     }
 }
Example #33
0
        private void ShutDown()
        {
            lock (_locker)
            {
                if (_isClosed)
                {
                    return;
                }

                _callback.OnClose();
                try
                {
                    _channelFactory.Close();
                }
                catch
                {
                    _channelFactory.Abort();
                }
                finally
                {
                    _isClosed = true;
                }
            }
        }
Example #34
0
        static void Main()
        {
            _handler += Handler;
            SetConsoleCtrlHandler(_handler, true);
            ClientProcessor = new ClientProcessor();

            var instanceContext = new InstanceContext(new BombermanCallbackService(ClientProcessor));
            Binding binding = new NetTcpBinding(SecurityMode.None);
            DuplexChannelFactory<IBombermanService> factory = new DuplexChannelFactory<IBombermanService>(instanceContext, binding, new EndpointAddress(
                new Uri(string.Concat("net.tcp://", ConfigurationManager.AppSettings["MachineName"], ":7900/BombermanCallbackService"))));
            Proxy = factory.CreateChannel();

            Console.WriteLine("--------------------------------------");
            Console.WriteLine("-------- Welcome to Bomberman --------");
            Console.WriteLine("--------------------------------------\n\n");

            do
            {
                Console.WriteLine("Type your player name :\n");
                Username = Console.ReadLine();
                ConnectUser(Username);
                ClientProcessor.Username = Username;
            } while (ErrorConnection);

            Log.Initialize(@"D:\Temp\BombermanLogs", "Client_" + Username + ".log");
            Log.WriteLine(Log.LogLevels.Info, "Logged at " + DateTime.Now.ToShortTimeString());

            bool stop = false;
            while (!stop)
            {
                ConsoleKeyInfo keyboard = Console.ReadKey();
                switch (keyboard.Key)
                {
                    //s
                    case ConsoleKey.S:
                        StartGame();
                        break;
                    case ConsoleKey.UpArrow:
                        MoveTo(ActionType.MoveUp);
                        break;
                    case ConsoleKey.LeftArrow:
                        MoveTo(ActionType.MoveLeft);
                        break;
                    case ConsoleKey.RightArrow:
                        MoveTo(ActionType.MoveRight);
                        break;
                    case ConsoleKey.DownArrow:
                        MoveTo(ActionType.MoveDown);
                        break;
                    case ConsoleKey.X: // SinaC: never leave a while(true) without an exit condition
                        stop = true;
                        break;
                }
            }

            // SinaC: Clean properly factory
            try
            {
                factory.Close();
            }
            catch (Exception ex)
            {
                Log.WriteLine(Log.LogLevels.Warning, "Exception:{0}", ex);
                factory.Abort();
            }
        }
Example #35
0
        internal static void worker(int loop, string name, InstanceContext context)
        {
            //ThreadPool.QueueUserWorkItem(delegate
            //{
                DuplexChannelFactory<ITest> factory = null;
                ITest channel = null;
                try
                {
                    factory = new DuplexChannelFactory<ITest>(context, name);

                    channel = factory.CreateChannel();

                    using (var scope = new OperationContextScope((IContextChannel)channel))
                    {
                        OperationContext.Current.OutgoingMessageHeaders.ReplyTo = ((IClientChannel)channel).LocalAddress;
                        
                        // action
                        channel.Ping("Hello,  " + loop.ToString());

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine(string.Format("[{0}, {1}]: D O N E, tid={2}", loop, name, Thread.CurrentThread.GetHashCode()));
                        Console.ResetColor();

                        Console.WriteLine("\n+++ press any key to close this channel +++\n");
                        Console.ReadLine();
                    }

                    ((IChannel)channel).Close();
                    factory.Close();
                }
                catch (Exception ex)
                {
                    if (channel != null) ((IChannel)channel).Abort();
                    if (factory != null) factory.Abort();
                    Console.WriteLine(ex.Message);
                }
            //});
        }
Example #36
0
    public static void ServiceContract_TypedProxy_DuplexCallback()
    {
        DuplexChannelFactory<IDuplexChannelService> factory = null;
        StringBuilder errorBuilder = new StringBuilder();
        Guid guid = Guid.NewGuid();

        try
        {
            NetTcpBinding binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.None;

            DuplexChannelServiceCallback callbackService = new DuplexChannelServiceCallback();
            InstanceContext context = new InstanceContext(callbackService);

            factory = new DuplexChannelFactory<IDuplexChannelService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_DuplexCallback_Address));
            IDuplexChannelService serviceProxy = factory.CreateChannel();

            serviceProxy.Ping(guid);
            Guid returnedGuid = callbackService.CallbackGuid;

            if (guid != returnedGuid)
            {
                errorBuilder.AppendLine(String.Format("The sent GUID does not match the returned GUID. Sent: {0} Received: {1}", guid, returnedGuid));
            }

            factory.Close();
        }
        catch (Exception ex)
        {
            errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
            for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
            {
                errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString()));
            }
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }

        if (errorBuilder.Length != 0)
        {
            Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: ServiceContract_TypedProxy_DuplexCallback FAILED with the following errors: {0}", errorBuilder));
        }
    }