Ejemplo n.º 1
0
        private void OnStateChanged(object sender, AudioSessionStateChangedEventArgs e)
        {
            if (e.NewState != AudioSessionState.AudioSessionStateExpired)
            {
                return;
            }

            SessionEnded?.Invoke(this);
        }
Ejemplo n.º 2
0
        void IAudioSessionEventsHandler.OnStateChanged(AudioSessionState state)
        {
            if (state != AudioSessionState.AudioSessionStateExpired)
            {
                return;
            }

            SessionEnded?.Invoke(this);
        }
Ejemplo n.º 3
0
        public void UpdateSessionBasics(SessionType type, SessionPhase phase)
        {
            if (phase == SessionPhase.None)
            {
                return;
            }

            if (_session == null)
            {
                _session = CreateSession(type);
                Logger.Log($"{type} session started - new weekend");
                SessionStarted?.Invoke(this, EventArgs.Empty);
            }
            else if (type != _session.Type)
            {
                if (IsInProgress(_session.Phase))
                {
                    EndTimedPhase();
                }

                Logger.Log($"{_session.Type} session ended");
                SessionEnded?.Invoke(this, EventArgs.Empty);

                var isPartOfWeekend = type > _session.Type;

                _session = isPartOfWeekend
          ? CreateSession(type, _session.WeekendId)
          : CreateSession(type);

                var message = isPartOfWeekend
          ? $"{type} session started - part of existing weekend"
          : $"{type} session started - new weekend";

                Logger.Log(message, Severity.Verbose);
                SessionStarted?.Invoke(this, EventArgs.Empty);
            }

            // We capture this so we the nested methods can use the up-to-date session
            var oldPhase = _session.Phase;

            _session.UpdateSessionInfo(type, phase);

            // If we are in the same session, check if we are advancing through the timed phases
            if (type == _session.Type)
            {
                if (IsStarting(oldPhase) && IsInProgress(_session.Phase))
                {
                    StartTimedPhase();
                }

                if (IsInProgress(oldPhase) && IsEnding(_session.Phase))
                {
                    EndTimedPhase();
                }
            }
        }
Ejemplo n.º 4
0
        private void TriggerEvents(bool recursive)
        {
            int originalCount = eventQueue.Count;

            // Do not use foreach as eventQueue might change
            for (int i = 0; i < (recursive ? eventQueue.Count : originalCount); i++)
            {
                // Performance is not a problem since events are rare!
                var arg = eventQueue[i];
                if (arg is GamerJoinedEventArgs)
                {
                    if (GamerJoined != null)
                    {
                        GamerJoined.Invoke(this, arg as GamerJoinedEventArgs);
                    }
                }
                else if (arg is GamerLeftEventArgs)
                {
                    if (GamerLeft != null)
                    {
                        GamerLeft.Invoke(this, arg as GamerLeftEventArgs);
                    }
                }
                else if (arg is GameStartedEventArgs)
                {
                    if (GameStarted != null)
                    {
                        GameStarted.Invoke(this, arg as GameStartedEventArgs);
                    }
                }
                else if (arg is GameEndedEventArgs)
                {
                    if (GameEnded != null)
                    {
                        GameEnded.Invoke(this, arg as GameEndedEventArgs);
                    }
                }
                else if (arg is NetworkSessionEndedEventArgs)
                {
                    if (SessionEnded != null)
                    {
                        SessionEnded.Invoke(this, arg as NetworkSessionEndedEventArgs);
                    }
                }
            }

            if (recursive)
            {
                eventQueue.Clear();
            }
            else
            {
                eventQueue.RemoveRange(0, originalCount);
            }
        }
Ejemplo n.º 5
0
        private void OnSessionEnded(IAudioSession session)
        {
            if (!_sessions.Remove(session.ID))
            {
                return;
            }

            session.SessionEnded  -= OnSessionEnded;
            session.VolumeChanged -= OnSessionVolumeChanged;
            session.Dispose();

            SessionEnded?.Invoke(session);
        }
