Exemple #1
0
        public void CombineWithOtherCustomMappings(CustomMapping root, IEnumerable <CustomMapping> mappings)
        {
            lock (root)
            {
                foreach (var otherMapping in mappings)
                {
                    foreach (var m in otherMapping.Members)
                    {
                        if (!root.Members.Contains(m))
                        {
                            var oldParams = otherMapping.ArgumentParameters.Select(p => p.Parameter).ToList();
                            var newParams = root.ArgumentParameters.Select(p => p.Parameter).ToList();

                            oldParams.Add(otherMapping.SourceParameter);
                            newParams.Add(root.SourceParameter);

                            var visitor = new ParameterVisitor(oldParams, newParams);

                            var member = new MemberExpressionTuple
                            {
                                Expression = visitor.Visit(m.Expression),
                                Member     = m.Member
                            };

                            root.Members.Add(member);
                        }
                    }
                }
            }
        }
Exemple #2
0
        public override IAsyncEnumerable <Object> Execute(Object dataContext, OeQueryContext queryContext)
        {
            Expression           expression;
            MethodCallExpression countExpression = null;
            IQueryable           entitySet       = queryContext.EntitySetAdapter.GetEntitySet(dataContext);

            if (base.QueryCache.AllowCache)
            {
                expression = GetFromCache(queryContext, (T)dataContext, base.QueryCache, out countExpression);
            }
            else
            {
                expression = queryContext.CreateExpression(new OeConstantToVariableVisitor());
                expression = queryContext.TranslateSource(dataContext, expression);
                expression = new ParameterVisitor().Visit(expression);

                if (queryContext.IsQueryCount())
                {
                    countExpression = queryContext.CreateCountExpression(expression);
                }
            }

            IQueryable <Object>       query           = (IQueryable <Object>)entitySet.Provider.CreateQuery(expression);
            IAsyncEnumerable <Object> asyncEnumerator = Infrastructure.AsyncEnumeratorHelper.ToAsyncEnumerable(query);

            if (countExpression != null)
            {
                queryContext.TotalCountOfItems = entitySet.Provider.Execute <int>(countExpression);
            }

            return(asyncEnumerator);
        }
 private static Expression MakeLambda(Expression parameter, Expression predicate)
 {
     var resultParameterVisitor = new ParameterVisitor();
     resultParameterVisitor.Visit(parameter);
     var resultParameter = resultParameterVisitor.Parameter;
     return Expression.Lambda(predicate, (ParameterExpression)resultParameter);
 }
        /// <summary> Expression building </summary>
        private static Expression <Func <T, Boolean> > Create <T>(this Expression body, params ParameterExpression[] oldParams)
        {
            var parameter  = Expression.Parameter(typeof(T));
            var expression = new ParameterVisitor(parameter, oldParams).Visit(body);

            return(Expression.Lambda <Func <T, Boolean> >(expression, parameter));
        }
        private static Expression CreateAnyAllExpression(
            Expression left,
            Expression right,
            ParameterExpression sourceParameter,
            IEnumerable <ParameterExpression> lambdaParameters,
            MethodInfo anyAllMethod)
        {
            var genericFunc = typeof(Func <,>)
                              .MakeGenericType(
                MethodProvider.GetIEnumerableImpl(left.Type).GetGenericArguments()[0],
                typeof(bool));

            var filteredParameters = new ParameterVisitor()
                                     .GetParameters(right)
                                     .Where(p => p.Name != sourceParameter.Name)
                                     .ToArray();

            if (!filteredParameters.Any())
            {
                filteredParameters = lambdaParameters.ToArray();
            }

            return(Expression.Call(
                       anyAllMethod,
                       left,
                       Expression.Lambda(genericFunc, right, filteredParameters)));
        }
        public override Db.OeAsyncEnumerator ExecuteEnumerator(Object dataContext, OeQueryContext queryContext, CancellationToken cancellationToken)
        {
            Expression           expression;
            MethodCallExpression countExpression = null;
            IQueryable           entitySet       = queryContext.EntitySetAdapter.GetEntitySet(dataContext);

            if (base.QueryCache.AllowCache)
            {
                expression = GetFromCache(queryContext, (T)dataContext, base.QueryCache, out countExpression);
            }
            else
            {
                expression = queryContext.CreateExpression(new OeConstantToVariableVisitor());
                expression = queryContext.TranslateSource(dataContext, expression);
                expression = new ParameterVisitor().Visit(expression);

                if (queryContext.ODataUri.QueryCount.GetValueOrDefault())
                {
                    countExpression = OeQueryContext.CreateCountExpression(expression);
                }
            }

            IQueryable <Object> query = (IQueryable <Object>)entitySet.Provider.CreateQuery(expression);

            Db.OeAsyncEnumerator asyncEnumerator = new Db.OeAsyncEnumeratorAdapter(query, cancellationToken);

            if (countExpression != null)
            {
                asyncEnumerator.Count = entitySet.Provider.Execute <int>(countExpression);
            }

            return(asyncEnumerator);
        }
