private void Assert <TDocument>(Expression <Func <TDocument, bool> > expression, int expectedCount, string expectedFilter)
        {
            expression = (Expression <Func <TDocument, bool> >)PartialEvaluator.EvaluatePartially(expression);

            var parameter  = expression.Parameters.Single();
            var serializer = BsonSerializer.LookupSerializer <TDocument>();
            var context    = TranslationContext.Create(expression, serializer);
            var symbol     = context.CreateSymbol(parameter, serializer, isCurrent: true);

            context = context.WithSymbol(symbol);
            var filterAst      = ExpressionToFilterTranslator.Translate(context, expression.Body);
            var renderedFilter = (BsonDocument)filterAst.Render();

            renderedFilter.Should().Be(expectedFilter);

            var filter = new BsonDocumentFilterDefinition <C>(renderedFilter);
            var list   = __collection.FindSync <TDocument>(filter).ToList();

            list.Count.Should().Be(expectedCount);
        }
예제 #2
0
        public List <TDocument> Assert <TDocument>(IMongoCollection <TDocument> collection, Expression <Func <TDocument, bool> > filter, int expectedCount, BsonDocument expectedFilter)
        {
            filter = (Expression <Func <TDocument, bool> >)PartialEvaluator.EvaluatePartially(filter);

            var serializer = BsonSerializer.SerializerRegistry.GetSerializer <TDocument>();
            var parameter  = filter.Parameters.Single();
            var context    = TranslationContext.Create(filter, serializer);
            var symbol     = context.CreateSymbol(parameter, serializer, isCurrent: true);

            context = context.WithSymbol(symbol);
            var filterAst      = ExpressionToFilterTranslator.Translate(context, filter.Body);
            var filterDocument = (BsonDocument)filterAst.Render();

            filterDocument.Should().Be(expectedFilter);

            var list = collection.FindSync(filterDocument).ToList();

            list.Count.Should().Be(expectedCount);
            return(list);
        }
예제 #3
0
        /// <inheritdoc />
        public override RenderedFieldDefinition Render(IBsonSerializer <TDocument> documentSerializer, IBsonSerializerRegistry serializerRegistry)
        {
            var bindingContext      = new PipelineBindingContext(serializerRegistry);
            var lambda              = ExpressionHelper.GetLambda(PartialEvaluator.Evaluate(_expression));
            var parameterExpression = new DocumentExpression(documentSerializer);

            bindingContext.AddExpressionMapping(lambda.Parameters[0], parameterExpression);
            var bound = bindingContext.Bind(lambda.Body);

            bound = FieldExpressionFlattener.FlattenFields(bound);
            IFieldExpression field;

            if (!ExpressionHelper.TryGetExpression(bound, out field))
            {
                var message = string.Format("Unable to determine the serialization information for {0}.", _expression);
                throw new InvalidOperationException(message);
            }

            return(new RenderedFieldDefinition(field.FieldName, field.Serializer));
        }
예제 #4
0
        public TranslateResult Translate(Expression expression)
        {
            expression = PartialEvaluator.Eval(expression);
            ProjectionExpression project = expression as ProjectionExpression;

            if (project == null)
            {
                expression = new QueryBinder().Bind(expression);
                expression = OrderByRewriter.Rewrite(expression);
                project    = expression as ProjectionExpression;
            }
            string commandText = new QueryFormatter().FormatExpression(project.Source);

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

            return(new TranslateResult()
            {
                CommandText = commandText, Projector = projector
            });
        }
예제 #5
0
        private LambdaExpression Parameterize(Expression query, out object[] arguments)
        {
            IQueryProvider provider = this.FindProvider(query);

            if (provider == null)
            {
                throw new ArgumentException(Res.ArgumentQuery);
            }

            var ep = provider as IDbContext;

            // turn all relatively constant expression into actual constants
            Func <Expression, bool> fnCanBeEvaluated = e => ep != null?ExpressionHelper.CanBeEvaluatedLocally(e) : true;

            var body = PartialEvaluator.Eval(query, fnCanBeEvaluated);

            // convert all constants into parameters
            List <ParameterExpression> parameters;
            List <object> values;

            body = Parameterizer.Parameterize(body, out parameters, out values);

            // make sure the body will return a value typed as 'object'.
            if (body.Type != typeof(object))
            {
                body = Expression.Convert(body, typeof(object));
            }

            // make a lambda expression with these parameters
            arguments = values.ToArray();
            if (arguments.Length < 5)
            {
                return(Expression.Lambda(body, parameters.ToArray()));
            }
            else
            {
                // too many parameters, use an object array instead.
                arguments = new object[] { arguments };
                return(ExplicitToObjectArray.Rewrite(body, parameters));
            }
        }