Ejemplo n.º 6
0
        public SessionManager(Option <ICluster> cluster, SystemName system, ProcessName nodeName, VectorConflictStrategy strategy)
        {
            this.cluster  = cluster;
            this.system   = system;
            this.nodeName = nodeName;

            Sync = new SessionSync(system, nodeName, strategy);

            cluster.Iter(c =>
            {
                notify = c.SubscribeToChannel <SessionAction>(SessionsNotify).Subscribe(act => Sync.Incoming(act));

                var now = DateTime.UtcNow;

                // Look for stranded sessions that haven't been removed properly.  This is done once only
                // on startup because the systems should be shutting down sessions on their own.  This just
                // catches the situation where an app-domain died without shutting down properly.
                c.GetAllHashFieldsInBatch(c.QuerySessionKeys().ToSeq())
                .Map(sessions =>
                     sessions.Filter(vals => (from ts in vals.Find(LastAccessKey).Map(v => new DateTime((long)v))
                                              from to in vals.Find(TimeoutKey).Map(v => (long)v)
                                              where ts < now.AddSeconds(-to * 2)
                                              select true).IfNone(false))
                     .Keys)
                .Map(Seq)
                .Do(strandedSessions => SupplementarySessionManager.removeSessionIdFromSuppMap(c, strandedSessions.Map(ReverseSessionKey)))
                .Do(strandedSessions => c.DeleteMany(strandedSessions))
                .Map(strandedSessions => strandedSessions.Iter(sessionId => c.PublishToChannel(SessionsNotify, SessionAction.Stop(sessionId, system, nodeName))));;



                // Remove session keys when an in-memory session ends
                ended = SessionEnded.Subscribe(sid => Stop(sid));

                touch = Sync.Touched.Subscribe(tup =>
                {
                    try
                    {
                        //check if the session has not been stopped in the meantime or expired
                        if (c.HashFieldAddOrUpdateIfKeyExists(SessionKey(tup.Item1), LastAccessKey, DateTime.UtcNow.Ticks))
                        {
                            c.PublishToChannel(SessionsNotify, SessionAction.Touch(tup.Item1, system, nodeName));
                        }
                    }
                    catch (Exception e)
                    {
                        logErr(e);
                    }
                });
            });
        }