Exemple #7
0
    public static IEnumerable <string> GetParameters(this ParseResult p)
    {
        var pv = new ParameterVisitor();

        p.Script.Accept(pv);
        return(pv.Parameters);
    }
Exemple #8
0
        /// <summary>
        /// 编织扩展
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        internal Expression <Func <TEntity, T> > Expand <T>(Expression <Func <TEntity, T> > source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            var adjuster            = new ParameterVisitor(node => source.Parameters.Single());
            var adjustedExpandables =
                from expandable in _expandables
                select new
            {
                From = expandable.From(),
                To   = (adjuster.Visit(expandable.To()))
            };

            var propertyReplacer = new MemberVisitor(node =>
            {
                var query =
                    from expandable in adjustedExpandables
                    where (expandable.From == node.Member)
                    select expandable.To;
                return(query.SingleOrDefault() ?? node);
            });

            return((Expression <Func <TEntity, T> >)propertyReplacer.Visit(source));
        }
        public static bool HasParameterExpression(this Expression self)
        {
            var constantVisitor = new ParameterVisitor();

            constantVisitor.Visit(self);

            return(constantVisitor.HasParameterExpression);
        }
        public Expression Process(Expression expression)
        {
            var paramVisitor = new ParameterVisitor(this.ParametersToReplace);

              expression = paramVisitor.Visit(expression);

              return expression;
        }
Exemple #11
0
        public Expression Process(Expression expression)
        {
            var paramVisitor = new ParameterVisitor(this.ParametersToReplace);

            expression = paramVisitor.Visit(expression);

            return(expression);
        }
Exemple #12
0
        public override TResult ExecuteScalar <TResult>(Object dataContext, OeParseUriContext parseUriContext)
        {
            IQueryable query      = parseUriContext.EntitySetAdapter.GetEntitySet(dataContext);
            Expression expression = parseUriContext.CreateExpression(query, new OeConstantToVariableVisitor());

            expression = new ParameterVisitor().Visit(expression);
            return(query.Provider.Execute <TResult>(expression));
        }
