コード例 #1
0
        static TranslateResult <T> BuildPrivate <T>(ProjectionExpression proj)
        {
            var eagerChildProjections = EagerChildProjectionGatherer.Gatherer(proj).Select(cp => BuildChild(cp)).ToList();
            var lazyChildProjections  = LazyChildProjectionGatherer.Gatherer(proj).Select(cp => BuildChild(cp)).ToList();

            Scope scope = new Scope(
                alias: proj.Select.Alias,
                positions: proj.Select.Columns.Select((c, i) => new { c.Name, i }).ToDictionary(p => p.Name !, p => p.i) /*CSBUG*/
                );

            Expression <Func <IProjectionRow, T> > lambda = ProjectionBuilder.Build <T>(proj.Projector, scope);

            var command = QueryFormatter.Format(proj.Select);

            var result = new TranslateResult <T>(

                eagerProjections: eagerChildProjections,
                lazyChildProjections: lazyChildProjections,

                mainCommand: command,
                projectorExpression: lambda,
                unique: proj.UniqueFunction
                );

            return(result);
        }
コード例 #2
0
        public void Mapping_Fails_For_Duplicate_Projection()
        {
            MemberMappingDescriptor desc = new MemberMappingDescriptor();

            desc.OwnerType = typeof(AttributedUserDTO);
            desc.Type      = typeof(string);
            desc.Member    = "FullName";
            desc.IsArray   = false;
            desc.IsList    = false;
            try
            {
                List <ProjectionItem> items = new List <ProjectionItem>();
                items.Add(new ProjectionItem("source", "target_1"));
                items.Add(new ProjectionItem("source", "target_2"));
                ProjectionBuilder.Build(desc, items);
            }
            catch (OtisException e)
            {
                if (e.Message.Contains("Invalid projection 'source => target_2'. 'source' is already mapped to '\"target_1\"'"))
                {
                    return;                     // success
                }
            }
            Assert.Fail("Tested method didn't throw an exception!");
        }
コード例 #3
0
        static TranslateResult <T> BuildPrivate <T>(ProjectionExpression proj)
        {
            var eagerChildProjections = EagerChildProjectionGatherer.Gatherer(proj).Select(cp => BuildChild(cp)).ToList();
            var lazyChildProjections  = LazyChildProjectionGatherer.Gatherer(proj).Select(cp => BuildChild(cp)).ToList();

            Scope scope = new Scope
            {
                Alias     = proj.Select.Alias,
                Positions = proj.Select.Columns.Select((c, i) => new { c.Name, i }).ToDictionary(p => p.Name, p => p.i),
            };

            Expression <Func <IProjectionRow, T> > lambda = ProjectionBuilder.Build <T>(proj.Projector, scope);

            var command = QueryFormatter.Format(proj.Select);

            var result = new TranslateResult <T>
            {
                EagerProjections     = eagerChildProjections,
                LazyChildProjections = lazyChildProjections,

                MainCommand = command,

                ProjectorExpression = lambda,

                Unique = proj.UniqueFunction,
            };

            return(result);
        }
コード例 #4
0
        public static ProjectionInfo <TResult> TranslateGroup <TKey, TDocument, TResult>(Expression <Func <TDocument, TKey> > idProjector, Expression <Func <IGrouping <TKey, TDocument>, TResult> > groupProjector, IBsonSerializer <TDocument> parameterSerializer, IBsonSerializerRegistry serializerRegistry)
        {
            var keyBinder          = new SerializationInfoBinder(serializerRegistry);
            var boundKeyExpression = BindSerializationInfo(keyBinder, idProjector, parameterSerializer);

            if (!(boundKeyExpression is ISerializationExpression))
            {
                var keySerializer = SerializerBuilder.Build(boundKeyExpression, serializerRegistry);
                boundKeyExpression = new SerializationExpression(
                    boundKeyExpression,
                    new BsonSerializationInfo(null, keySerializer, typeof(TKey)));
            }

            var idExpression = new IdExpression(boundKeyExpression, ((ISerializationExpression)boundKeyExpression).SerializationInfo);

            var groupBinder = new GroupSerializationInfoBinder(BsonSerializer.SerializerRegistry);

            groupBinder.RegisterMemberReplacement(typeof(IGrouping <TKey, TDocument>).GetProperty("Key"), idExpression);
            var groupSerializer      = new ArraySerializer <TDocument>(parameterSerializer);
            var boundGroupExpression = BindSerializationInfo(groupBinder, groupProjector, groupSerializer);
            var projectionSerializer = (IBsonSerializer <TResult>)SerializerBuilder.Build(boundGroupExpression, serializerRegistry);
            var projection           = ProjectionBuilder.Build(boundGroupExpression).AsBsonDocument;

            // must have an "_id" in a group document
            if (!projection.Contains("_id"))
            {
                var idProjection = ProjectionBuilder.Build(boundKeyExpression);
                projection.InsertAt(0, new BsonElement("_id", idProjection));
            }

            return(new ProjectionInfo <TResult>(projection, projectionSerializer));
        }
