示例#1
0
 public void InitializeSessionTrackerTest()
 {
     _mockChannelGroup = new Mock <IChannelGroup>();
     _mockChannel      = new Mock <IChannelUnit>();
     _mockChannelGroup.Setup(
         group => group.AddChannel(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <TimeSpan>(),
                                   It.IsAny <int>()))
     .Returns(_mockChannel.Object);
     _sessionTracker = new SessionTracker(_mockChannelGroup.Object, _mockChannel.Object);
     SessionTracker.SessionTimeout = 500; // 0.5s
     SessionTracker.LastSid        = Guid.Empty;
 }
示例#2
0
 // fire when a session is abandoned or expires
 protected void Session_End(object sender, EventArgs e)
 {
     // experimental
     try
     {
         SessionTracker.Remove(Session.SessionID);
     }
     catch (Exception)
     {
         //
     }
 }
        public void TestSetSessionIdNone()
        {
            var log = new EventLog {
                Toffset = 430
            };
            var sessions = new Dictionary <long, Guid> {
                { 431, Guid.Empty }, { 632, Guid.Empty }, { 461, Guid.Empty }
            };
            var success = SessionTracker.SetExistingSessionId(log, sessions);

            Assert.IsFalse(success);
            Assert.IsFalse(log.Sid.HasValue);
        }
        public void TestSetSessionIdEqualTo()
        {
            var log = new EventLog {
                Toffset = 430
            };
            var intendedSid = Guid.NewGuid();
            var sessions    = new Dictionary <long, Guid> {
                { 4, Guid.Empty }, { 430, intendedSid }, { 431, Guid.Empty }
            };
            var success = SessionTracker.SetExistingSessionId(log, sessions);

            Assert.IsTrue(success);
            Assert.AreEqual(intendedSid, log.Sid.Value);
        }
        public void CanStartSession()
        {
            // Arrange
            var sessionTracker = new SessionTracker(new NullLogger <SessionTracker>(), DefaultTimeoutCheckInterval, DefaultTimeoutCheckInterval);
            var game           = Helpers.GetOrCreateGame("CanStartSession");

            var user = Helpers.GetOrCreateUser($"CanStartSession");

            // Act
            var session = sessionTracker.StartSession(game.Id, user.Id);

            // Assert
            Assert.True(sessionTracker.IsActive(session.Id));
        }
示例#6
0
        public void TestSetSessionIdNone()
        {
            var time = new DateTime(430 * TimeSpan.TicksPerMillisecond);
            var log  = new EventLog {
                Timestamp = time
            };
            var sessions = new Dictionary <long, Guid> {
                { 431, Guid.Empty }, { 632, Guid.Empty }, { 461, Guid.Empty }
            };
            var success = SessionTracker.SetExistingSessionId(log, sessions);

            Assert.IsFalse(success);
            Assert.IsFalse(log.Sid.HasValue);
        }
