public async Task IntegrationWithRepo()
        {
            BsonMapRegistrationHelpers.AddBsonMapFor <TestEventEventStore>();
            var snapShotRepo = new Mock <ISnapShotRepository>();

            snapShotRepo.Setup(re => re.LoadSnapShot <TestEntity>(It.IsAny <string>()))
            .ReturnsAsync(SnapShotResult <TestEntity> .Default());
            var entityId   = Guid.NewGuid();
            var eventStore = new EventStore(
                new EventRepositoryMongoDb(EventMongoDb,
                                           new VersionCache(EventMongoDb)),
                snapShotRepo.Object, new SnapShotConfig());

            await eventStore.AppendAsync(new List <IDomainEvent> {
                new TestEventEventStore(entityId, "Test")
            }, 0);

            var loadAsync = await eventStore.LoadAsync <TestEntity>(entityId.ToString());

            var loadAsync2 = await eventStore.LoadAsync <TestEntity>(entityId.ToString());

            Assert.AreEqual(entityId, loadAsync.Value.Id);
            Assert.AreEqual("Test", loadAsync.Value.Name);

            Assert.AreEqual(entityId, loadAsync2.Value.Id);
            Assert.AreEqual("Test", loadAsync2.Value.Name);
        }
Example #2
0
        public async Task AddEvents_ForeachMethod()
        {
            BsonMapRegistrationHelpers.AddBsonMapFor <TestEventAllOk>();

            var eventRepository = new EventRepositoryMongoDb(EventMongoDb, new VersionCache(EventMongoDb));
            var snapShotRepo    = new Mock <ISnapShotRepository>();

            snapShotRepo.Setup(re => re.LoadSnapShot <TestEntity>(It.IsAny <string>()))
            .ReturnsAsync(SnapShotResult <TestEntity> .Default());

            var eventStore = new EventStore(eventRepository, snapShotRepo.Object, new SnapShotConfig());

            var newGuid = Guid.NewGuid();

            await eventStore.AppendAsync(
                new List <IDomainEvent> {
                new TestEventAllOk(newGuid, "Simon")
            },
                0);

            var result = await eventRepository.LoadEvents();

            Assert.AreEqual(1, result.Value.Count());
            Assert.AreEqual(newGuid.ToString(), result.Value.Single().DomainEvent.EntityId);
            Assert.AreEqual("Simon", ((TestEventAllOk)result.Value.Single().DomainEvent).Name);
        }
Example #3
0
        /// <summary>
        /// Method to read all of the snapshots in specific year.
        /// </summary>
        /// <param name="year">Year needed to get all snapshots pertaining to it.</param>
        /// <returns>A list of SnapShotResult objects.</returns>
        public async Task <List <SnapShotResult> > ReadYearlySnapshotAsync(string year)
        {
            using (Session session = MySQLX.GetSession(NOSQLConnection))
            {
                Schema schema = session.GetSchema(Constants.SnapshotSchemaName);

                var collection = schema.GetCollection(Constants.SnapshotCollectionPrefix);

                // Snapshots for specific year.
                DocResult result = await collection.Find($"{Constants.SnapshotMonth} like :_month").Bind("_month", year + "%").ExecuteAsync().ConfigureAwait(false);

                var snapshotList = new List <SnapShotResult>();

                // Making a snapshot object for each result and adding it into a list.
                while (result.Next())
                {
                    var snapshot = new SnapShotResult((string)result.Current[Constants.SnapshotMonth], (string)result.Current[Constants.SnapshotOperationsDict], (string)result.Current[Constants.SnapshotUsersDict], (string)result.Current[Constants.SnapshotTopCityDict],
                                                      (string)result.Current[Constants.SnapshotTopUserUploadedDict], (string)result.Current[Constants.SnapshotTopUploadedIngredientDict], (string)result.Current[Constants.SnapshotTopUploadedStoreDict],
                                                      (string)result.Current[Constants.SnapshotTopSearchedIngredientDict], (string)result.Current[Constants.SnapshotTopSearchedStoreDict], (string)result.Current[Constants.SnapshotTopUpvotedUserDict], (string)result.Current[Constants.SnapshotTopDownvotedUserDict]);
                    snapshotList.Add(snapshot);
                }

                return(snapshotList);
            }
        }
