Esempio n. 1
0
        public override Task AssertEventStoreHasOneEvent(AggregateInfo aggregateInfo)
        {
            var records = ((InMemoryEventStore)EventStore).Db.Where(x => x.AggregateInfo == aggregateInfo);

            records.Count().ShouldBe(1);
            return(Task.CompletedTask);
        }
        /// <summary>
        /// Constructeur.
        /// </summary>
        /// <param name="dbPath">Chemin de la base de données.</param>
        /// <param name="aggregateInfo">Informations sur l'agrégat.</param>
        public SqliteRepositoryProvider(IDatabaseContext databaseContext, AggregateInfo aggregateInfo)
        {
            this.databaseContext = databaseContext;
            databaseContext.EnsureDatabaseCreated();

            data = databaseContext.GetDbSet <AggregateImplementationT, AggregateT, IndexT>(aggregateInfo);
        }
Esempio n. 3
0
        public Clustering(ISet <TSource> instances, Func <TSource, double> clusterValueFunc)
        {
            _instances = instances;

            if (_instances.Count == 0)
            {
                return;
            }

            AggregateInfo AggregateInstances(AggregateInfo agg, TSource current)
            {
                var currentValue = clusterValueFunc(current);

                agg.Max    = Math.Max(agg.Max, currentValue);
                agg.Min    = Math.Min(agg.Min, currentValue);
                agg.Count += 1;
                agg.Sum   += currentValue;
                return(agg);
            }

            var seed = new AggregateInfo {
                Min = double.MaxValue, Max = double.MinValue, Sum = 0, Count = 0
            };
            var info = _instances.Aggregate(seed, AggregateInstances);

            MaxValue     = info.Max;
            MinValue     = info.Min;
            AverageValue = info.Sum / info.Count;
        }
Esempio n. 4
0
        public async Task <AggregateEvent[]> LoadEvents(AggregateInfo aggregateInfo, String aggregateId)
        {
            if (aggregateInfo == null)
            {
                throw new ArgumentNullException(nameof(aggregateInfo));
            }
            if (String.IsNullOrWhiteSpace(aggregateId))
            {
                throw new ArgumentNullException(nameof(aggregateId));
            }

            var collection = Db.GetCollection <BsonDocument>(aggregateInfo.Id);
            var filter     = new BsonDocument("aggregateId", aggregateId);
            var documents  = await collection.Find(filter).ToListAsync();

            var events = new List <AggregateEvent>();

            foreach (var doc in documents)
            {
                var eventInfoId = doc.GetValue("eventInfoId").AsString;
                var eventType   = _logicSchema.FindAggregateEvent(eventInfoId).Type;
                var eventData   = doc.GetValue("eventData").AsString;
                events.Add((AggregateEvent)JsonSerializer.Deserialize(eventData, eventType, _serializationOptions));
            }
            return(events.ToArray());
        }
Esempio n. 5
0
        /// <summary>
        /// Returns the result of the specified aggregated function(s) executed in a SQL Database.
        /// </summary>
        /// <param name="entity">The entity type</param>
        /// <param name="aggregateInfo">The aggregateInfo data</param>
        /// <param name="searchType">The search type</param>
        /// <param name="filter">The filter info</param>
        /// <returns>The agregated list of entities</returns>
        public IList <Entity> GetAggregateEntities(Entity entity, AggregateInfo aggregateInfo, FilterInfo.SearchType searchType, FilterInfo filter)
        {
            LoggerHelper.Info("Start");
            IList <Entity> list = new List <Entity>();

            try
            {
                Entity           aggregateEntity = new Entity();
                StatementWrapper stmtWrapper     = GetQueryBuilder().BuildAggregateStatement(entity, aggregateInfo, aggregateEntity, searchType, filter);
                LoggerHelper.Debug(stmtWrapper.Query.ToString());

                ResultSetHandler <IList <Entity> > h = new EntityHandler <Entity>(aggregateEntity);
                list = GetQueryRunner().Query(GetConnection(), stmtWrapper, h);
            }
            catch (Exception e)
            {
                LoggerHelper.Error(e);
                throw new Exception("Unable to fetch " + entity.GetTableName() + " list.", e);
            }
            finally
            {
                LoggerHelper.Info("End");
            }

            return(list);
        }