コード例 #5
0
 static IChildProjection LazyChild <K, V>(Expression projector, Scope scope)
 {
     return(new LazyChildProjection <K, V>
     {
         ProjectorExpression = ProjectionBuilder.Build <KeyValuePair <K, MList <V> .RowIdElement> >(projector, scope),
     });
 }
コード例 #6
0
 static IChildProjection EagerChild <K, V>(Expression projector, Scope scope)
 {
     return(new EagerChildProjection <K, V>
     {
         ProjectorExpression = ProjectionBuilder.Build <KeyValuePair <K, V> >(projector, scope),
     });
 }
コード例 #7
0
        public async Task Given_no_stock_When_reserve_cancel_projected_Then_error_occurs()
        {
            var stockId = Guid.NewGuid();

            var reserveExpired = new ReserveExpired(stockId, Guid.NewGuid());
            await Assert.ThrowsAsync <SkuStockEntryNotFoundException>(() => ProjectionBuilder.Handle(reserveExpired));
        }
コード例 #8
0
            static internal Expression <Func <IProjectionRow, T> > Build <T>(Expression expression, Scope scope)
            {
                ProjectionBuilder pb   = new ProjectionBuilder(scope);
                Expression        body = pb.Visit(expression);

                return(Expression.Lambda <Func <IProjectionRow, T> >(body, row));
            }
コード例 #9
0
        static IChildProjection LazyChild <K, V>(Expression projector, Scope scope, LookupToken token, SqlPreCommandSimple command)
            where K : notnull
        {
            var proj = ProjectionBuilder.Build <KeyValuePair <K, MList <V> .RowIdElement> >(projector, scope);

            return(new LazyChildProjection <K, V>(token, command, proj));
        }
コード例 #10
0
        public SkuStock_added_tests()// Given_sku_created_and_stock_added_messages_When_projected()
        {
            _stockCreatedEvent = new SkuStockCreated(Guid.NewGuid(), Guid.NewGuid(), 100, TimeSpan.FromDays(2));
            _stockAddedEvent   = new StockAdded(_stockCreatedEvent.SourceId, 15, "test pack");

            ProjectionBuilder.Handle(_stockCreatedEvent).Wait();
            ProjectionBuilder.Handle(_stockAddedEvent).Wait();
        }
コード例 #11
0
        /// <summary>
        /// Groups the specified projection.
        /// </summary>
        /// <typeparam name="TDocument">The type of the document.</typeparam>
        /// <param name="projection">The projection.</param>
        public void Group <TDocument>(Action <IProjectionBuilder <TDocument> > projection) where TDocument : IDocument
        {
            var projectionBuilder = new ProjectionBuilder <TDocument>();

            projection(projectionBuilder);

            GetCollection <TDocument>().Aggregate().Group(projectionBuilder.ProjectDefinition);
        }
コード例 #12
0
        public override object Execute(Expression expression)
        {
            ProjectionExpression projection = this.Translate(expression);
            var projector = ProjectionBuilder.Build(Context, projection.Projector);
            DirectorySearcher searcher = CreateSearcher(projection.Searcher);
            var reader = GetReader(projector, projection.Aggregator, true, (projection.Searcher == null) ? null : projection.Searcher.Skip);

            return(((Func <DirectorySearcher, object>)reader.Compile())(searcher));
        }