예제 #6
0
        /// <summary>
        /// 对表达式进行解析,并返回限制值字典。
        /// </summary>
        /// <param name="expression">查询表达式。</param>
        /// <param name="dicRestrMbrs"></param>
        /// <returns></returns>
        public static RestrictionDictionary GetRestrictions <T>(Expression expression, Dictionary <Type, List <MemberInfo> > dicRestrMbrs)
        {
            if (expression == null)
            {
                return(RestrictionDictionary.Empty);
            }

            var translator = new SchemaQueryTranslator {
                _metadataType = typeof(T)
            };

            if (!dicRestrMbrs.TryGetValue(typeof(T), out List <MemberInfo> properties))
            {
                throw new SchemaQueryTranslateException(typeof(T));
            }

            translator._members = properties;
            expression          = PartialEvaluator.Eval(expression);
            translator.Visit(expression);
            return(translator._restrDict);
        }
예제 #7
0
        /// <summary>
        /// 通过一个 <see cref="MemberInitExpression"/> 表达式将属性值绑定到实体对象中。
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="factory"></param>
        /// <returns></returns>
        public static IEntity InitByExpression(this IEntity entity, LambdaExpression factory)
        {
            if (factory.Body is MemberInitExpression initExp)
            {
                foreach (var bind in initExp.Bindings)
                {
                    if (bind as MemberAssignment == null)
                    {
                        continue;
                    }

                    var exp = PartialEvaluator.Eval((bind as MemberAssignment).Expression);
                    if (exp is ConstantExpression constExp)
                    {
                        entity.SetValue((bind as MemberAssignment).Member.Name, PropertyValue.NewValue(constExp.Value, (bind as MemberAssignment).Member.GetMemberType()));
                    }
                }
            }

            return(entity);
        }
예제 #8
0
        public static RenderedProjectionDefinition <TProjection> Translate <TDocument, TProjection>(Expression <Func <TDocument, TProjection> > projector, IBsonSerializer <TDocument> parameterSerializer)
        {
            var parameterSerializationInfo = new BsonSerializationInfo(null, parameterSerializer, parameterSerializer.ValueType);
            var parameterExpression        = new SerializationExpression(projector.Parameters[0], parameterSerializationInfo);
            var binder = new SerializationInfoBinder(BsonSerializer.SerializerRegistry);

            binder.RegisterParameterReplacement(projector.Parameters[0], parameterExpression);
            var normalizedBody  = Normalizer.Normalize(projector.Body);
            var evaluatedBody   = PartialEvaluator.Evaluate(normalizedBody);
            var boundExpression = binder.Bind(evaluatedBody);
            var candidateFields = FieldGatherer.Gather(boundExpression);

            var fields = GetUniqueFieldsByHierarchy(candidateFields);

            var serializationInfo = fields.Select(x => x.SerializationInfo).ToList();

            var replacementParameter = Expression.Parameter(typeof(ProjectedObject), "document");

            var translator   = new FindProjectionTranslator(projector.Parameters[0], replacementParameter, fields);
            var newProjector = Expression.Lambda <Func <ProjectedObject, TProjection> >(
                translator.Visit(boundExpression),
                replacementParameter);

            BsonDocument projectionDocument;
            IBsonSerializer <TProjection> serializer;

            if (translator._fullDocument)
            {
                projectionDocument = null;
                serializer         = new ProjectingDeserializer <TDocument, TProjection>(parameterSerializer, projector.Compile());
            }
            else
            {
                projectionDocument = GetProjectionDocument(serializationInfo);
                var projectedObjectSerializer = new ProjectedObjectDeserializer(serializationInfo);
                serializer = new ProjectingDeserializer <ProjectedObject, TProjection>(projectedObjectSerializer, newProjector.Compile());
            }

            return(new RenderedProjectionDefinition <TProjection>(projectionDocument, serializer));
        }
        protected override Expression VisitSelect(SelectExpression select)
        {
            // select * from table order by x skip s take t
            // =>
            // select * from (select top s * from (select top s + t from table order by x) order by -x) order by x

            select = (SelectExpression)base.VisitSelect(select);

            if (select.Skip != null && select.Take != null && select.OrderBy.Count > 0)
            {
                var skip         = select.Skip;
                var take         = select.Take;
                var skipPlusTake = PartialEvaluator.Eval(Expression.Add(skip, take));

                select = select.SetTake(skipPlusTake).SetSkip(null);
                select = select.AddRedundantSelect(this.language, new TableAlias());
                select = select.SetTake(take);

                // propogate order-bys to new layer
                select = (SelectExpression)OrderByRewriter.Rewrite(this.language, select);
                var inverted = select.OrderBy.Select(ob => new OrderExpression(
                                                         ob.OrderType == OrderType.Ascending ? OrderType.Descending : OrderType.Ascending,
                                                         ob.Expression
                                                         ));
                select = select.SetOrderBy(inverted);

                select = select.AddRedundantSelect(this.language, new TableAlias());
                select = select.SetTake(Expression.Constant(0)); // temporary
                select = (SelectExpression)OrderByRewriter.Rewrite(this.language, select);
                var reverted = select.OrderBy.Select(ob => new OrderExpression(
                                                         ob.OrderType == OrderType.Ascending ? OrderType.Descending : OrderType.Ascending,
                                                         ob.Expression
                                                         ));
                select = select.SetOrderBy(reverted);
                select = select.SetTake(null);
            }

            return(select);
        }