Exemple #13
0
        private static Expression <Func <T, bool> > MakeLambda <T>(Expression parameter, Expression predicate)
        {
            var resultParameterVisitor = new ParameterVisitor();

            resultParameterVisitor.Visit(parameter);
            var resultParameter = resultParameterVisitor.Parameter;

            return(Expression.Lambda <Func <T, bool> >(predicate, (ParameterExpression)resultParameter));
        }
        public override Expression Translate(ExpandedNavigationSelectItem item)
        {
            var        segment            = (NavigationPropertySegment)item.PathToNavigationProperty.LastSegment;
            Expression expression         = Translate(segment);
            Type       navigationItemType = expression.Type;

            Type itemType = OeExpressionHelper.GetCollectionItemType(navigationItemType);

            if (itemType != null)
            {
                var expressionBuilder = new OeExpressionBuilder(_model, itemType);
                expression = expressionBuilder.ApplyFilter(expression, item.FilterOption);
                expression = expressionBuilder.ApplyOrderBy(expression, item.OrderByOption);

                var path = new ODataPath(_path.Union(item.PathToNavigationProperty));
                expression = expressionBuilder.ApplySkip(expression, item.SkipOption, path);
                expression = expressionBuilder.ApplyTake(expression, item.TopOption, path);

                foreach (KeyValuePair <ConstantExpression, ConstantNode> constant in expressionBuilder.Constants)
                {
                    _visitor.AddConstant(constant.Key, constant.Value);
                }
            }

            Expression countExpression = null;

            if (item.CountOption.GetValueOrDefault())
            {
                MethodInfo countMethodInfo = OeMethodInfoHelper.GetCountMethodInfo(itemType);
                countExpression = Expression.Call(countMethodInfo, expression);
            }

            if (item.SelectAndExpand.SelectedItems.Any())
            {
                var        path             = new ODataPath(_path.Union(item.PathToNavigationProperty));
                var        selectTranslator = new OeSelectTranslator(_visitor, path);
                Expression nestedExpression = selectTranslator.CreateExpression(expression, item.SelectAndExpand, OeMetadataLevel.Minimal);

                Type nestedType = OeExpressionHelper.GetCollectionItemType(nestedExpression.Type);
                if (nestedType == null)
                {
                    var visitor = new ParameterVisitor(selectTranslator._parameter, expression);
                    nestedExpression = visitor.Visit(nestedExpression);
                    nestedType       = nestedExpression.Type;
                }

                _selectItemInfo.EntryFactory = selectTranslator.CreateNestedEntryFactory(nestedType, _selectItemInfo.EntitySet, _selectItemInfo.ResourceInfo);
                expression = nestedExpression;
            }

            if (countExpression != null)
            {
                return(CreateNavigationLinkInfo(navigationItemType, expression, countExpression));
            }

            return(expression);
        }
Exemple #15
0
        public static ParameterExpression GetParamaterFromExpression(Expression parameter)
        {
            var resultParameterVisitor = new ParameterVisitor();

            resultParameterVisitor.Visit(parameter);
            var resultParameter = resultParameterVisitor.Parameter as ParameterExpression;

            return(resultParameter);
        }
    public static Expression <Func <TResult, bool> > WithParameter <TResult, TSource>(this Expression <Func <TSource, bool> > source, Expression <Func <TResult, TSource> > selector)
    {
        // Replace parameter with body of selector
        var replaceParameter = new ParameterVisitor(source.Parameters, selector.Body);
        // This will be the new body of the expression
        var newExpressionBody = replaceParameter.Visit(source.Body);

        return(Expression.Lambda <Func <TResult, bool> >(newExpressionBody, selector.Parameters));
    }
        private static Expression <T> Compose <T>(
            this Expression <T> first,
            Expression <T> second,
            Func <Expression, Expression, Expression> merge)
        {
            var visitor    = new ParameterVisitor(first.Parameters);
            var expression = merge(visitor.Visit(first.Body) !, visitor.Visit(second.Body) !);

            return(Expression.Lambda <T>(expression, first.Parameters));
        }
Exemple #18
0
        protected override System.Linq.Expressions.Expression <System.Func <TEntity, bool> > CreateExpression()
        {
            var parameter = Expression_.Parameter(typeof(TEntity), "entity");
            var replacer  = new ParameterVisitor(node => parameter);
            var leftBody  = replacer.Visit(LeftSideSpecification.Expression.Body);
            var rightBody = replacer.Visit(RightSideSpecification.Expression.Body);
            var newBody   = CreateBody(leftBody, rightBody);

            return(Expression_.Lambda <Func <TEntity, bool> >(newBody, parameter));
        }
Exemple #19
0
        public static LambdaExpression OrElse(
            LambdaExpression x, LambdaExpression y)
        {
            var newY = new ParameterVisitor(y.Parameters, x.Parameters)
                       .VisitAndConvert(y.Body, "OrElse");

            return(Expression.Lambda(
                       Expression.OrElse(x.Body, newY),
                       x.Parameters));
        }
