Example #1
0
        //[STAThread]
        static public void MainThreadStart()
        {
            Console.WriteLine("-----------------------------------");
            Console.WriteLine("SharpLibDisplay console server.");
            Console.WriteLine("Commands:");
            Console.WriteLine("   q: close server");
            Console.WriteLine("-----------------------------------");


            StartServer("net.tcp://localhost:8111/");

            CommunicationState state = iServiceHost.State;

            Console.WriteLine("State: " + state.ToString());

            while (Console.ReadLine() != "q")
            {
                if (state != iServiceHost.State)
                {
                    //State has changed
                    state = iServiceHost.State;
                    Console.WriteLine("State: " + state.ToString());
                }
            }

            StopServer();
        }
Example #2
0
        private void ThrowIfDisposedOrImmutable()
        {
            IChannel channel = this.Channel;

            if (channel != null)
            {
                CommunicationState state = channel.State;
                string             text  = null;

                switch (state)
                {
                case CommunicationState.Created:
                    break;

                case CommunicationState.Opening:
                case CommunicationState.Opened:
                case CommunicationState.Closing:
                case CommunicationState.Closed:
                case CommunicationState.Faulted:
                    text = SR.Format(SR.ChannelParametersCannotBeModified,
                                     channel.GetType().ToString(), state.ToString());
                    break;

                default:
                    text = SR.Format(SR.CommunicationObjectInInvalidState,
                                     channel.GetType().ToString(), state.ToString());
                    break;
                }

                if (text != null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(text));
                }
            }
        }
        public async Task Close()
        {
            await _lock.WaitAsync();

            try
            {
                if (this.State < CommunicationState.Opened)
                {
                    throw new Exception($"Can not close channel when its state is {State.ToString()}");
                }
                this.State = CommunicationState.Closing;

                await this.OnClose();

                if (this.State != CommunicationState.Closing)
                {
                    throw new Exception($"Can not close channel when its state is {State.ToString()}");
                }
                this.State = CommunicationState.Closed;
            }
            catch
            {
                this.State = CommunicationState.Faulted;
                throw;
            }
            finally
            {
                _lock.Release();
            }
        }
Example #4
0
        static void Main(string[] args)
        {
            Console.WriteLine("-----------------------------------");
            Console.WriteLine("SharpLibDisplay console client.");
            Console.WriteLine("Commands:");
            Console.WriteLine("   q: quit");
            Console.WriteLine("   c: close client");
            Console.WriteLine("   o: open client");
            Console.WriteLine("   l: set layout");
            Console.WriteLine("   stf: set text field");
            Console.WriteLine("   sbf: set bitmap field");
            Console.WriteLine("   srf: set recording field");
            Console.WriteLine("   savf: set audio visualizer field");
            Console.WriteLine("   scf: set client field");
            Console.WriteLine("   t: trigger event by name");
            Console.WriteLine("-----------------------------------");

            //Create our client and connect to our server
            iClient = new Client();
            iClient.CloseOrderEvent += OnCloseOrder;

            OpenClient();

            CommunicationState state = iClient.SessionState;

            Console.WriteLine("State: " + state.ToString());

            bool quit = false;

            while (!quit)
            {
                string command = Console.ReadLine();
                quit = DispatchCommand(command);

                //Output our state if it was changed
                if (state != iClient.SessionState)
                {
                    //State has changed
                    state = iClient.SessionState;
                    Console.WriteLine("State: " + state.ToString());
                }
            }

            iClient.Close();
        }