예제 #10
0
            //重写projectrow 中的ExecuteSubQuery  方法
            public override IEnumerable <E> ExcuteSubQuery <E>(LambdaExpression query)
            {
                //干什么用的??
                // 将查询主体 替换为 查询参数
                //
                // Replace 参数 在query.Body 中搜索 query.parameter ,并用 Expression.Constant(this) 替换
                ProjectionExpression projection = (ProjectionExpression) new DbExpressionReplacer().
                                                  Replace(query.Body, query.Parameters[0], Expression.Constant(this));

                //计算 本地表达式,去除本地引用
                projection = PartialEvaluator.Eval(projection, CanEvaluateLocally) as ProjectionExpression;
                //执行查询
                IEnumerable <E> result = (IEnumerable <E>) this.provider.Execute(projection);
                List <E>        list   = new List <E>(result);

                // 如果是 IQueryable 类型,直接返回
                if (typeof(IQueryable <E>).IsAssignableFrom(query.Body.Type))
                {
                    return(list.AsQueryable());
                }
                return(list);
            }
        protected override Expression VisitProjection(DbProjectionExpression proj)
        {
            // select * from table order by x skip s take t
            // =>
            // select * from (select top s * from (select top s + t from table order by x) order by -x) order by x

            if (proj.Select.Skip != null && proj.Select.Take != null && proj.Select.OrderBy.Count > 0)
            {
                var skip         = proj.Select.Skip;
                var take         = proj.Select.Take;
                var select       = proj.Select;
                var skipPlusTake = PartialEvaluator.Eval(Expression.Add(skip, take));

                select = proj.Select.SetTake(skipPlusTake).SetSkip(null);
                select = select.AddRedundantSelect(new DbTableAlias());
                select = select.SetTake(take);

                // propogate order-bys to new layer
                select = (DbSelectExpression)OrderByRewriter.Rewrite(select);
                var inverted = select.OrderBy.Select(ob => new DbOrderExpression(
                                                         ob.OrderType == DbOrderType.Ascending ? DbOrderType.Descending : DbOrderType.Ascending,
                                                         ob.Expression
                                                         ));
                select = select.SetOrderBy(inverted);

                select = select.AddRedundantSelect(new DbTableAlias());
                select = select.SetTake(Expression.Constant(0)); // temporary
                select = (DbSelectExpression)OrderByRewriter.Rewrite(select);
                var reverted = select.OrderBy.Select(ob => new DbOrderExpression(
                                                         ob.OrderType == DbOrderType.Ascending ? DbOrderType.Descending : DbOrderType.Ascending,
                                                         ob.Expression
                                                         ));
                select = select.SetOrderBy(reverted);
                select = select.SetTake(null);

                return(new DbProjectionExpression(select, proj.Projector, proj.Aggregator));
            }
            return(proj);
        }