Exemple #20
0
        public override OeEntityAsyncEnumerator ExecuteEnumerator(Object dataContext, OeParseUriContext parseUriContext, CancellationToken cancellationToken)
        {
            IQueryable entitySet  = parseUriContext.EntitySetAdapter.GetEntitySet(dataContext);
            Expression expression = parseUriContext.CreateExpression(entitySet, new OeConstantToVariableVisitor());

            expression = new ParameterVisitor().Visit(expression);
            var query = (IQueryable <Object>)entitySet.Provider.CreateQuery(expression);

            return(new OeEntityAsyncEnumeratorAdapter(query, cancellationToken));
        }
Exemple #21
0
        public static Expression <Func <T, bool> > Or <T>(
            Expression <Func <T, bool> > x, Expression <Func <T, bool> > y)
        {
            var newY = new ParameterVisitor(y.Parameters, x.Parameters)
                       .VisitAndConvert(y.Body, "Or");

            return(Expression.Lambda <Func <T, bool> >(
                       Expression.Or(x.Body, newY),
                       x.Parameters));
        }
Exemple #22
0
        public static LambdaExpression AndAlso(
            LambdaExpression x, LambdaExpression y)
        {
            var newY = new ParameterVisitor(y.Parameters, x.Parameters)
                       .VisitAndConvert(y.Body, "AndAlso");

            return(Expression.Lambda(
                       Expression.AndAlso(x.Body, newY),
                       x.Parameters));
        }
Exemple #23
0
        public BasicFilterBase Convert(Expression exp)
        {
            var parameters = new ParameterVisitor().GetParameters(exp);

            if (parameters.Count != 1)
            {
                throw new InvalidOperationException("İfade tek bir parametre içermeli!");
            }

            return(Visit(exp));
        }
Exemple #24
0
        public static LambdaExpression BuildPredicateForSubQuery(Type parentType, Type propertyType, Expression parameter)
        {
            var resultParameterVisitor = new ParameterVisitor();

            resultParameterVisitor.Visit(parameter);

            var parentParameter = (ParameterExpression)resultParameterVisitor.Parameter;
            var functionType    = typeof(Func <,>).MakeGenericType(parentType, propertyType);

            return(Expression.Lambda(functionType, parameter, parentParameter));
        }
        /// <summary>
        /// Performs analysis and returns a list of problems detected
        /// </summary>
        /// <param name="ruleExecutionContext">Contains the schema model and model element to analyze</param>
        /// <returns>
        /// The problems detected by the rule in the given element
        /// </returns>
        public override IList <SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext)
        {
            var problems = new List <SqlRuleProblem>();
            var sqlObj   = ruleExecutionContext.ModelElement;

            if (sqlObj == null || sqlObj.IsWhiteListed())
            {
                return(problems);
            }
            var name = sqlObj.Name.GetName();

            var fragment = ruleExecutionContext.ScriptFragment.GetFragment(typeof(CreateProcedureStatement));

            if (fragment.ScriptTokenStream == null)
            {
                return(problems);
            }

            var parameterVisitor = new ParameterVisitor();
            var selectVisitor    = new SelectStatementVisitor();

            fragment.Accept(parameterVisitor);
            fragment.Accept(selectVisitor);

            if (parameterVisitor.Count == 0 || selectVisitor.Count == 0)
            {
                return(problems);
            }

            var setVisitor = new SetVariableStatementVisitor();

            fragment.Accept(setVisitor);

            foreach (var param in parameterVisitor.Statements.Select(p => p.VariableName.Value))
            {
                var selectsUsingParam = selectVisitor.Statements.GetSelectsUsingParameterInWhere(param).ToList();
                if (!selectsUsingParam.Any())
                {
                    continue;
                }

                var selectStartLine      = selectsUsingParam.FirstOrDefault()?.StartLine;
                var getAssignmentSelects = selectVisitor.NotIgnoredStatements(RuleId)
                                           .GetSelectsSettingParameterValue(param).Where(sel => sel.StartLine < selectStartLine);
                var setStatements = setVisitor.NotIgnoredStatements(RuleId)
                                    .Where(set => _comparer.Equals(set.Variable.Name, param) && set.StartLine < selectStartLine);

                problems.AddRange(getAssignmentSelects.Select(x => new SqlRuleProblem(Message, sqlObj, x)));
                problems.AddRange(setStatements.Select(x => new SqlRuleProblem(Message, sqlObj, x)));
            }

            return(problems);
        }
        internal static LambdaExpression Bind(Type sourceType, PropertyOrFieldInfo member, LambdaExpression conversion, LambdaExpression customMapping = null)
        {
            var parameterToReplace = conversion.Parameters.Single();

              var newParameter = Expression.Parameter(sourceType, "p");

              var accessMember = Expression.MakeMemberAccess(newParameter, member);

              var visitor = new ParameterVisitor(parameterToReplace, accessMember);

              var newBody= visitor.Visit(conversion.Body);

              return Expression.Lambda(newBody, newParameter);
        }
        internal static LambdaExpression Bind(Type sourceType, PropertyOrFieldInfo member, LambdaExpression conversion, LambdaExpression customMapping = null)
        {
            var parameterToReplace = conversion.Parameters.Single();

            var newParameter = Expression.Parameter(sourceType, "p");

            var accessMember = Expression.MakeMemberAccess(newParameter, member);

            var visitor = new ParameterVisitor(parameterToReplace, accessMember);


            var newBody = visitor.Visit(conversion.Body);

            return(Expression.Lambda(newBody, newParameter));
        }
        public void ShouldReplaceParameter()
        {
            Expression<Func<User, bool>> expr1 = user => user.Name == "name";
            Expression<Func<User, bool>> expr2 = user => user.IsMale;

            var parm1 = expr1.Parameters[0];
            var parm2 = expr2.Parameters[0];

            var visitor = new ParameterVisitor(parm2, parm1);
            var body = visitor.Visit(expr2);

            var lambda = Expression.Lambda(body, parm1);

            Assert.Equal(parm1, lambda.Parameters[0]);
        }