コード例 #13
0
        /// <summary>
        /// Lista publicações com base em uma tecnologia
        /// </summary>
        /// <param name="techieId">id da tecnologia a ser usada como base</param>
        public async Task <List <Publication> > ListPublicationsPerTechieId(ObjectId techieId)
        {
            var filter     = FilterBuilder.Exists(a => a.DeletedAt, false) & FilterBuilder.AnyEq(a => a.Techies, techieId);
            var projection = ProjectionBuilder.Slice(a => a.Comments, 0, 1); //Projeta 0 comentarios pois não vai mostrar a publicação, vai apenas calcular os dados dela então carregar os comentarios é desnecessario

            return(await Collection
                   .Find(filter)
                   .Project <Publication>(projection)
                   .ToListAsync());
        }
コード例 #14
0
        public SkuStock_taken_tests()// Given_sku_created_and_taken_messages_When_projected()
        {
            var stockId = Guid.NewGuid();

            _stockCreatedEvent = new SkuStockCreated(stockId, Guid.NewGuid(), 5, TimeSpan.FromDays(2));
            _stockTakenEvent   = new StockTaken(stockId, 3);

            ProjectionBuilder.Handle(_stockCreatedEvent).Wait();
            ProjectionBuilder.Handle(_stockTakenEvent).Wait();
        }
コード例 #15
0
        public async Task Given_no_reserve_When_reserve_taken_projected_Then_error_occurs()
        {
            var stockId           = Guid.NewGuid();
            var stockCreatedEvent = new SkuStockCreated(stockId, Guid.NewGuid(), 1, TimeSpan.FromDays(2));
            var reserveTaken      = new StockReserveTaken(stockId, Guid.NewGuid());

            await ProjectionBuilder.Handle(stockCreatedEvent);

            await Assert.ThrowsAsync <ReserveEntryNotFoundException>(() => ProjectionBuilder.Handle(reserveTaken));
        }
コード例 #16
0
        public SkuStock_reserve_taken_tests()// Given_sku_created_and_stock_added_and_stock_reserved_messages_When_projected()
        {
            var stockId = Guid.NewGuid();

            _stockCreatedEvent      = new SkuStockCreated(stockId, Guid.NewGuid(), 1, TimeSpan.FromDays(2));
            _stockReservedEvent     = new StockReserved(stockId, Guid.NewGuid(), DateTime.Now.AddDays(1), 7);
            _stockReserveTakenEvent = new StockReserveTaken(stockId, _stockReservedEvent.ReserveId);

            ProjectionBuilder.Handle(_stockCreatedEvent).Wait();
            ProjectionBuilder.Handle(_stockReservedEvent).Wait();
            ProjectionBuilder.Handle(_stockReserveTakenEvent).Wait();
        }
コード例 #17
0
        public QueryBuilder <T> ProjectionExclude(Expression <Func <T, object> > field)
        {
            if (Projection == null)
            {
                Projection = ProjectionBuilder.Exclude(field);
            }
            else
            {
                Projection = Projection.Exclude(field);
            }

            return(this);
        }
コード例 #18
0
        public MongoQueryBuilder <TEntity, TKey> ProjectionInclude(Expression <Func <TEntity, object> > field)
        {
            if (Projection == null)
            {
                Projection = ProjectionBuilder.Include(field);
            }
            else
            {
                Projection = Projection.Include(field);
            }

            return(this);
        }
コード例 #19
0
        public async Task <List <Publication> > ListPublications()
        {
            var filter     = FilterBuilder.Exists(a => a.DeletedAt, false);
            var sort       = SortBuilder.Descending(a => a.DateCreation);
            var projection = ProjectionBuilder.Slice(a => a.Comments, 0, 3);


            return(await Collection
                   .Find(filter)
                   .Sort(sort)
                   .Project <Publication>(projection)
                   .ToListAsync());
        }