예제 #12
0
            public override Expression ApplyPolicy(Expression expression, MemberInfo member)
            {
                List <LambdaExpression> ops;

                if (this.policy.operations.TryGetValue(member, out ops))
                {
                    var result = expression;
                    foreach (var fnOp in ops)
                    {
                        var pop = PartialEvaluator.Eval(fnOp, this.Translator.Mapper.Mapping.CanBeEvaluatedLocally);
                        result = this.Translator.Mapper.ApplyMapping(Expression.Invoke(pop, result));
                    }
                    var projection = (ProjectionExpression)result;
                    if (projection.Type != expression.Type)
                    {
                        var fnAgg = Aggregator.GetAggregator(expression.Type, projection.Type);
                        projection = new ProjectionExpression(projection.Select, projection.Projector, fnAgg);
                    }
                    return(projection);
                }
                return(expression);
            }
예제 #13
0
        internal Expression ApplyPolicy(Expression expression, MemberInfo member)
        {
            List <LambdaExpression> ops;

            if (Operations.TryGetValue(member, out ops))
            {
                var result = expression;
                foreach (var fnOp in ops)
                {
                    var pop = PartialEvaluator.Eval(fnOp, ExpressionHelper.CanBeEvaluatedLocally);
                    result = QueryBinder.Bind(ExpressionBuilder, this, Expression.Invoke(pop, result));
                }
                var projection = (ProjectionExpression)result;
                if (projection.Type != expression.Type)
                {
                    var fnAgg = Aggregator.GetAggregator(expression.Type, projection.Type);
                    projection = new ProjectionExpression(projection.Select, projection.Projector, fnAgg);
                }
                return(projection);
            }
            return(expression);
        }
        public void Setup()
        {
            Func <int, Expression <Func <int, int, int> > > builder;

            switch (ExpressionType)
            {
            case ExpressionTypes.Simple:
                builder = buildSimpleExpression;
                break;

            case ExpressionTypes.Complex:
                builder = buildComplexExpression;
                break;

            default:
                throw new NotSupportedException(ExpressionType.ToString());
            }

            expression           = PartialEvaluator.PartialEvalBody(builder(5), ExpressionInterpreter.Instance);
            similarExpression    = PartialEvaluator.PartialEvalBody(builder(5), ExpressionInterpreter.Instance);
            nonSimilarExpression = PartialEvaluator.PartialEvalBody(builder(42), ExpressionInterpreter.Instance);
        }
예제 #15
0
            internal void Compile(params object[] args)
            {
                if (this.fnQuery == null)
                {
                    // first identify the query provider being used
                    Expression         replaced = null;
                    Expression         body     = this.query.Body;
                    ConstantExpression root     = RootQueryableFinder.Find(body) as ConstantExpression;
                    if (root == null && args != null && args.Length > 0)
                    {
                        replaced = ExpressionReplacer.ReplaceAll(
                            this.query,
                            this.query.Parameters.ToArray(),
                            args.Select((a, i) => Expression.Constant(a, this.query.Parameters[i].Type)).ToArray()
                            );
                        body = PartialEvaluator.Eval(replaced);
                        root = RootQueryableFinder.Find(body) as ConstantExpression;
                    }
                    if (root == null)
                    {
                        throw new InvalidOperationException("Could not find query provider");
                    }
                    // ask the query provider to compile the query by 'executing' the lambda expression
                    IQueryProvider provider = ((IQueryable)root.Value).Provider;
                    Delegate       result   = null;

                    if (replaced != null)
                    {
                        result = (Delegate)provider.Execute(replaced);
                    }
                    else
                    {
                        result = (Delegate)provider.Execute(this.query);
                    }

                    System.Threading.Interlocked.CompareExchange(ref this.fnQuery, result, null);
                }
            }