Example #4
0
        /// <summary>
        /// Method to read multiple snapshots.
        /// There are 3 retries, after the retries fail it will notify system admin.
        /// </summary>
        /// <param name="year">The year to get all the snapshots.</param>
        /// <returns>A snapshot object with data pertaining to the year.</returns>
        public async Task <SnapShotResult> ReadMultiSnapshotAsync(int year)
        {
            int currentNumExceptions = 0;
            var snapshot             = new SnapShotResult(null, null, null, null, null, null, null, null, null, null, null);

            while (currentNumExceptions < 4)
            {
                currentNumExceptions++;
                try
                {
                    snapshot = await _snapshotService.ReadMultiSnapshotAsync(year).ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString),
                                                   Constants.ReadMultiSnapshotOperation,
                                                   Constants.SystemIdentifier,
                                                   Constants.LocalHost, e.Message).ConfigureAwait(false);

                    // Increment the amount of tries and then check if the 3 retries are up.
                    // If it is, notify system admin.
                    currentNumExceptions++;
                    if (currentNumExceptions >= Constants.MaximumOperationRetries)
                    {
                        await SystemUtilityService.NotifySystemAdminAsync($"{Constants.ReadMultiSnapshotOperation} failed a maximum number of times for {Constants.LocalHost}.", Constants.SystemAdminEmailAddress).ConfigureAwait(false);
                    }
                }
            }
            return(snapshot);
        }
Example #5
0
        public async Task AddEvents_AutoProperty_NotNamedEntityId()
        {
            BsonMapRegistrationHelpers.AddBsonMapFor <TestEvent_BsonBug_AutoProperty_NotWithEntityIdName>();

            var eventRepository = new EventRepositoryMongoDb(EventMongoDb, new VersionCache(EventMongoDb));
            var snapShotRepo    = new Mock <ISnapShotRepository>();

            snapShotRepo.Setup(re => re.LoadSnapShot <TestEntity>(It.IsAny <string>()))
            .ReturnsAsync(SnapShotResult <TestEntity> .Default());

            var eventStore = new EventStore(eventRepository, snapShotRepo.Object, new SnapShotConfig());

            await eventStore.AppendAsync(new List <IDomainEvent> {
                new TestEvent_BsonBug_AutoProperty_NotWithEntityIdName("whatever", "Peter")
            },
                                         0);

            var result = await eventRepository.LoadEvents();

            Assert.AreEqual(1, result.Value.Count());
            var domainEvent = result.Value.Single().DomainEvent as TestEvent_BsonBug_AutoProperty_NotWithEntityIdName;

            Assert.AreEqual("whatever", domainEvent.EntityId);
            Assert.AreEqual("Peter", domainEvent.Name);
        }
        public Task <SnapShotResult <T> > LoadSnapShot <T>(string entityId) where T : new()
        {
            if (entityId == null)
            {
                return(Task.FromResult(SnapShotResult <T> .NotFound(null)));
            }
            if (!_snapShots.TryGetValue(entityId, out var entity))
            {
                return(Task.FromResult(SnapShotResult <T> .Default()));
            }
            var snapShotWrapper = (SnapShotWrapper <T>)entity;

            return(Task.FromResult(new SnapShotResult <T>(snapShotWrapper.Entity, snapShotWrapper.Version)));
        }
        public async Task NotFoundExceptionIsWithCorrectT()
        {
            var snapShotRepo = new Mock <ISnapShotRepository>();

            snapShotRepo.Setup(re => re.LoadSnapShot <TestEntity>(It.IsAny <string>()))
            .ReturnsAsync(SnapShotResult <TestEntity> .Default());
            var entityId   = Guid.NewGuid();
            var eventStore = new EventStore(new EventRepositoryMongoDb(EventMongoDb, new VersionCache(EventMongoDb)), snapShotRepo.Object, new SnapShotConfig());

            var result = await eventStore.LoadAsync <TestEntity>(entityId.ToString());

            var exception = Assert.ThrowsException <NotFoundException>(() => result.Value);

            Assert.IsTrue(exception.Message.StartsWith("Could not find TestEntity"));
        }
        public async Task IntegrationWithRepo_NotFound()
        {
            var snapShotRepo = new Mock <ISnapShotRepository>();

            snapShotRepo.Setup(re => re.LoadSnapShot <TestEntity>(It.IsAny <string>()))
            .ReturnsAsync(SnapShotResult <TestEntity> .Default());
            var entityId   = Guid.NewGuid();
            var eventStore = new EventStore(new EventRepositoryMongoDb(EventMongoDb, new VersionCache(EventMongoDb)), snapShotRepo.Object, new SnapShotConfig());

            await eventStore.AppendAsync(new List <IDomainEvent> {
                new TestEventEventStore(entityId, "Test")
            }, 0);

            var loadAsync = await eventStore.LoadAsync <TestEntity>(Guid.NewGuid().ToString());

            Assert.IsTrue(loadAsync.Is <NotFound>());
        }
        public async Task DifferentIdsInEventsDefined()
        {
            var snapShotRepo = new Mock <ISnapShotRepository>();

            snapShotRepo.Setup(re => re.LoadSnapShot <TestEntity>(It.IsAny <string>()))
            .ReturnsAsync(SnapShotResult <TestEntity> .Default());
            var entityId   = Guid.NewGuid();
            var entityId2  = Guid.NewGuid();
            var eventStore = new EventStore(new EventRepositoryMongoDb(EventMongoDb, new VersionCache(EventMongoDb)), snapShotRepo.Object, new SnapShotConfig());

            await Assert.ThrowsExceptionAsync <DifferentIdsException>(async() => await eventStore.AppendAsync(new
                                                                                                              List <IDomainEvent> {
                new
                TestEventEventStore(entityId, "Test"), new
                TestEventEventStore(entityId2, "Test")
            }, 0));
        }
        public async Task <SnapShotResult <T> > LoadSnapShot <T>(string entityId) where T : new()
        {
            if (entityId == null)
            {
                return(SnapShotResult <T> .NotFound(null));
            }
            var mongoCollection = _context.GetCollection <SnapShotDbo <T> >(_snapShotCollectionName);
            var asyncCursor     = await mongoCollection.FindAsync(r => r.Id == entityId);

            var snapShot = asyncCursor.ToList().FirstOrDefault();

            if (snapShot == null)
            {
                return(SnapShotResult <T> .Default());
            }
            return(new SnapShotResult <T>(snapShot.Payload, snapShot.Version));
        }
        public async Task ApplyMethod_WrongIfDeclared()
        {
            var entityStremRepo = new Mock <IEventRepository>();
            var snapShotRepo    = new Mock <ISnapShotRepository>();

            snapShotRepo.Setup(re => re.LoadSnapShot <TestEntity_NoIApply>(It.IsAny <string>()))
            .ReturnsAsync(SnapShotResult <TestEntity_NoIApply> .Default());
            var entityId            = Guid.NewGuid();
            var testEventEventStore = new TestEventEventStore(entityId);
            var domainEventWrapper  = new DomainEventWrapper
            {
                DomainEvent = testEventEventStore
            };

            entityStremRepo.Setup(ev => ev.LoadEventsByEntity(It.IsAny <string>(), It.IsAny <long>()))
            .ReturnsAsync(Result <IEnumerable <DomainEventWrapper> > .Ok(new[] { domainEventWrapper }));
            var eventStore = new EventStore(entityStremRepo.Object, snapShotRepo.Object, new SnapShotConfig());
            var loadAsync  = await eventStore.LoadAsync <TestEntity_NoIApply>(entityId.ToString());

            Assert.AreEqual(Guid.Empty, loadAsync.Value.Id);
        }