Example #5
0
 private void NotifyStateChanged(CommunicationState newState)
 {
     lock (this.stateChangeLock)
     {
         this.stateChanged = true;
         this.stateCache   = newState.ToString();
         Debug.WriteLine($"[{nameof(ServiceClient)}] .{nameof(this.NotifyStateChanged)} state changed to {newState.ToString()}");
     }
 }
        private void ChangeCommunicationState(CommunicationState communicationState)
        {
            this.CommunicationState = communicationState;
            if (this.CommunicationStateChanged != null)
            {
                this.CommunicationStateChanged(this, new CommunicationStateChangedEventArgs((CommunicationStatus)communicationState));
            }

            _Log.Info("Communication state changed to " + communicationState.ToString());
            if (communicationState == CommunicationState.Opened)
            {
                Resubscribe();
                _PingTimer = new Timer(new TimerCallback(Ping), null, this._MessageClientConfigurationSection.PingInterval, this._MessageClientConfigurationSection.PingInterval);
            }
        }
        private void ThrowIfMutable()
        {
            IChannel channel = this.Channel;

            if (channel != null)
            {
                CommunicationState state   = channel.State;
                string             message = null;
                switch (state)
                {
                case CommunicationState.Created:
                    message = System.ServiceModel.SR.GetString("ChannelParametersCannotBePropagated", new object[] { channel.GetType().ToString(), state.ToString() });
                    break;

                case CommunicationState.Opening:
                case CommunicationState.Opened:
                case CommunicationState.Closing:
                case CommunicationState.Closed:
                case CommunicationState.Faulted:
                    break;

                default:
                    message = System.ServiceModel.SR.GetString("CommunicationObjectInInvalidState", new object[] { channel.GetType().ToString(), state.ToString() });
                    break;
                }
                if (message != null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(message));
                }
            }
        }
Example #8
0
        public async Task Close()
        {
            lock (this)
            {
                if (this.State < CommunicationState.Opened)
                {
                    throw new Exception($"Can not close channel when its state is {State.ToString()}");
                }
                this.State = CommunicationState.Closing;
            }
            try
            {
                await this.OnClose();

                lock (this)
                {
                    if (this.State != CommunicationState.Closing)
                    {
                        throw new Exception($"Can not close channel when its state is {State.ToString()}");
                    }
                    this.State = CommunicationState.Closed;
                }
            }
            catch (Exception)
            {
                lock (this)
                {
                    this.State = CommunicationState.Faulted;
                    throw;
                }
            }
        }
Example #9
0
        /// <summary>
        /// Finds any HW device
        /// </summary>
        /// <returns>Result.eERR_SUCCESS if successfull</returns>
        public Result FindHW()
        {
            Result result = Result.eERR_INITIAL_STATE;

            if (CommState == CommunicationState.Ready)
            {
                STBLogger.AddEvent(ToString(), STBLogger.EventLevel.Information, "Find HW: The comm driver was already initialized.", "Comm Drv CommunicationState:" + CommState.ToString() + " Extended Find HW");
                result = Result.eERR_NOT_READY;
            }
            else if (CommState == CommunicationState.Idle)
            {
                result = Result.eERR_SUCCESS;

                lock (objectLock)
                    CommState = CommunicationState.HWFind;

                IsExtendedFindHW = true;
                SetCommStatus("");
            }
            return(result);
        }
Example #10
0
        /// <summary>
        /// Connects to Solace. Ignores call if already connected.
        /// </summary>
        /// <param name="config">The configuration to establish a Solace connection</param>
        public void Connect()
        {
            if (_state == CommunicationState.Opened || _state == CommunicationState.Opening)
            {
                log.Debug("Ignoring call - the Solace transport channel is in state: " + _state.ToString());
                return;
            }

            // Indicate we are opening
            this._state = CommunicationState.Opening;
            log.Debug("Connecting to Solace");

            try
            {
                // Context & Session Properties
                var contextProps = new ContextProperties();
                SessionProperties sessionProps = new SessionProperties();
                sessionProps.Host                        = this._config.SessionHost;
                sessionProps.VPNName                     = this._config.SessionVpnName;
                sessionProps.UserName                    = this._config.SessionUsername;
                sessionProps.Password                    = this._config.SessionPassword;
                sessionProps.ClientName                  = this._config.SessionClientName;
                sessionProps.ClientDescription           = this._config.SessionClientDescription;
                sessionProps.ConnectRetries              = this._config.SessionConnectRetries;
                sessionProps.ConnectTimeoutInMsecs       = this._config.SessionConnectTimeoutInMsecs;
                sessionProps.ReconnectRetries            = this._config.SessionReconnectRetries;
                sessionProps.ReconnectRetriesWaitInMsecs = this._config.SessionReconnectRetriesWaitInterval;
                sessionProps.ReapplySubscriptions        = true;

                // Context
                _context = ContextFactory.Instance.CreateContext(contextProps, null);

                // Session
                _session = _context.CreateSession(sessionProps, HandleMessageEvent, HandleSessionEvent);

                // Connect
                ReturnCode rc = _session.Connect();

                if (rc != ReturnCode.SOLCLIENT_OK)
                {
                    // throw exception to caller
                    throw new Exception("Unable to connect Solace session. Solace ReturnCode: " + rc.ToString());
                }

                // Update state
                this._state = CommunicationState.Opened;
                log.InfoFormat("Service is connected to Solace on: {0}", this._config.SessionHost);
            }
            catch (OperationErrorException ex)
            {
                throw new Exception("Unable to connect Solace session. See inner exception for details.", ex);
            }
        }