Esempio n. 6
0
        /// <summary>
        /// Executes an aggregated operation in the datasource and returns the list of entities as a JSON response.
        /// </summary>
        /// <param name="request">The request</param>
        /// <returns>a JSON response</returns>
        public virtual string GetAggreateEntities(HttpRequest request)
        {
            LoggerHelper.Info("Start");
            IList <Entity> list = new List <Entity>();

            try
            {
                if (string.IsNullOrEmpty(request.Params[AggregateParam]))
                {
                    throw new Exception("aggregate info can not be null.");
                }

                Page page = GetPage(request);

                //Creating entity
                Entity entity = CreateEntity(request, page);

                string json = request.Params[AggregateParam];
                LoggerHelper.Debug("AggregateInfo = " + json);
                AggregateInfo aggregateInfo = (AggregateInfo) new JavaScriptSerializer().Deserialize(json, typeof(AggregateInfo));
                list = GetCatalogDAO(page).GetAggregateEntities(entity, aggregateInfo, GetSearchType(request), CreateFilter(request));
            }
            catch (Exception e)
            {
                LoggerHelper.Error(e);
                return(ErrorResponse(e));
            }
            finally
            {
                LoggerHelper.Info("End");
            }

            return(CreateEntityListResponse(list));
        }
Esempio n. 7
0
        /// <summary>
        /// Constructeur.
        /// </summary>
        /// <param name="repositoriesConfiguration">Configuratrion des répertoires de données.</param>
        /// <param name="repositoryService">Service de gestion des répertoires de données.</param>
        public Repository(IRepositoriesConfiguration repositoriesConfiguration, IRepositoryService repositoryService)
        {
            // Recherche des informations de l'égrégat.
            AggregateInfo aggregateInfo = repositoryService.GetInfo <AggregateT>();

            // Récupération du fournisseur de données pour l'agrégat.
            provider = repositoriesConfiguration.GetRepositoryProvider <AggregateT, IndexT>(aggregateInfo);
        }
Esempio n. 8
0
        private async Task <Aggregate> LoadOrCreate(String id, AggregateInfo aggregateInfo)
        {
            var aggregateLogicInfo = _logicSchema.GetAggregate(aggregateInfo);
            var persistedEvents    = await _eventStore.LoadEvents(aggregateInfo, id);

            var aggregateLogic = (Aggregate)Activator.CreateInstance(aggregateLogicInfo.Type, new[] { id });

            aggregateLogic.LoadFromHistory(persistedEvents);
            return(aggregateLogic);
        }
Esempio n. 9
0
        /// <summary>
        /// Génération d'un agrégat.
        /// </summary>
        /// <typeparam name="AggregateT">Type de l'agrégat.</typeparam>
        /// <typeparam name="IndexT">Type de l'index.</typeparam>
        /// <returns>Agrégat.</returns>
        private AggregateT BuildAggregate <AggregateT, IndexT>()
            where AggregateT : IAggregate <IndexT>
            where IndexT : IComparable, IComparable <IndexT>, IEquatable <IndexT>
        {
            // Recherche des informations de l'agrégat pour en extraire l'implémentation
            AggregateInfo aggregateInfo      = repositoryService.GetInfo <AggregateT>();
            Type          implementationType = aggregateInfo.ImplementationType;

            // Instanciation d'un agrégat.
            return((AggregateT)Activator.CreateInstance(implementationType));
        }
Esempio n. 10
0
        public Task <AggregateEvent[]> LoadEvents(AggregateInfo aggregateInfo, String aggregateId)
        {
            if (aggregateInfo == null)
            {
                throw new ArgumentNullException(nameof(aggregateInfo));
            }
            if (String.IsNullOrWhiteSpace(aggregateId))
            {
                throw new ArgumentNullException(nameof(aggregateId));
            }

            var records = Db.Where(x => x.AggregateInfo == aggregateInfo && x.AggregateId == aggregateId);

            return(Task.FromResult(records.Select(x => x.Event).ToArray()));
        }