예제 #16
0
 protected override Expression VisitSelect(SelectExpression selectExpression)
 {
     selectExpression = (SelectExpression)base.VisitSelect(selectExpression);
     if (((selectExpression.Skip != null) && (selectExpression.Take != null)) && (selectExpression.OrderBy.Count > 0))
     {
         Expression skip        = selectExpression.Skip;
         Expression take        = selectExpression.Take;
         Expression expression3 = PartialEvaluator.Eval(Expression.Add(skip, take));
         selectExpression = selectExpression.SetTake(expression3).SetSkip(null);
         selectExpression = selectExpression.AddRedundantSelect(this.language, new TableAlias());
         selectExpression = selectExpression.SetTake(take);
         selectExpression = (SelectExpression)OrderByRewriter.Rewrite(this.language, selectExpression);
         IEnumerable <OrderExpression> orderBy = from ob in selectExpression.OrderBy select new OrderExpression((ob.OrderType == OrderType.Ascending) ? OrderType.Descending : OrderType.Ascending, ob.Expression);
         selectExpression = selectExpression.SetOrderBy(orderBy);
         selectExpression = selectExpression.AddRedundantSelect(this.language, new TableAlias());
         selectExpression = selectExpression.SetTake(Expression.Constant(0));
         selectExpression = (SelectExpression)OrderByRewriter.Rewrite(this.language, selectExpression);
         IEnumerable <OrderExpression> enumerable2 = from ob in selectExpression.OrderBy select new OrderExpression((ob.OrderType == OrderType.Ascending) ? OrderType.Descending : OrderType.Ascending, ob.Expression);
         selectExpression = selectExpression.SetOrderBy(enumerable2);
         selectExpression = selectExpression.SetTake(null);
     }
     return(selectExpression);
 }
        /// <summary>
        /// 通过表达式计算出对应的缓存键。
        /// </summary>
        /// <param name="expression">作为 Key 的 Lambda 表达式。</param>
        /// <param name="prefix">用于区分缓存的前缀。</param>
        /// <returns></returns>
        public string Generate(Expression expression, params string[] prefix)
        {
            var evalExp  = PartialEvaluator.Eval(expression, TranslateProviderBase.EvaluatedLocallyFunc);
            var cacheKey = ExpressionWriter.WriteToString(evalExp);

            //使用md5进行hash编码
            var md5  = new MD5CryptoServiceProvider();
            var data = md5.ComputeHash(Encoding.Unicode.GetBytes(cacheKey));

            var sb = new StringBuilder();

            foreach (var p in prefix)
            {
                if (!string.IsNullOrEmpty(p))
                {
                    sb.AppendFormat("{0}:", p);
                }
            }

            sb.Append(data.ToHex(true));

            return(sb.ToString());
        }
예제 #18
0
            public override Expression ApplyPolicy(Expression expression, MemberInfo member)
            {
                List <LambdaExpression> list;

                if (this.policy.operations.TryGetValue(member, out list))
                {
                    Expression expression2 = expression;
                    foreach (LambdaExpression expression3 in list)
                    {
                        QueryMapping mapping     = base.Translator.Mapper.Mapping;
                        Expression   expression4 = PartialEvaluator.Eval(expression3, new Func <Expression, bool>(mapping.CanBeEvaluatedLocally));
                        expression2 = base.Translator.Mapper.ApplyMapping(Expression.Invoke(expression4, new Expression[] { expression2 }));
                    }
                    ProjectionExpression expression5 = (ProjectionExpression)expression2;
                    if (expression5.Type != expression.Type)
                    {
                        LambdaExpression aggregator = Aggregator.GetAggregator(expression.Type, expression5.Type);
                        expression5 = new ProjectionExpression(expression5.Select, expression5.Projector, aggregator);
                    }
                    return(expression5);
                }
                return(expression);
            }
예제 #19
0
            internal IQueryProvider FindProvider(Expression expression, object[] args)
            {
                Expression root = this.FindProviderInExpression(expression) as ConstantExpression;

                if (root == null && args != null && args.Length > 0)
                {
                    Expression replaced = ExpressionReplacer.ReplaceAll(
                        expression,
                        this.query.Parameters.ToArray(),
                        args.Select((a, i) => Expression.Constant(a, this.query.Parameters[i].Type)).ToArray()
                        );
                    root = this.FindProviderInExpression(replaced);
                }
                if (root != null)
                {
                    ConstantExpression cex = root as ConstantExpression;
                    if (cex == null)
                    {
                        cex = PartialEvaluator.Eval(root) as ConstantExpression;
                    }
                    if (cex != null)
                    {
                        IQueryProvider provider = cex.Value as IQueryProvider;
                        if (provider == null)
                        {
                            IQueryable query = cex.Value as IQueryable;
                            if (query != null)
                            {
                                provider = query.Provider;
                            }
                        }
                        return(provider);
                    }
                }
                return(null);
            }