Example #11
0
        protected void ThrowIfCreated()
        {
            CommunicationState state = base.CommunicationObject.State;

            if (state == CommunicationState.Created)
            {
                Exception exception = new InvalidOperationException(System.ServiceModel.SR.GetString("CommunicationObjectCannotBeUsed", new object[] { base.GetType().ToString(), state.ToString() }));
                throw TraceUtility.ThrowHelperError(exception, Guid.Empty, this);
            }
        }
Example #12
0
 private Exception CreateNotOpenException()
 {
     return(new InvalidOperationException(SR.Format(SR.CommunicationObjectCannotBeUsed, this.GetCommunicationObjectType().ToString(), _state.ToString())));
 }
Example #13
0
        public void Disconnect()
        {
            lock (m_LockObject)
            {
                if (CommunicationState == CommunicationStatus.NotCommunicating ||
                    CommunicationState == CommunicationStatus.Disconnecting)
                {
                    return;
                }
                Log.TaskBegin(Id, "Called by " + CallerMethodName + ", CommunicationState = " + CommunicationState.ToString());
                CommunicationState = CommunicationStatus.Disconnecting;
            }

            try
            {
                try
                {
                    try
                    {
                        // Disconnect
                        System.Threading.Thread.Sleep(3000);
                    }
                    catch (Exception ex)
                    {
                        AuditMessage(AuditLevel.Error, "Disconnect error: " + ex.Message);
                    }

                    try
                    {
                        Util.RaiseEvent(Id, "Disconnected", OnDisconnected, this, EventArgs.Empty);
                    }
                    catch (Exception ex)
                    {
                        AuditMessage(AuditLevel.Error, "Disconnect event raise error: " + ex.Message);
                    }
                }
                finally
                {
                    Log.WriteLine(Id, "DDK.Disconnect is called");
                    m_DDK.Disconnect();  // Sets the standard driver property Connected = False and calls AuditMessage(AuditLevel.Abort)
                }
                Log.TaskEnd(Id);
            }
            finally
            {
                lock (m_LockObject)
                {
                    CommunicationState = CommunicationStatus.NotCommunicating;
                }
                Log.TaskEnd(Id);
            }
        }
 private static void EndPing(IAsyncResult result)
 {
     DuplexRequestBindingElement.DuplexRequestSessionChannel asyncState = (DuplexRequestBindingElement.DuplexRequestSessionChannel)result.AsyncState;
     try
     {
         asyncState.innerChannel.EndSend(result);
         lock (asyncState.pingTimer)
         {
             CommunicationState state = asyncState.State;
             if (state == CommunicationState.Opened && asyncState.inflightRequests.Count > 0)
             {
                 asyncState.pingTimer.Set(SbmpConstants.ConnectionPingTimeout);
             }
             else if (state != CommunicationState.Opened)
             {
                 MessagingClientEtwProvider.TraceClient(() => MessagingClientEtwProvider.Provider.EventWriteRuntimeChannelStopPingWithIncorrectState(asyncState.innerChannel.GetType().Name, asyncState.innerChannel.LocalAddress.Uri.AbsoluteUri, (asyncState.innerChannel.RemoteAddress == null ? "Null" : asyncState.innerChannel.RemoteAddress.Uri.AbsoluteUri), (asyncState.innerChannel.Via == null ? "Null" : asyncState.innerChannel.Via.AbsoluteUri), asyncState.innerChannel.Session.Id, state.ToString(), asyncState.inflightRequests.Count));
             }
         }
     }
     catch (Exception exception1)
     {
         Exception exception = exception1;
         if (Fx.IsFatal(exception))
         {
             throw;
         }
         MessagingClientEtwProvider.TraceClient(() => MessagingClientEtwProvider.Provider.EventWriteRuntimeChannelPingFailed(asyncState.innerChannel.GetType().Name, asyncState.innerChannel.LocalAddress.Uri.AbsoluteUri, (asyncState.innerChannel.RemoteAddress == null ? "Null" : asyncState.innerChannel.RemoteAddress.Uri.AbsoluteUri), (asyncState.innerChannel.Via == null ? "Null" : asyncState.innerChannel.Via.AbsoluteUri), asyncState.innerChannel.Session.Id, exception.ToString()));
     }
 }
            private static void BeginPing(object state)
            {
                DuplexRequestBindingElement.DuplexRequestSessionChannel duplexRequestSessionChannel = (DuplexRequestBindingElement.DuplexRequestSessionChannel)state;
                CommunicationState communicationState = duplexRequestSessionChannel.State;

                if (communicationState != CommunicationState.Opened)
                {
                    MessagingClientEtwProvider.TraceClient(() => MessagingClientEtwProvider.Provider.EventWriteRuntimeChannelPingIncorrectState(duplexRequestSessionChannel.innerChannel.GetType().Name, duplexRequestSessionChannel.innerChannel.LocalAddress.Uri.AbsoluteUri, (duplexRequestSessionChannel.innerChannel.RemoteAddress == null ? "Null" : duplexRequestSessionChannel.innerChannel.RemoteAddress.Uri.AbsoluteUri), (duplexRequestSessionChannel.innerChannel.Via == null ? "Null" : duplexRequestSessionChannel.innerChannel.Via.AbsoluteUri), duplexRequestSessionChannel.innerChannel.Session.Id, communicationState.ToString()));
                    return;
                }
                Message message = Message.CreateMessage(duplexRequestSessionChannel.messageVersion, "http://schemas.microsoft.com/servicebus/2010/08/protocol/Ping", new Microsoft.ServiceBus.Messaging.Channels.PingMessage());

                try
                {
                    duplexRequestSessionChannel.innerChannel.BeginSend(message, SbmpConstants.ConnectionPingOperationTimeout, DuplexRequestBindingElement.DuplexRequestSessionChannel.endPing, duplexRequestSessionChannel);
                }
                catch (Exception exception1)
                {
                    Exception exception = exception1;
                    if (Fx.IsFatal(exception))
                    {
                        throw;
                    }
                    MessagingClientEtwProvider.TraceClient(() => MessagingClientEtwProvider.Provider.EventWriteRuntimeChannelPingFailed(duplexRequestSessionChannel.innerChannel.GetType().Name, duplexRequestSessionChannel.innerChannel.LocalAddress.Uri.AbsoluteUri, (duplexRequestSessionChannel.innerChannel.RemoteAddress == null ? "Null" : duplexRequestSessionChannel.innerChannel.RemoteAddress.Uri.AbsoluteUri), (duplexRequestSessionChannel.innerChannel.Via == null ? "Null" : duplexRequestSessionChannel.innerChannel.Via.AbsoluteUri), duplexRequestSessionChannel.innerChannel.Session.Id, exception.ToString()));
                }
            }
        protected void ThrowIfCreated()
        {
            CommunicationState state = CommunicationObject.State;

            if (state == CommunicationState.Created)
            {
                Exception e = new InvalidOperationException(SR.Format(SR.CommunicationObjectCannotBeUsed, GetType().ToString(), state.ToString()));
                throw TraceUtility.ThrowHelperError(e, Guid.Empty, this);
            }
        }