Esempio n. 11
0
        public override async Task AssertEventStoreHasOneEvent(AggregateInfo aggregateInfo)
        {
            var collectionName = aggregateInfo.Id;

            using (var collections = await((MongoEventStore)EventStore).Db.ListCollectionNamesAsync())
            {
                await collections.MoveNextAsync();

                collections.Current.ShouldContain(collectionName);
            }
            var collection = ((MongoEventStore)EventStore).Db.GetCollection <BsonDocument>(collectionName);

            var documentsCount = await collection.CountDocumentsAsync(new BsonDocument());

            documentsCount.ShouldBe(1);
        }
Esempio n. 12
0
        /// <summary>
        /// Enregistrement d'un répertoire de données.
        /// </summary>
        /// <param name="contractType">Type du contrat.</param>
        /// <param name="implementationType">Type de l'implémentation.</param>
        /// <param name="registerForIoc">Action pour l'enregistrmenet du répertoire dans le conteneur IoC.</param>
        private void Register(Type contractType, Type implementationType)
        {
            // Recherche du type d'index de l'agrégat.
            Type indexType = TypeTools.GetAllInterfacesForType(contractType)
                             .Where(t => t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(IAggregate <>)))
                             .Select(t => t.GetGenericArguments().FirstOrDefault()).FirstOrDefault();

            // Contrôle du type de l'index.
            if (indexType == null)
            {
                throw new InvalidOperationException($"The aggregate {contractType} does not implement {typeof(IAggregate<>)}.");
            }

            // Enregistrement des informations sur l'agrégat.
            AggregateInfo aggregatenfo = new AggregateInfo(contractType, indexType, implementationType, implementationType.Name);

            if (aggregateInfoContainer.ContainsKey(contractType))
            {
                throw new ArgumentException($"The aggregate {contractType} is already registered.");
            }
            aggregateInfoContainer[contractType] = aggregatenfo;

            // Création des types génériques.
            Type repositoryContract       = typeof(IRepository <,>).MakeGenericType(contractType, indexType);
            Type repositoryImplementation = typeof(Repository <,>).MakeGenericType(contractType, indexType);

            // Enregistrement de la correspondance dans le conteneur IoC.
            registerForIoc(repositoryContract, repositoryImplementation);

            // Enregistrement des intercepteurs d'évènements par défaut.
            Type modificationEventHandlerContract       = typeof(IModificationEventHandler <,>).MakeGenericType(contractType, indexType);
            Type modificationEventHandlerImplementation = typeof(ModificationEventHandler <,>).MakeGenericType(contractType, indexType);

            eventHandlerServiceInitializer.RegisterEventHandler(modificationEventHandlerContract, modificationEventHandlerImplementation);
            registerForIoc(modificationEventHandlerContract, modificationEventHandlerImplementation);

            Type deletionEventHandlerContract       = typeof(IDeletionEventHandler <,>).MakeGenericType(contractType, indexType);
            Type deletionEventHandlerImplementation = typeof(DeletionEventHandler <,>).MakeGenericType(contractType, indexType);

            eventHandlerServiceInitializer.RegisterEventHandler(deletionEventHandlerContract, deletionEventHandlerImplementation);
            registerForIoc(deletionEventHandlerContract, deletionEventHandlerImplementation);
        }
Esempio n. 13
0
 public IList <Entity> GetAggregateEntities(Entity entity, AggregateInfo aggregateInfo, FilterInfo.SearchType searchType, FilterInfo filter)
 {
     return(sqlDAO.GetAggregateEntities(entity, aggregateInfo, searchType, filter));
 }
 public new void Create(AggregateInfo aggregateInfo, Command command)
 {
     base.Create(aggregateInfo, command);
 }
 public new void Create(AggregateInfo aggregateInfo, Event @event)
 {
     base.Create(aggregateInfo, @event);
 }
 public new void Buildup(AggregateInfo aggregateInfo, ICollection<Event> replayEvents)
 {
     base.Buildup(aggregateInfo, replayEvents);
 }
Esempio n. 17
0
 /// <summary>
 /// Returns the result of the specified aggregated function(s) executed in an Oracle Database.
 /// </summary>
 /// <param name="entity">The entity type</param>
 /// <param name="aggregateInfo">The aggregateInfo data</param>
 /// <param name="searchType">The search type</param>
 /// <param name="filter">The filter info</param>
 /// <returns>The agregated list of entities</returns>
 public IList <Entity> GetAggregateEntities(Entity entity, AggregateInfo aggregateInfo, FilterInfo.SearchType searchType, FilterInfo filter)
 {
     throw new NotImplementedException("This method is not available in offline mode.");
 }