コード例 #20
0
        private TranslateResult Translate(Expression expression)
        {
            var projection = expression as ProjectionExpression;
            var subQuery   = expression as SubQueryProjection;
            var groupQuery = expression as GroupingProjection;

            if (groupQuery != null)
            {
                throw new TabularException("Can't Return groups from group by you must use aggregates, or retrieve the complete table and run groupng in Linq to objects");
                ////var query = new TabularGroupByRewriter(groupQuery).Rewrite();
                ////return Translate(query);
            }
            if (subQuery != null)
            {
                projection = subQuery.Projection;
            }
            expression = TabularEvaluator.PartialEval(expression);
            var binder          = new TabularQueryBinder(this);
            var boundExpression = binder.Bind(expression);
            var orders          = binder.OrderByColumns;

            if (projection == null && subQuery == null)
            {
                if (boundExpression is ProjectionExpression)
                {
                    projection = (ProjectionExpression)boundExpression;
                }

                else
                {
                    return(Translate(boundExpression));
                }
            }

            if (projection == null)
            {
                throw new TabularException("Could not translate");
            }

            string commandText = new TabularQueryFormatter().Format(projection.Source, orders);

            LambdaExpression projector = new ProjectionBuilder().Build(projection.Projector);

            return
                (new TranslateResult
            {
                CommandText = commandText,
                Projector = projector
            });
        }
コード例 #21
0
        public static RenderedProjectionDefinition <TResult> TranslateProject <TDocument, TResult>(Expression <Func <TDocument, TResult> > projector, IBsonSerializer <TDocument> parameterSerializer, IBsonSerializerRegistry serializerRegistry)
        {
            var binder               = new SerializationInfoBinder(BsonSerializer.SerializerRegistry);
            var boundExpression      = BindSerializationInfo(binder, projector, parameterSerializer);
            var projectionSerializer = (IBsonSerializer <TResult>)SerializerBuilder.Build(boundExpression, serializerRegistry);
            var projection           = ProjectionBuilder.Build(boundExpression).AsBsonDocument;

            if (!projection.Contains("_id"))
            {
                projection.Add("_id", 0); // we don't want the id back unless we asked for it...
            }

            return(new RenderedProjectionDefinition <TResult>(projection, projectionSerializer));
        }
コード例 #22
0
        public Account_projection_tests()
        {
            _msg = new AccountCreated(Guid.NewGuid(), Guid.NewGuid(), 42);
            var user = new User {
                Id = _msg.UserId, Login = "******"
            };

            using (var context = CreateContext())
            {
                context.Users.Add(user);
                context.SaveChanges();
            }

            ProjectionBuilder.Handle(_msg).Wait();
        }
コード例 #23
0
        public async Task Given_sku_created_and_stock_added_and_stock_reserved_messages_When_projected()
        {
            var sourceId = Guid.NewGuid();

            await ProjectionBuilder.Handle(new SkuStockCreated(sourceId, Guid.NewGuid(), 1, TimeSpan.FromDays(2)));

            await ProjectionBuilder.Handle(new StockAdded(sourceId, 15, "test pack"));

            var stockReserved = new StockReserved(sourceId, Guid.NewGuid(), DateTime.Now.AddDays(1), 7);
            await ProjectionBuilder.Handle(stockReserved);

            //When_project_reserve_again_error_is_occured()
            await ProjectionBuilder.Handle(stockReserved)
            .ShouldThrow <ArgumentException>();
        }
コード例 #24
0
        /// <summary>
        /// Lista todas as publicações
        /// </summary>
        /// <returns>Lista de publicações</returns>
        public async Task <List <Publication> > ListPublications(int page)
        {
            var filter     = FilterBuilder.Exists(a => a.DeletedAt, false);
            var sort       = SortBuilder.Descending(a => a.DateCreation);
            var projection = ProjectionBuilder.Slice(a => a.Comments, 0, 3);


            return(await Collection
                   .Find(filter)
                   .Sort(sort)
                   .Skip((page - 1) * UtilBO.QUANTIDADE_PAGINAS)
                   .Limit(UtilBO.QUANTIDADE_PAGINAS)
                   .Project <Publication>(projection)
                   .ToListAsync());
        }
コード例 #25
0
        public Order_created_projection_test()// Given_order_created_message()
        {
            _msg = new OrderCreated(Guid.NewGuid(), 123, Guid.NewGuid());
            var user = new User {
                Id = _msg.User, Login = "******"
            };

            using (var context = CreateContext())
            {
                context.Users.Add(user);
                context.SaveChanges();
            }

            ProjectionBuilder.Handle(_msg).Wait();
        }