示例#7
0
        public void TestSetSessionIdEqualTo()
        {
            var time = new DateTime(430 * TimeSpan.TicksPerMillisecond);
            var log  = new EventLog {
                Timestamp = time
            };
            var intendedSid = Guid.NewGuid();
            var sessions    = new Dictionary <long, Guid> {
                { 4, Guid.Empty }, { 430, intendedSid }, { 431, Guid.Empty }
            };
            var success = SessionTracker.SetExistingSessionId(log, sessions);

            Assert.IsTrue(success);
            Assert.AreEqual(intendedSid, log.Sid);
        }
        private void LogInPublicModeRegistration(UserInfo user)
        {
            string          strRoles  = string.Empty;
            RoleController  role      = new RoleController();
            SageFrameConfig sfConfig  = new SageFrameConfig();
            string          userRoles = role.GetRoleNames(user.UserName, GetPortalID);

            strRoles += userRoles;
            if (strRoles.Length > 0)
            {
                SetUserRoles(strRoles);
                SessionTracker sessionTracker = (SessionTracker)Session[SessionKeys.Tracker];
                sessionTracker.PortalID      = GetPortalID.ToString();
                sessionTracker.Username      = user.UserName;
                Session[SessionKeys.Tracker] = sessionTracker;
                SageFrame.Web.SessionLog SLog = new SageFrame.Web.SessionLog();
                SLog.SessionTrackerUpdateUsername(sessionTracker, sessionTracker.Username, GetPortalID.ToString());
                {
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                                                                                     user.UserName,
                                                                                     DateTime.Now,
                                                                                     DateTime.Now.AddMinutes(30),
                                                                                     true,
                                                                                     GetPortalID.ToString(),
                                                                                     FormsAuthentication.FormsCookiePath);
                    // Encrypt the ticket.
                    string encTicket = FormsAuthentication.Encrypt(ticket);
                    // Create the cookie.
                    Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName + "_" + GetApplicationName + "_" + GetPortalID, encTicket));
                    bool IsUseFriendlyUrls = sfConfig.GetSettingBollByKey(SageFrameSettingKeys.UseFriendlyUrls);
                    if (IsUseFriendlyUrls)
                    {
                        if (GetPortalID > 1)
                        {
                            Response.Redirect(ResolveUrl("~/portal/" + GetPortalSEOName + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + SageFrameSettingKeys.PageExtension), false);
                        }
                        else
                        {
                            Response.Redirect(ResolveUrl("~/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + SageFrameSettingKeys.PageExtension), false);
                        }
                    }
                    else
                    {
                        Response.Redirect(ResolveUrl("~/Default.aspx?ptlid=" + GetPortalID + "&ptSEO=" + GetPortalSEOName + "&pgnm=" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage)), false);
                    }
                }
            }
        }
        public EvaluationTracker(
            ProgressEvaluator progressEvaluator,
            EvaluationController evaluationController,
            SessionTracker sessionTracker)
        {
            _progressEvaluator    = progressEvaluator;
            _evaluationController = evaluationController;
            _sessionTracker       = sessionTracker;

            _sessionTracker.SessionStartedEvent += OnSessionStarted;
            _sessionTracker.SessionEndedEvent   += OnSessionEnded;
            EvaluationDataController.EvaluationDataAddedEvent += OnEvaluationDataAdded;
            EvaluationController.EvaluationCreatedEvent       += OnEvaluationCreated;
            EvaluationController.EvaluationUpdatedEvent       += OnEvaluationUpdated;
            EvaluationController.EvaluationDeletedEvent       += OnEvaluationDeleted;
        }
示例#10
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());

            ModelMetadataProviders.Current = new CachedDataAnnotationsModelMetadataProvider();

            // clear all sessions used for online users count
            SessionTracker.RemoveAllSessions();
        }
示例#11
0
        public void VerifySessionChangesOnReenabling()
        {
            _sessionTracker.Resume();
            var sid1 = SessionTracker.Sid;

            Assert.AreNotEqual(Guid.Empty, sid1);

            // Disable and enable again.
            _sessionTracker = new SessionTracker(_mockChannelGroup.Object, _mockChannel.Object);
            _sessionTracker.Resume();

            // Verify second session has a different identifier, not the new one analytics wanted but the updated correlation identifier instead.
            var sid2 = SessionTracker.Sid;

            Assert.AreNotEqual(Guid.Empty, sid2);
            Assert.AreNotEqual(sid1, sid2);
        }