예제 #20
0
        public Expression ApplyPolicy(Expression expression, MemberInfo member, Func <Expression, Expression> builder)
        {
            if (_operations.TryGetValue(member, out List <LambdaExpression> ops))
            {
                var syntax = _provider.GetService <ISyntaxProvider>();
                var result = expression;
                foreach (var fnOp in ops)
                {
                    var pop = PartialEvaluator.Eval(fnOp);
                    result = builder(Expression.Invoke(pop, result));
                }

                var projection = (ProjectionExpression)result;
                if (projection.Type != expression.Type)
                {
                    var fnAgg = QueryUtility.GetAggregator(expression.Type, projection.Type);
                    projection = new ProjectionExpression(projection.Select, projection.Projector, fnAgg, projection.IsAsync, projection.IsNoTracking);
                }

                return(projection);
            }

            return(expression);
        }
예제 #21
0
            protected override MemberBinding VisitBinding(MemberBinding binding)
            {
                var assign = binding as MemberAssignment;

                if (assign == null)
                {
                    return(binding);
                }

                var propertyName = assign.Member.Name;
                var property     = PropertyUnity.GetProperty(typeof(TEntity), propertyName);

                if (property != null)
                {
                    if (condition.Length > 0)
                    {
                        condition.Append(" AND ");
                    }

                    var constExp = PartialEvaluator.Eval(assign.Expression) as ConstantExpression;
                    if (constExp.Type.IsStringOrDateTime())
                    {
                        condition.AppendFormat("{0} = '{1}'", property.Info.FieldName, constExp.Value);
                    }
                    else if (constExp.Type.IsEnum)
                    {
                        condition.AppendFormat("{0} = {1}", property.Info.FieldName, (int)constExp.Value);
                    }
                    else
                    {
                        condition.AppendFormat("{0} = {1}", property.Info.FieldName, constExp.Value);
                    }
                }

                return(binding);
            }
예제 #22
0
        Expression IQueryPolicy.ApplyPolicy(Expression expression, MemberInfo member)
        {
            if (operations.TryGetValue(member, out List <LambdaExpression> ops))
            {
                var syntax = Database.Provider.GetService <ISyntaxProvider>();
                var result = expression;
                foreach (var fnOp in ops)
                {
                    var pop = PartialEvaluator.Eval(fnOp);
                    result = QueryBinder.Bind(Expression.Invoke(pop, result), syntax);
                }

                var projection = (ProjectionExpression)result;
                if (projection.Type != expression.Type)
                {
                    var fnAgg = QueryUtility.GetAggregator(expression.Type, projection.Type);
                    projection = new ProjectionExpression(projection.Select, projection.Projector, fnAgg);
                }

                return(projection);
            }

            return(expression);
        }
예제 #23
0
 /// <summary>
 /// 对 ELinq 表达式进行翻译,并返回翻译的结果。
 /// </summary>
 /// <param name="expression">一个 ELinq 表达式。</param>
 /// <param name="options">翻译的选项。</param>
 /// <returns></returns>
 public virtual Expression Translate(Expression expression, TranslateOptions options = null)
 {
     expression = PartialEvaluator.Eval(expression, CanBeEvaluatedLocally);
     return(TranslateInternal(expression, options));
 }