コード例 #26
0
        public async Task InstallProjectionFor <TProjection>() where TProjection : IEventStoreProjection
        {
            var matchingProjections = _projections.OfType <TProjection>().ToList();

            var projectionBuilder = new ProjectionBuilder();
            var projectionManager = _eventStoreConnectionString.CreateProjectionsManager();
            var credentials       = _eventStoreConnectionString.GetUserCredentials();

            foreach (var projection in matchingProjections)
            {
                var name  = $"project-to-{projection.ProjectionName}";
                var query = projectionBuilder.BuildStreamProjection(projection.GetInterestingStreams(), projection.ProjectionName);

                await projectionManager.CreateOrUpdateContinuousQueryAsync(name, query, credentials).ConfigureAwait(false);
            }
        }
コード例 #27
0
        public async Task Given_sku_created_message_double_projected_When_project_again_additioanal_transaction_occures()
        {
            var stockCreatedEvent = new Fixture().Create <SkuStockCreated>();
            var stockAddedEvent   = new StockAdded(stockCreatedEvent.SourceId, 15, "test pack");

            await ProjectionBuilder.Handle(stockCreatedEvent);

            await ProjectionBuilder.Handle(stockAddedEvent);

            await ProjectionBuilder.Handle(stockAddedEvent);

            using (var context = CreateContext())
            {
                Assert.Equal(3, context.StockHistory.Count());
            }
        }
コード例 #28
0
        public async Task Given_sku_created_and_stock_added_and_stock_reserved_messages_When_projected()
        {
            var stockId = Guid.NewGuid();

            var stockCreatedEvent      = new SkuStockCreated(stockId, Guid.NewGuid(), 1, TimeSpan.FromDays(2));
            var stockReservedEvent     = new StockReserved(stockId, Guid.NewGuid(), DateTime.Now.AddDays(1), 7);
            var stockReserveTakenEvent = new StockReserveTaken(stockId, stockReservedEvent.ReserveId);

            await ProjectionBuilder.Handle(stockCreatedEvent);

            await ProjectionBuilder.Handle(stockReservedEvent);

            await ProjectionBuilder.Handle(stockReserveTakenEvent);

            await Assert.ThrowsAsync <ReserveEntryNotFoundException>(() => ProjectionBuilder.Handle(stockReserveTakenEvent));
        }
コード例 #29
0
        /// <summary>
        /// Busca publicações com base em uma palavra chave
        /// </summary>
        /// <param name="text">palavra chave</param>
        /// <param name="techiesId">Lista de tecnologias que a palavra chave se encaixa no nome</param>
        /// <param name="page">numero da pagina para paginação</param>
        /// <returns></returns>
        public async Task <List <Publication> > SearchPublications(string text, List <ObjectId> techiesId, int page)
        {
            var filter = FilterBuilder.Regex(a => a.Title, BsonRegularExpression.Create(new Regex(text, RegexOptions.IgnoreCase)))
                         | FilterBuilder.Regex(a => a.Description, BsonRegularExpression.Create(new Regex(text, RegexOptions.IgnoreCase)))
                         | FilterBuilder.AnyIn(a => a.Techies, techiesId)
                         & FilterBuilder.Exists(a => a.DeletedAt, false);

            var sort       = SortBuilder.Descending(a => a.DateCreation);
            var projection = ProjectionBuilder.Slice(a => a.Comments, 0, 3);

            return(await Collection
                   .Find(filter)
                   .Sort(sort)
                   .Skip((page - 1) * UtilBO.QUANTIDADE_PAGINAS)
                   .Limit(UtilBO.QUANTIDADE_PAGINAS)
                   .Project <Publication>(projection)
                   .ToListAsync());
        }
コード例 #30
0
        public async Task InstallProjectionFor <TProcessManager>() where TProcessManager : IManageProcess
        {
            var matchingProcessManagers = _processManagers.OfType <TProcessManager>().ToList();

            var projectionBuilder = new ProjectionBuilder();
            var projectionManager = _eventStoreConnectionString.CreateProjectionsManager();
            var credentials       = _eventStoreConnectionString.GetUserCredentials();

            foreach (var processManager in matchingProcessManagers)
            {
                var name  = $"project-to-{processManager.ProcessName}";
                var query = projectionBuilder.BuildStreamProjection(processManager.GetStreamsToProcess(),
                                                                    processManager.ProcessName,
                                                                    processManager.GetEventMappings().Select(x => new ProjectionBuilder.EventMap(x.Key.Name, x.Value)));

                await projectionManager.CreateOrUpdateContinuousQueryAsync(name, query, credentials).ConfigureAwait(false);
            }
        }