示例#12
0
        public async void CurrentSessionCanBeSet()
        {
            var server = new TestServer(1);

            server.Start();

            var sessionTracking = new SessionTracker(new Configuration("123456")
            {
                SessionTrackingInterval = TimeSpan.FromSeconds(5), SessionEndpoint = server.Endpoint
            });

            sessionTracking.CreateSession();

            var requests = await server.Requests();

            Assert.NotNull(sessionTracking.CurrentSession);
        }
    private void LogInPublicModeRegistration()
    {
        string strRoles             = string.Empty;
        MembershipController member = new MembershipController();
        RoleController       role   = new RoleController();
        UserInfo             user   = member.GetUserDetails(GetPortalID, UserName.Text);

        if (!(string.IsNullOrEmpty(UserName.Text) && string.IsNullOrEmpty(Password.Text)))
        {
            if (PasswordHelper.ValidateUser(user.PasswordFormat, Password.Text, user.Password, user.PasswordSalt))
            {
                string userRoles = role.GetRoleNames(user.UserName, GetPortalID);
                strRoles += userRoles;
                if (strRoles.Length > 0)
                {
                    SetUserRoles(strRoles);
                    SessionTracker sessionTracker = (SessionTracker)Session["Tracker"];
                    sessionTracker.PortalID = GetPortalID.ToString();
                    sessionTracker.Username = UserName.Text;
                    Session["Tracker"]      = sessionTracker;
                    SageFrame.Web.SessionLog SLog = new SageFrame.Web.SessionLog();
                    SLog.SessionTrackerUpdateUsername(sessionTracker, sessionTracker.Username, GetPortalID.ToString());
                    {
                        FormsAuthentication.SetAuthCookie(UserName.Text, true);
                        bool IsUseFriendlyUrls = pagebase.GetSettingBollByKey(SageFrameSettingKeys.UseFriendlyUrls);
                        if (IsUseFriendlyUrls)
                        {
                            if (GetPortalID > 1)
                            {
                                Response.Redirect(ResolveUrl("~/portal/" + GetPortalSEOName + "/" + pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + ".aspx"), false);
                            }
                            else
                            {
                                Response.Redirect(ResolveUrl("~/" + pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + ".aspx"), false);
                            }
                        }
                        else
                        {
                            Response.Redirect(ResolveUrl("~/Default.aspx?ptlid=" + GetPortalID + "&ptSEO=" + GetPortalSEOName + "&pgnm=" + pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage)), false);
                        }
                    }
                }
            }
        }
    }
示例#14
0
        public IActionResult UploadPhotoAndStartSession([FromBody] PhotoRequest photoRequest,
                                                        [FromServices] UserManager <ApplicationUser> userManager,
                                                        [FromServices] SessionTracker sessionTracker,
                                                        [FromServices] IImageDecryptor imageDecryptor,
                                                        [FromServices] RecognitionTaskQueue taskQueue,
                                                        [FromServices] IConfiguration configuration,
                                                        [FromServices] AnalyticsAgent agent)
        {
            using (_logger.BeginScope(nameof(UploadPhotoAndStartSession)))
            {
                //validate request
                if (photoRequest == null)
                {
                    _logger.LogError("Attempt to start a session because of null mobile photo request.");
                    return(BadRequest(new { message = "Error: something in your request is empty" }));
                }

                try
                {
                    //try start new session
                    var session = sessionTracker.StartSession(Convert.ToInt32(userManager.GetUserId(HttpContext.User)), photoRequest.TimeStamp);

                    //decrypt image and send to db
                    _logger.LogInformation($"Trying decrypt image...");
                    var decrypredImage = imageDecryptor.Decrypt(Convert.FromBase64String(photoRequest.Image));
                    var image          = new Photo(session.SessionID, decrypredImage, photoRequest.TimeStamp);
                    _photoRepository.Add(image);
                    _logger.LogInformation($"Ecrypted image was decrypted and saved to db.");

                    //send to analytics task queue
                    _logger.LogInformation($"Trying send photoId to RecognitionTaskQueue");
                    string modelName = configuration.GetSection("ModelName").Value; // get model name for analytics
                    taskQueue.Enqueue(new RecognitionTask(modelName, image.PhotoID));
                    _logger.LogInformation("Photo was sent to RecognitionTaskQueue");

                    var sessionResponse = new SessionResponse(session.SessionID);
                    return(Ok(sessionResponse));
                }
                catch (Exception ex)
                {
                    _logger.LogError("Exception caught: {0}, {1}", ex.Message, ex.StackTrace);
                    return(StatusCode(409, new { message = ex.Message }));
                }
            }
        }