Example #12
0
        /// <summary>
        /// Method to read a snapshot pertaining to a specific month.
        /// </summary>
        /// <param name="year">Year needed to get specific snapshot.</param>
        /// <param name="month">Month needed to get specific snapshot.</param>
        /// <returns>A SnapShotResult object that has all the information.</returns>
        public async Task <SnapShotResult> ReadMonthlySnapshotAsync(string year, string month)
        {
            using (Session session = MySQLX.GetSession(NOSQLConnection))
            {
                Schema schema = session.GetSchema(Constants.SnapshotSchemaName);

                string specificMonth = year + month;

                var collection = schema.GetCollection(Constants.SnapshotCollectionPrefix);
                // Snapshot for specific month.
                DocResult result = await collection.Find($"{Constants.SnapshotMonth} = :_month").Bind("_month", specificMonth).ExecuteAsync().ConfigureAwait(false);

                // Making a snapshot object with the result.
                result.Next();

                var snapshot = new SnapShotResult((string)result.Current[Constants.SnapshotMonth], (string)result.Current[Constants.SnapshotOperationsDict], (string)result.Current[Constants.SnapshotUsersDict], (string)result.Current[Constants.SnapshotTopCityDict],
                                                  (string)result.Current[Constants.SnapshotTopUserUploadedDict], (string)result.Current[Constants.SnapshotTopUploadedIngredientDict], (string)result.Current[Constants.SnapshotTopUploadedStoreDict],
                                                  (string)result.Current[Constants.SnapshotTopSearchedIngredientDict], (string)result.Current[Constants.SnapshotTopSearchedStoreDict], (string)result.Current[Constants.SnapshotTopUpvotedUserDict], (string)result.Current[Constants.SnapshotTopDownvotedUserDict]);

                return(snapshot);
            }
        }
Example #13
0
 private void UpdateCache(SnapShotResult snapShotResult)
 {
     if (snapShotResult != null)
     {
         lock (this.m_Cache)
         {
             if (this.m_Cache.Count == 5)
             {
                 int key = -2147483648;
                 foreach (KeyValuePair<int, SnapShotResult> pair in this.m_Cache)
                 {
                     key = pair.Key;
                     break;
                 }
                 this.m_Cache.Remove(key);
             }
             this.m_Cache.Add(snapShotResult.SnapshotId, snapShotResult);
         }
     }
 }