Esempio n. 18
0
        private void consumeEventOnAggregate(RaisedEvent raisedEvent, AggregateInfo aggregateInfo, ConsumptionLog consumptionLog)
        {
            //If it's not tracked, then select it from the domain.
            if (aggregateInfo.Lifestate == AggregateLifestate.Untracked)
                selectAggregate(aggregateInfo);

            using (var scope = new TransactionScope())
            {
                try
                {
                    try
                    {
                        //If we haven't found it in the domain, then create it, otherwise consume the event.
                        if (aggregateInfo.Lifestate == AggregateLifestate.Untracked)
                            AggregateFactory.Create(aggregateInfo, raisedEvent.Event);
                        else
                            aggregateInfo.Instance.AsDynamic().Receive(raisedEvent);
                    }
                    catch (ApplicationException e)
                    {
                        if (e.Source == "ReflectionMagic")
                            throw new MissingMethodException(
                                aggregateInfo.Type.FullName,
                                string.Format(
                                    "{0}({1})",
                                    aggregateInfo.Lifestate == AggregateLifestate.Untracked ? "_ctor" : "Receive",
                                    raisedEvent.GetType()));

                        throw;
                    }
                }
                catch (Exception e)
                {
                    consumptionLog.RecordExceptionForConsumer(e);
                }

                consumptionLog.RecordConsumptionComplete();

                Store.LogConsumption(raisedEvent, consumptionLog);
                scope.Complete();
            }
        }
Esempio n. 19
0
 /// <summary>
 /// Returns the result of the specified aggregated function(s) executed in a SQL Database.
 /// </summary>
 /// <param name="entity">The entity type</param>
 /// <param name="aggregateInfo">The aggregateInfo data</param>
 /// <param name="searchType">The search type</param>
 /// <returns>The agregated list of entities</returns>
 public IList <Entity> GetAggregateEntities(Entity entity, AggregateInfo aggregateInfo, FilterInfo.SearchType searchType)
 {
     return(GetAggregateEntities(entity, aggregateInfo, searchType, null));
 }
Esempio n. 20
0
 public abstract Task AssertEventStoreHasOneEvent(AggregateInfo aggregateInfo);
Esempio n. 21
0
        /// <summary>
        /// Recupération de l'accesseur aux données de la base.
        /// </summary>
        /// <typeparam name="AggregateT">Type d'agrégat.</typeparam>
        /// <typeparam name="IndexT">Type de l'idex.</typeparam>
        /// <param name="aggregateInfo">Informations sur l'agrégat.</param>
        /// <returns>Accesseur aux données de la base.</returns>
        public DbSet <AggregateImplementationT> GetDbSet <AggregateImplementationT, AggregateT, IndexT>(AggregateInfo aggregateInfo)
            where AggregateImplementationT : class, AggregateT
            where AggregateT : IAggregate <IndexT>
            where IndexT : IComparable, IComparable <IndexT>, IEquatable <IndexT>
        {
            string aggregateName = aggregateInfo.ImplementationType.Name;

            if (!dbSets.ContainsKey(aggregateName))
            {
                throw new ArgumentOutOfRangeException($"The aggregate {aggregateName} is not registered.");
            }

            return((DbSet <AggregateImplementationT>)dbSets[aggregateName]);
        }
Esempio n. 22
0
 private void selectAggregate(AggregateInfo aggregateInfo)
 {
     var replayEvents = Store.EventsForAggregate(aggregateInfo.Type, aggregateInfo.Key);
     if (replayEvents.Any())
         AggregateFactory.Buildup(aggregateInfo, replayEvents);
 }
Esempio n. 23
0
 public IList <Entity> GetAggregateEntities(Entity entity, AggregateInfo aggregateInfo, FilterInfo.SearchType searchType)
 {
     return(sqlDAO.GetAggregateEntities(entity, aggregateInfo, searchType));
     //TODO: implement logic to performe the aggregate operation if the table is in the cache
 }
Esempio n. 24
0
 public Aggregate(AggregateInfo info, T data)
 {
     Info = info;
     Data = data;
 }