示例#15
0
        public void EvaluatesOnSessionStarted()
        {
            // Arrange
            var game = Helpers.GetOrCreateGame("EvaluatesOnSessionStarted");
            var user = Helpers.GetOrCreateUser("EvaluatesOnSessionStarted");

            var evaluation = Helpers.CreateAndCompleteGenericAchievement("EvaluatesOnSessionStarted", user.Id, game.Id);

            // Act
            SessionTracker.StartSession(game.Id, user.Id);

            // Assert
            var progress = EvaluationTracker.GetPendingNotifications(game.Id, user.Id);

            Assert.True(progress.ContainsKey(user.Id));                                          // should have evalauted for this user
            Assert.True(progress[user.Id].Any(kvp => kvp.Key.Id == evaluation.Id));              // Should have returned the progress for the evaluation
            Assert.Equal(1, progress[user.Id].Single(kvp => kvp.Key.Id == evaluation.Id).Value); //Completed evaluation should have progress value of 1
        }
示例#16
0
        private void SagePageLoadPart()
        {
            try
            {
                CreateGlobalVariables();
                if (!IsPostBack)
                {
                    hypHome.NavigateUrl    = sageNavigateUrl;
                    hypHome.Text           = sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage);
                    hypHome.ImageUrl       = GetTemplateImageUrl("home.png", true);
                    hypPreview.NavigateUrl = hypHome.NavigateUrl;
                    Image imgProgress = (Image)UpdateProgress1.FindControl("imgPrgress");
                    if (imgProgress != null)
                    {
                        imgProgress.ImageUrl = GetTemplateImageUrl("ajax-loader.gif", true);
                    }
                }
                if ((SessionTracker)Session["Tracker"] != null)
                {
                    SessionTracker sessionTracker = (SessionTracker)Session["Tracker"];
                    if (string.IsNullOrEmpty(sessionTracker.PortalID))
                    {
                        sessionTracker.PortalID = GetPortalID.ToString();
                        sessionTracker.Username = GetUsername;
                        SageFrameConfig sfConfig = new SageFrameConfig();
                        sessionTracker.InsertSessionTrackerPages = sfConfig.GetSettingsByKey(SageFrameSettingKeys.InsertSessionTrackingPages);

                        SageFrame.Web.SessionLog SLog = new SageFrame.Web.SessionLog();
                        SLog.SessionTrackerUpdateUsername(sessionTracker, GetUsername, GetPortalID.ToString());
                        SLog.StoreSessionTrackerAdd(sessionTracker, GetStoreID, GetPortalID);
                        Session["Tracker"] = sessionTracker;
                    }
                }
                //if ((StoreSettingInfo)Session["DefaultStoreSettings"] == null)
                //{
                //    AspxCommerceWebService AspxCommerceWebService = new AspxCommerceWebService();
                //    StoreSettingInfo DefaultStoreSettings = AspxCommerceWebService.GetAllStoreSettings(GetStoreID, GetPortalID, GetCurrentCultureName);
                //    Session["DefaultStoreSettings"] = DefaultStoreSettings;
                //}
            }
            catch
            {
            }
        }
示例#17
0
 protected void Session_End(object sender, EventArgs e)
 {
     try
     {
         SessionTracker sessionTracker = (SessionTracker)Session["Tracker"];
         if ((sessionTracker == null))
         {
             return;
         }
         else
         {
             SageFrame.Web.SessionLog sLog = new SageFrame.Web.SessionLog();
             sLog.SessionLogEnd(sessionTracker);
         }
     }
     catch
     {
     }
 }
示例#18
0
        // add a new session
        public static void Add(string subverseName, string sessionId)
        {
            try
            {
                if (SessionExists(sessionId, subverseName)) return;
                using (var db = new voatEntities())
                {
                    var newSession = new SessionTracker { SessionID = sessionId, Subverse = subverseName, CreationDate = DateTime.Now };

                    db.SessionTrackers.Add(newSession);
                    db.SaveChanges();

                }
            }
            catch (Exception)
            {
                //
            }
        }