예제 #24
0
 /// <summary>
 /// 对 ELinq 表达式进行翻译,并返回翻译的结果。
 /// </summary>
 /// <param name="expression">一个 ELinq 表达式。</param>
 /// <returns></returns>
 public virtual Expression Translate(Expression expression)
 {
     expression = PartialEvaluator.Eval(expression, CanBeEvaluatedLocally);
     return(TranslateInternal(expression));
 }
        public void InterpreterToCompiler()
        {
            var r = PartialEvaluator.PartialEvaluate <Expression <Func <int, int> >, int, int>((f, i) => f.Compile()(i), i => i * 100);

            Assert.That(r.Compile()(20), Is.EqualTo(2000));
        }
        // public methods
        /// <summary>
        /// Gets the serialization info for the given expression.
        /// </summary>
        /// <param name="node">The expression.</param>
        /// <returns>The serialization info.</returns>
        public BsonSerializationInfo GetSerializationInfo(Expression node)
        {
            var evaluatedNode = PartialEvaluator.Evaluate(node);

            return(BsonSerializationInfoFinder.GetSerializationInfo(evaluatedNode, _serializationInfoCache));
        }
예제 #27
0
        public object Execute(Expression expression)
        {
            var visitor = new SalesforceVisitor(NamingConvention, SelectType);
            var cmd     = visitor.Translate(PartialEvaluator.Eval(expression));

            switch (visitor.QueryType)
            {
            case QueryTypeEnum.FirstOrDefault:
                return(ProduceAsyncEnumerable(cmd).FirstOrDefault());

            case QueryTypeEnum.First:
                return(ProduceAsyncEnumerable(cmd).First());

            case QueryTypeEnum.Single:
                return(ProduceAsyncEnumerable(cmd).Single());

            case QueryTypeEnum.SingleOrDefault:
                return(ProduceAsyncEnumerable(cmd).SingleOrDefault());

            case QueryTypeEnum.Count:
                return(ProduceCountAsync(cmd));

            case QueryTypeEnum.Any:
                return(ProduceCountAsync(cmd).ContinueWith(task => task.Result > 0));

            case QueryTypeEnum.List:
                return(ProduceAsyncEnumerable(cmd).ToList());

//                    var argument = typeof(TResult).GetGenericArguments()[0];
//
//                    var method = GetType().GetMethod("ProduceAsyncEnumerable", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(argument);
//                    var asyncEnumerable = method.Invoke(this, new object[]{cmd});
//
//
//                    var enumerabletype = typeof(IAsyncEnumerable<>).MakeGenericType(argument);
//                    var toList = GetGenericMethod(typeof(AsyncEnumerable), "ToList", typeof(IAsyncEnumerable<>)).MakeGenericMethod(argument);
//
//                    var result = (Task<TResult>) toList.Invoke(null, new [] {asyncEnumerable});
//
//                    MethodInfo GetGenericMethod(Type type, string name, params Type[] argumentTypes)
//                    {
//                        var methods = type.GetTypeInfo().GetMember("ToList").OfType<MethodInfo>().ToList();
//
//                        return methods.FirstOrDefault(m =>
//                        {
//                            var parameters = m.GetParameters();
//
//                            if (parameters.Length != argumentTypes.Length)
//                                return false;
//
//                            for (var i = 0; i < parameters.Length; i++)
//                            {
//                                var parameterType = parameters[i].ParameterType;
//
//                                if (parameterType.IsGenericType)
//                                    parameterType = parameterType.GetGenericTypeDefinition();
//
//                                if (parameterType != argumentTypes[i])
//                                    return false;
//                            }
//
//                            return true;
//                        });
//                    }

            case QueryTypeEnum.Enumerator:
            default:
                return(Task.FromResult(ProduceAsyncEnumerator(cmd)));
            }
        }
예제 #28
0
        public string ToString(Expression expression)
        {
            var visitor = new SalesforceVisitor(NamingConvention, SelectType);

            return(visitor.Translate(PartialEvaluator.Eval(expression)));
        }
 public void StaticReadonlyClosurePartialEvaluation()
 {
     PartialEvaluator.PartialEvalBody(staticReadonlyClosureExpression, MiaPlaza.ExpressionUtils.Evaluating.ExpressionInterpreter.Instance);
 }
        /// <summary>
        /// Tries the get serialization information.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="serializationInfo">The serialization information.</param>
        /// <returns></returns>
        public bool TryGetSerializationInfo(Expression node, out BsonSerializationInfo serializationInfo)
        {
            var evaluatedNode = PartialEvaluator.Evaluate(node);

            return(BsonSerializationInfoFinder.TryGetSerializationInfo(evaluatedNode, _serializationInfoCache, out serializationInfo));
        }