Ejemplo n.º 7
0
        public void Remove(IGameSession session)
        {
            if (session == null)
            {
                return;
            }

            lock (sessionMutex)
            {
                if (sessions.Remove(session))
                {
                    if (SessionEnded != null)
                    {
                        SessionEnded.Invoke(this, session);
                    }
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        ///     Ends the specified <see cref="Session"/>.
        /// </summary>
        /// <param name="session">The Session to end.</param>
        /// <returns>A Result containing the result of the operation.</returns>
        public IResult EndSession(ISession session)
        {
            logger.EnterMethod();
            logger.Debug($"Ending Session '{session?.Token}'...");

            IResult  retVal       = new Result();
            ISession foundSession = default(Session);

            if (State != State.Running)
            {
                retVal.AddError($"The Manager is not in a state in which it can service requests (Currently {State}).");
            }
            else
            {
                foundSession = FindSession(session?.Token);

                if (foundSession != default(Session))
                {
                    sessionLock.EnterWriteLock();

                    try
                    {
                        SessionList.Remove(foundSession);
                    }
                    finally
                    {
                        sessionLock.ExitWriteLock();
                    }
                }
                else
                {
                    retVal.AddError($"The Session matching Token '{session?.Token}' does not exist.");
                }
            }

            if (retVal.ResultCode != ResultCode.Failure)
            {
                Task.Run(() => SessionEnded?.Invoke(this, new SessionEventArgs(foundSession)));
            }

            retVal.LogResult(logger.Debug);
            logger.ExitMethod();
            return(retVal);
        }
Ejemplo n.º 9
0
        public SessionManager(Option <ICluster> cluster, SystemName system, ProcessName nodeName, VectorConflictStrategy strategy)
        {
            this.cluster  = cluster;
            this.system   = system;
            this.nodeName = nodeName;

            Sync = new SessionSync(system, nodeName, strategy);

            cluster.Iter(c =>
            {
                notify = c.SubscribeToChannel <SessionAction>(SessionsNotify).Subscribe(act => Sync.Incoming(act));

                var now = DateTime.UtcNow;

                // Look for stranded sessions that haven't been removed properly.  This is done once only
                // on startup because the systems should be shutting down sessions on their own.  This just
                // catches the situation where an app-domain died without shutting down properly.
                c.QuerySessionKeys()
                .Map(key =>
                     from ts in c.GetHashField <long>(key, LastAccessKey)
                     from to in c.GetHashField <int>(key, TimeoutKey)
                     where new DateTime(ts) < now.AddSeconds(-to * 2) // Multiply by 2, just to catch genuine non-active sessions
                     select c.Delete(key))
                .Iter(id => { });

                // Remove session keys when an in-memory session ends
                ended = SessionEnded.Subscribe(sid => Stop(sid));

                touch = Sync.Touched.Subscribe(tup =>
                {
                    try
                    {
                        c.HashFieldAddOrUpdate(SessionKey(tup.Item1), LastAccessKey, DateTime.UtcNow.Ticks);
                        c.PublishToChannel(SessionsNotify, SessionAction.Touch(tup.Item1, system, nodeName));
                    }
                    catch (Exception e)
                    {
                        logErr(e);
                    }
                });
            });
        }
        /// <summary>
        /// handles a sessioninfo packet
        /// </summary>
        private void handlesessioninfo()
        {
            headers.infotype infotype = headers.infotypes[sendrecv.readfromstream(_Reader, 1)[0]]; //first get the infotype of the sessioninfopacket

            //handle the packet depending on the type of the packet
            switch (infotype)
            {
            case headers.infotype.CurrentSessionInfo:
                Int32  idlength = BitConverter.ToInt32(sendrecv.readfromstream(_Reader, 4), 0);
                string id       = Encoding.UTF8.GetString(sendrecv.readfromstream(_Reader, idlength));
                byte   role     = sendrecv.readfromstream(_Reader, 1)[0];
                this.Role = role == 0 ? delegates.Roles.Moderator : delegates.Roles.Viewer;
                SessionInfoAvailable.Invoke(id, role == 0 ? delegates.Roles.Moderator : delegates.Roles.Viewer);
                break;

            case headers.infotype.EndSession:
                stopAsyncRead();
                SessionEnded.Invoke();
                break;

            case headers.infotype.ViewerJoined:
                ViewerJoinedSession.Invoke();
                break;

            case headers.infotype.QuitSession:
                ViewerQuitSession.Invoke();
                break;

            case headers.infotype.RequestModerator:
                ModeratorRequest.Invoke();
                break;

            case headers.infotype.RequestDenied:
                RequestAnswerAvailable.Invoke(false);
                break;

            case headers.infotype.RequestAccepted:
                RequestAnswerAvailable.Invoke(true);
                break;
            }
        }
Ejemplo n.º 11
0
        public async Task CloseSessionAsync(bool expected)
        {
            try
            {
                if (Connected && State.Controlling)
                {
                    var maxdl = Task.Delay(TLCFIDataProvider.Default.Settings.MaxReleaseControlDuration,
                                           _sessionCancellationToken);
                    var relct = Task.Run(async() =>
                    {
                        while (State.Controlling)
                        {
                            await Task.Delay(100, _sessionCancellationToken);
                        }
                    }, _sessionCancellationToken);
                    await Task.WhenAny(maxdl, relct);
                }
                StopAliveTimers();
                if (Connected && State.Registered)
                {
                    try
                    {
                        await TLCProxy.DeregisterAsync(new DeregistrationRequest(),
                                                       _sessionCancellationToken);

                        _logger.Info("Deregistered succesfully from TLC.");
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e, "Error while deregistering: ");
                    }
                }
                SessionEnded?.Invoke(this, expected);
            }
            catch (TaskCanceledException)
            {
            }
        }
Ejemplo n.º 12
0
 protected void OnSessionEnded(EventArgs e) => SessionEnded?.Invoke(this, e);
 internal void OnSessionEnded() => SessionEnded?.Invoke(this, null);
 protected virtual void OnSessionEnded()
 {
     SessionEnded?.Invoke(this, null);
 }
Ejemplo n.º 15
0
 void DebugEngine_SessionEnded(object sender, EventArgs args)
 {
     ((IGgpDebugEngine)sender).SessionEnded -= DebugEngine_SessionEnded;
     SessionEnded?.Invoke(this, args);
 }
        private void TerminateMeterSession()
        {
            IList <IService> services = ansiProtocolSession.Services;

            try
            {
#if DEBUG
                ansiProtocolSession.RawDataSent     -= Session_RawDataSent;
                ansiProtocolSession.RawDataReceived -= Session_RawDataReceived;
#endif

                ansiProtocolSession.SessionStarting   -= Session_Starting;
                ansiProtocolSession.SessionStartError -= Session_StartError;
                ansiProtocolSession.SessionStarted    -= Session_Started;
                ansiProtocolSession.SessionTimeout    -= Session_Timeout;

                ansiProtocolSession.HandshakeInitializing -= Session_HandshakeInitializing;
                ansiProtocolSession.HandshakeInitialized  -= Session_HandshakeInitialized;
                ansiProtocolSession.HandshakeError        -= Session_HandshakeError;
                ansiProtocolSession.HandshakeCompleted    -= Session_HandshakeCompleted;

                ansiProtocolSession.ServiceExecutionStarted   -= Session_ServiceExecutionStarted;
                ansiProtocolSession.ServiceExecutionCompleted -= Session_ServiceExecutionCompleted;
                ansiProtocolSession.ServiceExecutionError     -= Session_ServiceExecutionError;
                ansiProtocolSession.ServiceExecutionCanceled  -= Session_ServiceExecutionCanceled;

                ansiProtocolSession.ServicesExecutionCompleted -= Session_ServicesExecutionCompleted;

                ansiProtocolSession.SessionClosing -= Session_Closing;
                ansiProtocolSession.SessionClosed  -= Session_Closed;

                ansiProtocolSession.Dispose();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Dispose Session Error. {ex.Message}");
            }
            finally
            {
                ansiProtocolSession = null;
            }

            reconnectionAttempts++;

            var taskCompletedCount = CurrentMeterSession.SessionTasks.Values.Count(x => x.Completed);

            if ((taskCompletedCount > 0) ||
                (CurrentMeterSession.SessionSetting.ReconnectionSchema == null) ||
                (reconnectionAttempts > CurrentMeterSession.SessionSetting.ReconnectionSchema.MaxReconnectionAttempts))
            {
                reconnectionCountdownTimer?.Dispose();

                CurrentMeterSession.EndDate      = DateTime.UtcNow;
                CurrentMeterSession.SessionTrace = sessionTracer.ToString();


                int dataSetExecutionPercent = taskCompletedCount * 100 / CurrentMeterSession.SessionTasks.Count;
                var dataSetExecutionQuality = (dataSetExecutionPercent == 0) ? DataSetExecutionQuality.Critical
                                                                                                : (dataSetExecutionPercent <= 25) ? DataSetExecutionQuality.VeryPoor
                                                                                                : (dataSetExecutionPercent <= 50) ? DataSetExecutionQuality.Poor
                                                                                                : (dataSetExecutionPercent <= 75) ? DataSetExecutionQuality.Moderate
                                                                                                : (dataSetExecutionPercent < 100) ? DataSetExecutionQuality.Good
                                                                                                : DataSetExecutionQuality.Great;
                var sessionEndedEventArgs = new SessionEndedEventArgs()
                {
                    MeterSession            = CurrentMeterSession,
                    TotalBytesSent          = totalBytesSent,
                    TotalBytesReceived      = totalBytesReceived,
                    DataSetExecutionSuccess = taskCompletedCount == CurrentMeterSession.SessionTasks.Count,
                    DataSetExecutionPercent = dataSetExecutionPercent,
                    DataSetExecutionQuality = dataSetExecutionQuality
                };

                SessionEnded?.Invoke(this, sessionEndedEventArgs);

                reconnectionAttempts = 0;
                sessionTracer.Clear();
                totalBytesSent = 0; totalBytesReceived = 0;
            }
            else
            {
                currentReconnectionCountdown = CurrentMeterSession.SessionSetting.ReconnectionSchema.ReconnectionSchedules[reconnectionAttempts - 1].Schedule;
                reconnectionCountdownTimer.Change(1000, 1000); // disparamos cada 1 segundos hasta que se waitTimeSpan llegue a cero.
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Starts Processing Commands
        /// </summary>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>A Task which performs the operation</returns>
        public async override Task StartAsync(CancellationToken cancellationToken)
        {
            // Validate Port before starting
            if (Port == 0)
            {
                throw new Exception("Invalid port number");
            }

            // Initializes Server
            try
            {
                Server = new TcpListener(IPAddress.Any, Port);
                Server.Start(10);

                // Notify the listening started
                ListeningStarted?.Invoke(this, new ListeningStartedEventArgs(Port));

                while (cancellationToken.IsCancellationRequested == false)
                {
                    // Keep listening for incoming connections
                    var client = await Server.AcceptTcpClientAsync().WithCancellation(cancellationToken).ConfigureAwait(false);

                    cancellationToken.ThrowIfCancellationRequested();

                    // Creates the Communication Session
                    var sessionID = this.BeginSession();

                    // Notify that a session is started
                    var sessionStartedEventArgs = new SessionStartedEventArgs(sessionID);
                    SessionStarted?.Invoke(this, sessionStartedEventArgs);

                    // Make sure session is not denied
                    if (sessionStartedEventArgs.Deny)
                    {
                        // Session is denied, unregister it
                        this.EndSession(sessionID);
                    }
                    else
                    {
                        // Session is allowed, continue with it
                        var networkCommunicationSession = new NetworkCommunicationSession(client, sessionID, ShowTimer, ShowPrompt);
                        networkCommunicationSession.RawCommandReceived += (sender, commandEventArgs) =>
                        {
                            // Executes the command and waits for the answer
                            var taskResponse = Task.Run <CommandExecutionResponse>(async() => await ExecuteCommandAsync(networkCommunicationSession.ID, commandEventArgs.RawCommand));
                            var response     = taskResponse.Result;

                            // Outputs the response
                            commandEventArgs.Response = this.ResponseFormatter.Format(response);

                            // Replace "\n" by the environment NewLine
                            commandEventArgs.Response = commandEventArgs.Response.Replace("\n", System.Environment.NewLine);
                        };

                        // Add session to the collection
                        lock (NetworkCommunicationSessionsLock)
                        {
                            NetworkCommunicationSessions.Add(networkCommunicationSession.ID, networkCommunicationSession);
                        }

#pragma warning disable 4014

                        // Run Communication Session
                        networkCommunicationSession.RunAsync(cancellationToken).ContinueWith(t =>
                        {
                            // Stop Session
                            networkCommunicationSession.Stop();

                            // Remove Session from Internal Controls
                            lock (NetworkCommunicationSessionsLock)
                            {
                                NetworkCommunicationSessions.Remove(networkCommunicationSession.ID);
                            }

                            // Unregister session with the Command Processor
                            this.EndSession(networkCommunicationSession.ID);

                            // Call SessionEnded event
                            SessionEnded?.Invoke(this, new SessionEndedEventArgs(networkCommunicationSession.ID));
                        }, cancellationToken);

#pragma warning restore 4014
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (Server != null)
                {
                    Server.Stop();
                }
            }
        }
Ejemplo n.º 18
0
 private void Client_Disconnected(object sender, EventArgs e)
 {
     StopAliveTimers();
     Disconnected?.Invoke(this, EventArgs.Empty);
     SessionEnded?.Invoke(this, false);
 }