示例#19
0
        public CommandApplicationProcess(RaftLog raftLog, int maxBatchSize, int flushEvery, System.Func <DatabaseHealth> dbHealth, LogProvider logProvider, ProgressTracker progressTracker, SessionTracker sessionTracker, CoreState coreState, InFlightCache inFlightCache, Monitors monitors)
        {
            if (!InstanceFieldsInitialized)
            {
                InitializeInstanceFields();
                InstanceFieldsInitialized = true;
            }
            this._raftLog         = raftLog;
            this._flushEvery      = flushEvery;
            this._progressTracker = progressTracker;
            this._sessionTracker  = sessionTracker;
            this._log             = logProvider.getLog(this.GetType());
            this._dbHealth        = dbHealth;
            this._coreState       = coreState;
            this._inFlightCache   = inFlightCache;
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
            this._commitIndexMonitor = monitors.NewMonitor(typeof(RaftLogCommitIndexMonitor), this.GetType().FullName);
            this._batcher            = new CommandBatcher(maxBatchSize, this.applyBatch);
            this._batchStat          = StatUtil.create("BatchSize", _log, 4096, true);
        }
        private void SagePageLoadPart()
        {
            if (!IsPostBack)
            {
                string          sageNavigateUrl = string.Empty;
                SageFrameConfig sfConfig        = new SageFrameConfig();
                if (IsUseFriendlyUrls)
                {
                    if (GetPortalID > 1)
                    {
                        sageNavigateUrl = ResolveUrl("~/portal/" + GetPortalSEOName + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage).Replace(" ", "-") + Extension);
                    }
                    else
                    {
                        sageNavigateUrl = ResolveUrl("~/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage).Replace(" ", "-") + Extension);
                    }
                }
                else
                {
                    sageNavigateUrl = ResolveUrl("~/Default" + Extension + "?ptlid=" + GetPortalID + "&ptSEO=" + GetPortalSEOName + "&pgnm=" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage).Replace(" ", "-"));
                }
                hypPreview.NavigateUrl = sageNavigateUrl;
                Image imgProgress = (Image)UpdateProgress1.FindControl("imgPrgress");
                if (imgProgress != null)
                {
                    imgProgress.ImageUrl = GetAdminImageUrl("ajax-loader.gif", true);
                }
            }
            SessionTracker sessionTracker = (SessionTracker)Session[SessionKeys.Tracker];

            if (string.IsNullOrEmpty(sessionTracker.PortalID))
            {
                sessionTracker.PortalID = GetPortalID.ToString();
                sessionTracker.Username = GetUsername;
                SageFrameConfig sfConfig = new SageFrameConfig();
                sessionTracker.InsertSessionTrackerPages = sfConfig.GetSettingsByKey(SageFrameSettingKeys.InsertSessionTrackingPages);
                SageFrame.Web.SessionLog SLog = new SageFrame.Web.SessionLog();
                SLog.SessionTrackerUpdateUsername(sessionTracker, GetUsername, GetPortalID.ToString());
                Session[SessionKeys.Tracker] = sessionTracker;
            }
        }
示例#21
0
 /// <summary>
 /// Application's  prerequest handler execute
 /// </summary>
 /// <param name="sender">Object sender</param>
 /// <param name="e">event arguments.</param>
 public void Application_PreRequestHandlerExecute(object sender, EventArgs e)
 {
     try
     {
         ApplicationController objAppController = new ApplicationController();
         if (objAppController.IsInstalled())
         {
             if ((Context.Session != null))
             {
                 SessionTracker tracker = (SessionTracker)Session[SessionKeys.Tracker];
                 if ((tracker != null))
                 {
                     tracker.AddPage(Request.Url.ToString());
                 }
             }
         }
     }
     catch
     {
     }
 }
        public async Task InactiveGetRemoved()
        {
            // Arrange
            var timeoutMilliseconds = 100;
            var game           = Helpers.GetOrCreateGame("InactiveGetRemoved");
            var sessions       = new List <Session>();
            var sessionTracker = new SessionTracker(new NullLogger <SessionTracker>(), new TimeSpan(0, 0, 0, 0, timeoutMilliseconds), new TimeSpan(0, 0, 0, 0, timeoutMilliseconds));

            for (var i = 0; i < 100; i++)
            {
                var user    = Helpers.GetOrCreateUser($"CanRemoveTimedOut_ShouldRemove_{i}");
                var session = sessionTracker.StartSession(game.Id, user.Id);
                sessions.Add(session);
            }

            // Act
            await Task.Delay(timeoutMilliseconds * 2);

            // Assert
            sessions.ForEach(s => Assert.False(sessionTracker.IsActive(s.Id)));
        }