Exemple #29
0
        public override OeAsyncEnumerator ExecuteEnumerator(Object dataContext, OeQueryContext queryContext, CancellationToken cancellationToken)
        {
            IQueryable entitySet  = queryContext.EntitySetAdapter.GetEntitySet(dataContext);
            Expression expression = queryContext.CreateExpression(entitySet, new OeConstantToVariableVisitor(queryContext.SkipTokenParser != null));

            expression = new ParameterVisitor().Visit(expression);

            var query = (IQueryable <Object>)entitySet.Provider.CreateQuery(expression);
            OeAsyncEnumerator asyncEnumerator = new OeAsyncEnumeratorAdapter(query, cancellationToken);

            if (queryContext.CountExpression != null)
            {
                asyncEnumerator.Count = query.Provider.Execute <int>(queryContext.CountExpression);
            }

            return(asyncEnumerator);
        }
Exemple #30
0
        public override TResult ExecuteScalar <TResult>(Object dataContext, OeQueryContext queryContext)
        {
            IQueryable query = queryContext.EntitySetAdapter.GetEntitySet(dataContext);
            Expression expression;

            if (base.QueryCache.AllowCache)
            {
                expression = GetFromCache(queryContext, (T)dataContext, base.QueryCache, out _);
            }
            else
            {
                expression = queryContext.CreateExpression(new OeConstantToVariableVisitor());
                expression = queryContext.TranslateSource(dataContext, expression);
                expression = new ParameterVisitor().Visit(expression);
            }
            return(query.Provider.Execute <TResult>(expression));
        }
        public void ShouldNotReplaceIfParameterIsDifferent()
        {
            Expression<Func<User, bool>> expr1 = user => user.Name == "name";
            Expression<Func<User, bool>> expr2 = user => user.IsMale;
            Expression<Func<User, bool>> expr3 = user => user.FavoriteNumber == 3;

            var parm1 = expr1.Parameters[0];
            var parm2 = expr2.Parameters[0];
            var parm3 = expr3.Parameters[0];

            var visitor = new ParameterVisitor(parm1, parm2);
            var body = visitor.Visit(expr3);

            var lambda = Expression.Lambda(body, parm3);

            Assert.Equal(parm3, lambda.Parameters[0]);
        }
        private static Expression GetFromCache(OeQueryContext queryContext, T dbContext, Cache.OeQueryCache queryCache,
                                               out MethodCallExpression countExpression)
        {
            Cache.OeCacheContext   cacheContext   = queryContext.CreateCacheContext();
            Cache.OeQueryCacheItem queryCacheItem = queryCache.GetQuery(cacheContext);

            Expression expression;
            IReadOnlyList <Cache.OeQueryCacheDbParameterValue> parameterValues;
            IQueryable query = queryContext.EntitySetAdapter.GetEntitySet(dbContext);

            if (queryCacheItem == null)
            {
                var parameterVisitor = new OeConstantToParameterVisitor();
                expression = queryContext.CreateExpression(parameterVisitor);
                expression = new ParameterVisitor().Visit(expression);

                countExpression = OeQueryContext.CreateCountExpression(expression);
                queryCache.AddQuery(queryContext.CreateCacheContext(parameterVisitor.ConstantToParameterMapper), expression, countExpression,
                                    queryContext.EntryFactory, queryContext.SkipTokenAccessors);
                parameterValues = parameterVisitor.ParameterValues;
            }
            else
            {
                expression = (Expression)queryCacheItem.Query;
                queryContext.EntryFactory       = queryCacheItem.EntryFactory;
                queryContext.SkipTokenAccessors = queryCacheItem.SkipTokenAccessors;
                countExpression = queryCacheItem.CountExpression;
                parameterValues = cacheContext.ParameterValues;
            }

            expression = new OeParameterToVariableVisitor().Translate(expression, parameterValues);
            expression = queryContext.TranslateSource(dbContext, expression);

            if (queryContext.ODataUri.QueryCount.GetValueOrDefault())
            {
                countExpression = (MethodCallExpression)queryContext.TranslateSource(dbContext, countExpression);
                countExpression = (MethodCallExpression) new OeParameterToVariableVisitor().Translate(countExpression, parameterValues);
            }
            else
            {
                countExpression = null;
            }

            return(expression);
        }
        public Expression <Func <TEntity, bool> > And(Expression <Func <TEntity, bool> > leftExpression, Expression <Func <TEntity, bool> > rightExpression)
        {
            if (leftExpression == null)
            {
                return(rightExpression);
            }

            if (rightExpression == null)
            {
                return(leftExpression);
            }

            var newRightExpression = new ParameterVisitor(rightExpression.Parameters, leftExpression.Parameters).VisitAndConvert(rightExpression.Body, "And");

            BinaryExpression andExpression = Expression.AndAlso(leftExpression.Body, newRightExpression);

            return(Expression.Lambda <Func <TEntity, bool> >(andExpression, leftExpression.Parameters.Single()));
        }
        public Expression <Func <TEntity, bool> > Or(Expression <Func <TEntity, bool> > leftExpression, Expression <Func <TEntity, bool> > rightExpression)
        {
            if (leftExpression == null)
            {
                return(rightExpression);
            }

            if (rightExpression == null)
            {
                return(leftExpression);
            }

            var newRightExpression = new ParameterVisitor(rightExpression.Parameters, leftExpression.Parameters).VisitAndConvert(rightExpression.Body, "Or");

            BinaryExpression orExpression = Expression.OrElse(leftExpression.Body, newRightExpression);

            return(Expression.Lambda <Func <TEntity, bool> >(orExpression, leftExpression.Parameters.Single()));
        }
        private void BuildSimpleTypeMappingExpressions(ParameterExpression source, ParameterExpression destination, ProposedMemberMapping member, List<Expression> expressions, List<ParameterExpression> newParams, CustomMapping customMapping = null)
        {
            Expression sourceExpression = Expression.PropertyOrField(source, member.SourceMember.Name);
              var destMember = Expression.PropertyOrField(destination, member.DestinationMember.Name);

              BinaryExpression assignSourceToDest;

              Expression customExpression;

              if (customMapping != null && (customExpression = customMapping.GetExpressionForMember(member.DestinationMember)) != null)
              {
            var visitor = new ParameterVisitor(customMapping.Parameter, source);

            customExpression = visitor.Visit(customExpression);

            assignSourceToDest = Expression.Assign(destMember, customExpression);

              }
              else
              {
            assignSourceToDest = Expression.Assign(destMember, sourceExpression);
              }

              expressions.Add(assignSourceToDest);
        }