示例#23
0
        public void EvaluatesOnEvaluationDataAdded()
        {
            // Arrange
            var game = Helpers.GetOrCreateGame("EvaluatesOnEvaluationDataAdded");
            var user = Helpers.GetOrCreateUser("EvaluatesOnEvaluationDataAdded");

            SessionTracker.StartSession(game.Id, user.Id);

            var evaluation = Helpers.CreateGenericAchievement("EvaluatesOnEvaluationDataAdded", game.Id);

            var gameDatas = Helpers.ComposeAchievementGameDatas(user.Id, evaluation, "100");

            // Act
            gameDatas.ForEach(g => ControllerLocator.GameDataController.Add(g));

            // Assert
            var progress = EvaluationTracker.GetPendingNotifications(game.Id, user.Id);

            Assert.True(progress.ContainsKey(user.Id));                             // should have evalauted for this user
            Assert.True(progress[user.Id].Any(kvp => kvp.Key.Id == evaluation.Id)); // Should have returned the progress for the evaluation
        }
示例#24
0
        public void RemovesOnSessionEnded()
        {
            // Arrange
            var game = Helpers.GetOrCreateGame("RemovesOnSessionEnded");
            var user = Helpers.GetOrCreateUser("RemovesOnSessionEnded");

            Helpers.CreateAndCompleteGenericAchievement("RemovesOnSessionEnded", user.Id, game.Id);

            var session = SessionTracker.StartSession(game.Id, user.Id);

            var progress = EvaluationTracker.GetPendingNotifications(game.Id, user.Id);

            Assert.True(progress.ContainsKey(user.Id)); // should have evalauted for this user

            // Act
            SessionTracker.EndSession(session.Id);

            // Assert
            progress = EvaluationTracker.GetPendingNotifications(game.Id, user.Id);
            Assert.False(progress.ContainsKey(user.Id)); // Shouldn't have any progress for this user
        }
示例#25
0
        public void DoesntGetAlreadyRecievedNotifications()
        {
            // Arrange
            var game = Helpers.GetOrCreateGame("DoesntGetAlreadyRecievedNotifications");
            var user = Helpers.GetOrCreateUser("DoesntGetAlreadyRecievedNotifications");

            SessionTracker.StartSession(game.Id, user.Id);

            var evaluation = Helpers.CreateAndCompleteGenericAchievement("DoesntGetAlreadyRecievedNotifications", user.Id, game.Id);
            var progress   = EvaluationTracker.GetPendingNotifications(game.Id, user.Id);

            Helpers.CompleteGenericAchievement(evaluation, game.Id);
            // Act
            progress = EvaluationTracker.GetPendingNotifications(game.Id, user.Id);

            // Assert
            if (progress.ContainsKey(user.Id))
            {
                Assert.False(progress[user.Id].Any(p => p.Key.Id == evaluation.Id));
            }
        }
示例#26
0
        public void RemovesProgressWhenGotten()
        {
            // Arrange
            var game = Helpers.GetOrCreateGame("RemovesProgressWhenGotten");
            var user = Helpers.GetOrCreateUser("RemovesProgressWhenGotten");

            SessionTracker.StartSession(game.Id, user.Id);

            var evaluation = Helpers.CreateAndCompleteGenericAchievement("RemovesProgressWhenGotten", user.Id, game.Id);

            // Act
            var progress = EvaluationTracker.GetPendingNotifications(game.Id, user.Id);

            // Assert
            progress = EvaluationTracker.GetPendingNotifications(game.Id, user.Id);

            if (progress.ContainsKey(user.Id))
            {
                Assert.False(progress[user.Id].Any(p => p.Key.Id == evaluation.Id));
            }
        }
示例#27
0
        public void RemovesProgressOnEvaluationDeleted()
        {
            // Arange
            var game = Helpers.GetOrCreateGame("RemovesProgressOnEvaluationDeleted");
            var user = Helpers.GetOrCreateUser("RemovesProgressOnEvaluationDeleted");

            SessionTracker.StartSession(game.Id, user.Id);

            var evaluation = Helpers.CreateAndCompleteGenericAchievement("RemovesProgressOnEvaluationDeleted", user.Id, game.Id);

            // Act
            ControllerLocator.EvaluationController.Delete(evaluation.Token, game.Id, EvaluationType.Achievement);

            // Assert
            var progress = EvaluationTracker.GetPendingNotifications(game.Id, user.Id);

            // Make sure that there are no instances of the evaluation in the progress
            foreach (var actorProgress in progress)
            {
                Assert.False(actorProgress.Value.Any(kvp => kvp.Key.Id == evaluation.Id));
            }
        }
        public async Task CanRemoveTimedOut()
        {
            // Arrange
            var timeoutSeconds   = 5;
            var inactiveSessions = new List <Session>();
            var activeSessions   = new List <Session>();

            var sessionTracker = new SessionTracker(new NullLogger <SessionTracker>(), new TimeSpan(0, 0, 0, timeoutSeconds), DefaultTimeoutCheckInterval);
            var game           = Helpers.GetOrCreateGame("CanRemoveTimedOut");

            for (var i = 0; i < 5; i++)
            {
                var user    = Helpers.GetOrCreateUser($"CanRemoveTimedOut_ShouldRemove_{i}");
                var session = sessionTracker.StartSession(game.Id, user.Id);
                inactiveSessions.Add(session);
            }

            await Task.Delay(timeoutSeconds * 1000);

            for (var i = 0; i < 5; i++)
            {
                var user    = Helpers.GetOrCreateUser($"CanRemoveTimedOut_ShouldNotRemove_{i}");
                var session = sessionTracker.StartSession(game.Id, user.Id);
                activeSessions.Add(session);
            }

            // Act
            sessionTracker
            .GetType()
            .GetMethod("RemoveTimedOut", BindingFlags.Instance | BindingFlags.NonPublic)
            .Invoke(sessionTracker, null);

            // Assert
            inactiveSessions.ForEach(s => Assert.False(sessionTracker.IsActive(s.Id)));

            activeSessions.ForEach(s => Assert.True(sessionTracker.IsActive(s.Id)));
        }
        public async void EmptySessionsPayloadsAreNotSent()
        {
            var server = new TestServer();

            server.Start();

            var sessionTracking = new SessionTracker(new Configuration("123456")
            {
                SessionEndpoint = server.Endpoint
            });

            sessionTracking.CreateSession();

            // set the cancellation token length long enough so that the session
            // tracker would attempt to send sessions twice
            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(130));

            // the cancellation token should throw as we are 'expecting' 2 requests
            // to be received but we only want one to be sent as the second sessions
            // request will have no sessions data
            await Assert.ThrowsAsync <OperationCanceledException>(async() => {
                await server.Requests(2, cts.Token);
            });
        }
示例#30
0
        private void UpdateSessionTracker(SessionTracker sessionTracker, string sessionID)
        {
            SessionLog sLog = new SessionLog();

            sLog.SessionLogStart(sessionTracker, sessionID);
        }
示例#31
0
        public void CurrentSessionIsNullWithoutBeingSet()
        {
            var sessionTracking = new SessionTracker(new Configuration("123456"));

            Assert.Null(sessionTracking.CurrentSession);
        }