/// <summary>
        /// Create a new UnaryOperatorQueryToken given the operator and operand
        /// </summary>
        /// <param name="operatorKind">The operator represented by this node.</param>
        /// <param name="operand">The operand.</param>
        public UnaryOperatorQueryToken(UnaryOperatorKind operatorKind, QueryToken operand)
        {
            ExceptionUtils.CheckArgumentNotNull(operand, "operand");

            this.operatorKind = operatorKind;
            this.operand = operand;
        }
Ejemplo n.º 2
0
 private static string ToString(QueryToken t)
 {
     if (t.Parts.Length == 1) { return t.Parts[0]; }
     string str = "\"";
     foreach (string part in t.Parts) { str += part + " "; }
     return str.TrimEnd(' ') + "\"";
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Create a new OrderByQueryToken given the expression and direction
        /// </summary>
        /// <param name="expression">The expression according to which to order the results.</param>
        /// <param name="direction">The direction of the ordering.</param>
        public OrderByQueryToken(QueryToken expression, OrderByDirection direction)
        {
            ExceptionUtils.CheckArgumentNotNull(expression, "expression");

            this.expression = expression;
            this.direction = direction;
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Binds the given filter token.
        /// </summary>
        /// <param name="filter">The filter token to bind.</param>
        /// <returns>A FilterNode with the given path linked to it (if provided).</returns>
        internal FilterClause BindFilter(QueryToken filter)
        {
            ExceptionUtils.CheckArgumentNotNull(filter, "filter");

            QueryNode expressionNode = this.bindMethod(filter);

            SingleValueNode expressionResultNode = expressionNode as SingleValueNode;
            if (expressionResultNode == null ||
                (expressionResultNode.TypeReference != null && !expressionResultNode.TypeReference.IsODataPrimitiveTypeKind()))
            {
                throw new ODataException(ODataErrorStrings.MetadataBinder_FilterExpressionNotSingleValue);
            }

            // The type may be null here if the query statically represents the null literal or an open property.
            IEdmTypeReference expressionResultType = expressionResultNode.TypeReference;
            if (expressionResultType != null)
            {
                IEdmPrimitiveTypeReference primitiveExpressionResultType = expressionResultType.AsPrimitiveOrNull();
                if (primitiveExpressionResultType == null ||
                    primitiveExpressionResultType.PrimitiveKind() != EdmPrimitiveTypeKind.Boolean)
                {
                    throw new ODataException(ODataErrorStrings.MetadataBinder_FilterExpressionNotSingleValue);
                }
            }

            FilterClause filterNode = new FilterClause(expressionResultNode, this.state.ImplicitRangeVariable);

            return filterNode;
        }
        /// <summary>
        /// Create a PropertyAccessQueryToken given the name and the parent (if any)
        /// </summary>
        /// <param name="name">The name of the property to access.</param>
        /// <param name="parent">The parent token to access the property on.  Pass no if this property has no parent.</param>
        public PropertyAccessQueryToken(string name, QueryToken parent)
        {
            ExceptionUtils.CheckArgumentStringNotNullOrEmpty(name, "name");

            this.name = name;
            this.parent = parent;
        }
Ejemplo n.º 6
0
        internal CountToken(QueryToken parent)
            : base(parent)
        {
            if (parent == null)
                throw new ArgumentNullException("parent");

        }
        private List<QueryToken> QueryTokenBuilder_SubTokensEvent(QueryToken arg)
        {
            if (SubTokensEvent == null)
                throw new InvalidOperationException("SubTokensEvent not set");

            return SubTokensEvent(arg);
        }
Ejemplo n.º 8
0
 private void UpdateTokenList(QueryToken queryToken)
 {
     if (queryToken == null)
         tokens = new List<QueryToken>();
     else
         tokens = queryToken.Follow(a => a.Parent).Reverse().ToList();
     UpdateCombo();
 }
Ejemplo n.º 9
0
        internal BagPropertyToken(QueryToken parent, PropertyInfo pi)
            : base(parent)
        {
            if (pi == null)
                throw new ArgumentNullException("pi");

            this.PropertyInfo = pi;
        }
Ejemplo n.º 10
0
        internal HasValueToken(QueryToken parent)
            : base(parent)
        {
            if (parent == null)
                throw new ArgumentNullException("parent");

            this.Priority = -1;
        }
Ejemplo n.º 11
0
        private List<QueryToken> QueryTokenBuilderOrders_SubTokensEvent(QueryToken token)
        {
            var cr = (UserChartEntity)DataContext;
            if (cr == null || QueryDescription == null)
                return new List<QueryToken>();

            return token.SubTokens(QueryDescription, SubTokensOptions.CanElement | (cr.GroupResults ? SubTokensOptions.CanAggregate : 0));
        }
Ejemplo n.º 12
0
        internal CollectionElementToken(QueryToken parent, CollectionElementType type)
            : base(parent)
        {
            elementType = parent.Type.ElementType();
            if (elementType == null)
                throw new InvalidOperationException("not a collection");

            this.CollectionElementType = type;
        }
Ejemplo n.º 13
0
        internal EntityPropertyToken(QueryToken parent, PropertyInfo pi, PropertyRoute pr)
            : base(parent)
        {
            if (pi == null)
                throw new ArgumentNullException("pi");

            this.PropertyInfo = pi;
            this.PropertyRoute = pr;
        }
        /// <summary>
        /// Create a new SegmentQueryToken given the name and parent and namedValues if any
        /// </summary>
        /// <param name="name">The name of the segment, the identifier.</param>
        /// <param name="parent">The parent segment, or null if this is the root segment.</param>
        /// <param name="namedValues">The named values in the key lookup for this segment.</param>
        public NavigationPropertyToken(string name, QueryToken parent, IEnumerable<NamedValue> namedValues)
        {
            // We allow an "empty" name segment so we can create one for the case of a service-document URL (which has no path)
            ExceptionUtils.CheckArgumentNotNull(name, "name");

            this.name = name;
            this.parent = parent;
            this.namedValues = namedValues == null ? null : new ReadOnlyEnumerable<NamedValue>(namedValues);
        }
        /// <summary>
        /// Create a new BinaryOperatorQueryToken given the operator, left and right query.
        /// </summary>
        /// <param name="operatorKind">The operator represented by this node.</param>
        /// <param name="left">The left operand.</param>
        /// <param name="right">The right operand.</param>
        public BinaryOperatorQueryToken(BinaryOperatorKind operatorKind, QueryToken left, QueryToken right)
        {
            ExceptionUtils.CheckArgumentNotNull(left, "left");
            ExceptionUtils.CheckArgumentNotNull(right, "right");

            this.operatorKind = operatorKind;
            this.left = left;
            this.right = right;
        }
Ejemplo n.º 16
0
        private List<QueryToken> token_SubTokensEvent(QueryToken token)
        {
            var ct = DataContext as ChartColumnEntity;
            if (ct == null)
                return new List<QueryToken>();

            var desc = this.VisualParents().OfType<ChartBuilder>().First().Description;

            return QueryUtils.SubTokens(token, desc, SubTokensOptions.CanElement |  (ct.IsGroupKey == false ? SubTokensOptions.CanAggregate : 0));
        }
Ejemplo n.º 17
0
        static string CanAny(QueryToken token)
        {
            if (token == null)
                return TemplateTokenMessage.NoColumnSelected.NiceToString();

            if (token.HasAllOrAny())
                return TemplateTokenMessage.YouCannotAddBlocksWithAllOrAny.NiceToString();

            return null;
        }
Ejemplo n.º 18
0
        public AggregateToken(AggregateFunction function, QueryToken parent)
            : base(parent)
        {
            if (function == AggregateFunction.Count)
                throw new ArgumentException("function should not different than Count for this overload");

            if (parent == null)
                throw new ArgumentNullException("parent");

            this.AggregateFunction = function;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Binds the given filter token.
        /// </summary>
        /// <param name="search">The search token to bind.</param>
        /// <returns>A SearchClause with for given Token.</returns>
        internal SearchClause BindSearch(QueryToken search)
        {
            ExceptionUtils.CheckArgumentNotNull(search, "filter");

            QueryNode expressionNode = this.bindMethod(search);

            SingleValueNode expressionResultNode = expressionNode as SingleValueNode;

            SearchClause searchClause = new SearchClause(expressionResultNode);

            return searchClause;
        }
Ejemplo n.º 20
0
        public static bool IsChartColumnType(QueryToken token, ChartColumnType ct)
        {
            if (token == null)
                return false;

            var type =  token.GetChartColumnType();

            if(type == null)
                return false;

            return Flag(ct, type.Value);
        }
Ejemplo n.º 21
0
        internal AsTypeToken(QueryToken parent, Type type)
            : base(parent)
        {
            if (parent == null)
                throw new ArgumentNullException("parent");

            if (type == null)
                throw new ArgumentNullException("type");

            this.entityType = type;

            this.Priority = 8;
        }
Ejemplo n.º 22
0
        List<QueryToken> OnSubTokens(QueryToken token)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return new List<QueryToken>();

            if (SubTokensEvent == null)
                throw new InvalidOperationException("SubTokensEvent not set");

            if (token != null && AllowSubTokens != null && !AllowSubTokens(token))
                return new List<QueryToken>();

            return SubTokensEvent(token);
        }
Ejemplo n.º 23
0
        static string CanIf(QueryToken token)
        {
            if (token == null)
                return TemplateTokenMessage.NoColumnSelected.NiceToString();

            if (token.Type != typeof(string) && token.Type != typeof(byte[]) && token.Type.ElementType() != null)
                return TemplateTokenMessage.YouCannotAddIfBlocksOnCollectionFields.NiceToString();

            if (token.HasAllOrAny())
                return TemplateTokenMessage.YouCannotAddBlocksWithAllOrAny.NiceToString();

            return null;
        }
Ejemplo n.º 24
0
        public static MvcHtmlString QueryTokenBuilder(this HtmlHelper helper, QueryToken queryToken, Context context, QueryTokenBuilderSettings settings)
        {
            HtmlStringBuilder sb = new HtmlStringBuilder();
            using (sb.Surround(new HtmlTag("span").Id(context.Prefix).Class("token-builder")))
            {
                sb.Add(QueryTokenBuilderOptions(helper, queryToken, context, settings));
            }

            sb.Add(MvcHtmlString.Create("<script>" + new JsFunction(JsFunction.FinderModule, "QueryTokenBuilder.init", context.Prefix,
                Navigator.ResolveWebQueryName(settings.QueryDescription.QueryName), settings.ControllerUrl, settings.RequestExtraJSonData).ToString()
                + "</script>")); 
        
            return sb.ToHtml();     
        }
Ejemplo n.º 25
0
        public static void TemplatingDecorators(QueryToken qt, HtmlTag option)
        {
            string canIf = CanIf(qt);
            if (canIf.HasText())
                option.Attr("data-if", canIf);

            string canForeach = CanForeach(qt);
            if (canForeach.HasText())
                option.Attr("data-foreach", canForeach);

            string canAny = CanAny(qt);
            if (canAny.HasText())
                option.Attr("data-any", canAny);
        }
Ejemplo n.º 26
0
        internal NetPropertyToken(QueryToken parent, PropertyInfo pi, string displayName)
            : base(parent)
        {
            if (parent == null)
                throw new ArgumentNullException("parent");

            if (pi == null)
                throw new ArgumentNullException("pi");

            if (displayName == null)
                throw new ArgumentNullException("displayName");

            this.DisplayName = displayName;
            this.PropertyInfo = pi;
        }
Ejemplo n.º 27
0
        public static MvcHtmlString QueryTokenBuilderOptions(this HtmlHelper helper, QueryToken queryToken, Context context, QueryTokenBuilderSettings settings)
        {
            var tokenPath = queryToken.Follow(qt => qt.Parent).Reverse().NotNull().ToList();

            HtmlStringBuilder sb = new HtmlStringBuilder();

            for (int i = 0; i < tokenPath.Count; i++)
            {
                sb.AddLine(helper.QueryTokenCombo(i == 0 ? null : tokenPath[i - 1], tokenPath[i], i, context, settings));
            }

            sb.AddLine(helper.QueryTokenCombo(queryToken, null, tokenPath.Count, context, settings));

            return sb.ToHtml();
        }
Ejemplo n.º 28
0
        static MvcHtmlString QueryTokenCombo(this HtmlHelper helper, QueryToken previous, QueryToken selected, int index, Context context, QueryTokenBuilderSettings settings)
        {
            if (previous != null && AllowSubTokens != null && !AllowSubTokens(previous))
                return MvcHtmlString.Create("");

            var queryTokens = previous.SubTokens(settings.QueryDescription, settings.CanAggregate);

            if (queryTokens.IsEmpty())
                return new HtmlTag("input")
                .Attr("type", "hidden")
                .IdName(context.Compose("ddlTokensEnd_" + index))
                .Attr("disabled", "disabled")
                .Attr("data-parenttoken", previous == null ? "" : previous.FullKey());

            var options = new HtmlStringBuilder();
            options.AddLine(new HtmlTag("option").Attr("value", "").SetInnerText("-").ToHtml());
            foreach (var qt in queryTokens)
            {
                var option = new HtmlTag("option")
                    .Attr("value", previous == null ? qt.FullKey() : qt.Key)
                    .SetInnerText((previous == null && qt.Parent != null ? " - " : "") + qt.ToString());

                if (selected != null && qt.Key == selected.Key)
                    option.Attr("selected", "selected");

                option.Attr("title", qt.NiceTypeName);
                option.Attr("style", "color:" + qt.TypeColor);

                if (settings.Decorators != null)
                    settings.Decorators(qt, option); 

                options.AddLine(option.ToHtml());
            }

            HtmlTag dropdown = new HtmlTag("select")
                .Class("form-control")
                .IdName(context.Compose("ddlTokens_" + index))
                .InnerHtml(options.ToHtml()) 
                .Attr("data-parenttoken", previous == null ? "" : previous.FullKey());

            if (selected != null)
            {
                dropdown.Attr("title", selected.NiceTypeName);
                dropdown.Attr("style", "color:" + selected.TypeColor);
            }

            return dropdown.ToHtml();
        }
Ejemplo n.º 29
0
        static string CanForeach(QueryToken token)
        {
            if (token == null)
                return TemplateTokenMessage.NoColumnSelected.NiceToString();

            if (token.Type != typeof(string) && token.Type != typeof(byte[]) && token.Type.ElementType() != null)
                return TemplateTokenMessage.YouHaveToAddTheElementTokenToUseForeachOnCollectionFields.NiceToString();

            if (token.Key != "Element" || token.Parent == null || token.Parent.Type.ElementType() == null)
                return TemplateTokenMessage.YouCanOnlyAddForeachBlocksWithCollectionFields.NiceToString();

            if (token.HasAllOrAny())
                return TemplateTokenMessage.YouCannotAddBlocksWithAllOrAny.NiceToString();

            return null;
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Parses member access.
        /// </summary>
        /// <param name="instance">Instance being accessed.</param>
        /// <returns>The lexical token representing the expression.</returns>
        public QueryToken ParseMemberAccess(QueryToken instance)
        {
            if (this.lexer.CurrentToken.Text == UriQueryConstants.Star)
            {
                return this.ParseStarMemberAccess(instance);
            }

            string identifier = this.lexer.CurrentToken.GetIdentifier();
            if (instance == null && this.parameters.Contains(identifier))
            {
                this.lexer.NextToken();
                return new RangeVariableToken(identifier);
            }

            this.lexer.NextToken();
            return new EndPathToken(identifier, instance);
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Create a AnyQueryToken given the expression, parameter, and parent
 /// </summary>
 /// <param name="expression">The associated expression.</param>
 /// <param name="parameter">The parameter denoting source type.</param>
 /// <param name="parent">The parent token.  Pass null if this property has no parent.</param>
 public AnyQueryToken(QueryToken expression, string parameter, QueryToken parent)
 {
     this.expression = expression;
     this.parameter  = parameter;
     this.parent     = parent;
 }
Ejemplo n.º 32
0
 public OrQuerySyntax(QuerySyntax left, QueryToken operatorToken, QuerySyntax right)
 {
     Left          = left;
     OperatorToken = operatorToken;
     Right         = right;
 }
Ejemplo n.º 33
0
 internal ModuloToken(QueryToken parent, int divisor)
 {
     this.parent  = parent ?? throw new ArgumentNullException(nameof(parent));
     this.Divisor = divisor;
 }
Ejemplo n.º 34
0
 private SingleValueNode BindMethodThatReturnsSingleValueExtensionQueryNode(QueryToken queryToken)
 {
     return(this.extensionSingleValueQueryNode);
 }
Ejemplo n.º 35
0
    static UserAssetTokenAction?SelectInteractive(ref QueryToken token, QueryDescription qd, SubTokensOptions options, string?remainingText, bool allowRemoveToken, bool allowReGenerate)
    {
        var top = Console.CursorTop;

        try
        {
            if (Console.Out == null)
            {
                throw new InvalidOperationException("Unable to ask for renames to synchronize query tokens without interactive Console. Please use your Terminal application.");
            }

            var subTokens = token.SubTokens(qd, options).OrderBy(a => a.Parent != null).ThenByDescending(a => a.Priority).ThenBy(a => a.Key).ToList();

            int startingIndex = 0;

            SafeConsole.WriteColor(ConsoleColor.Cyan, "  " + token?.FullKey());
            if (remainingText.HasText())
            {
                Console.Write(" " + remainingText);
            }
            Console.WriteLine();

            bool isRoot = token == null;

retry:
            int maxElements = Console.LargestWindowHeight - 11;

            subTokens.Skip(startingIndex).Take(maxElements)
            .Select((s, i) => "- {1,2}: {2} ".FormatWith(i + " ", i + startingIndex, ((isRoot && s.Parent != null) ? "-" : "") + s.Key)).ToConsole();
            Console.WriteLine();

            int remaining = subTokens.Count - startingIndex - maxElements;
            if (remaining > 0)
            {
                SafeConsole.WriteLineColor(ConsoleColor.White, "- +: Show more values ({0} remaining)", remaining);
            }

            if (token != null)
            {
                SafeConsole.WriteLineColor(ConsoleColor.White, "- b: Back");
                SafeConsole.WriteLineColor(ConsoleColor.Green, "- c: Confirm");
            }

            SafeConsole.WriteLineColor(ConsoleColor.Yellow, "- s: Skip entity");

            if (allowRemoveToken)
            {
                SafeConsole.WriteLineColor(ConsoleColor.DarkRed, "- r: Remove token");
            }

            if (allowReGenerate)
            {
                SafeConsole.WriteLineColor(ConsoleColor.Magenta, "- g: Generate from default template");
            }


            SafeConsole.WriteLineColor(ConsoleColor.Red, "- d: Delete entity");

            while (true)
            {
                string answer = Console.ReadLine() !;

                if (answer == null)
                {
                    throw new InvalidOperationException("Impossible to synchronize interactively without Console");
                }

                answer = answer.ToLower();

                if (answer == "+" && remaining > 0)
                {
                    startingIndex += maxElements;
                    goto retry;
                }

                if (answer == "s")
                {
                    return(UserAssetTokenAction.SkipEntity);
                }

                if (answer == "r" && allowRemoveToken)
                {
                    return(UserAssetTokenAction.RemoveToken);
                }

                if (answer == "d")
                {
                    return(UserAssetTokenAction.DeleteEntity);
                }

                if (answer == "g")
                {
                    return(UserAssetTokenAction.ReGenerateEntity);
                }

                if (token != null)
                {
                    if (answer == "c")
                    {
                        return(UserAssetTokenAction.Confirm);
                    }

                    if (answer == "b")
                    {
                        token = token.Parent !;
                        return(null);
                    }
                }

                if (int.TryParse(answer, out int option))
                {
                    token = subTokens[option];
                    return(null);
                }

                Console.WriteLine("Error");
            }
        }
        finally
        {
            Clean(top, Console.CursorTop);
        }
    }
Ejemplo n.º 36
0
        protected internal virtual ExtensionToken CreateToken(QueryToken parent)
        {
            var info = metas.GetOrAdd(parent, qt =>
            {
                Expression e = MetadataVisitor.JustVisit(Lambda, MetaExpression.FromToken(qt, SourceType));

                MetaExpression me;

                if (this.IsProjection)
                {
                    var mpe = e as MetaProjectorExpression;

                    if (mpe == null)
                    {
                        mpe = MetadataVisitor.AsProjection(e);
                    }

                    me = mpe == null ? null : mpe.Projector as MetaExpression;
                }
                else
                {
                    me = e as MetaExpression;
                }

                CleanMeta cm = me == null ? null : me.Meta as CleanMeta;

                var result = new ExtensionRouteInfo();

                if (cm != null && cm.PropertyRoutes.Any())
                {
                    var cleanType = me.Type.CleanType();

                    result.PropertyRoute   = cm.PropertyRoutes.Only();
                    result.Implementations = me.Meta.Implementations;
                    result.Format          = ColumnDescriptionFactory.GetFormat(cm.PropertyRoutes);
                    result.Unit            = ColumnDescriptionFactory.GetUnit(cm.PropertyRoutes);
                }

                result.IsAllowed = () => (me == null || me.Meta == null) ? null : me.Meta.IsAllowed();

                if (ForcePropertyRoute != null)
                {
                    result.PropertyRoute = ForcePropertyRoute;
                }

                if (ForceImplementations != null)
                {
                    result.Implementations = ForceImplementations;
                }

                if (ForceFormat != null)
                {
                    result.Format = ForceFormat;
                }

                if (ForceUnit != null)
                {
                    result.Unit = ForceUnit;
                }

                if (ForceIsAllowed != null)
                {
                    result.IsAllowed = ForceIsAllowed;
                }

                return(result);
            });

            return(new ExtensionToken(parent, Key, Type, IsProjection, info.Unit, info.Format, info.Implementations, info.IsAllowed(), info.PropertyRoute)
            {
                DisplayName = NiceName()
            });
        }
Ejemplo n.º 37
0
        public static Control GetValueControl(QueryToken token, string bindingPath)
        {
            Type type = token.Type;

            if (type.IsLite())
            {
                Implementations implementations = token.GetImplementations().Value;

                Type cleanType = Lite.Extract(type);

                if (EntityKindCache.IsLowPopulation(cleanType) && !implementations.IsByAll)
                {
                    EntityCombo ec = new EntityCombo
                    {
                        Type            = type,
                        Implementations = implementations,
                    };

                    ec.SetBinding(EntityCombo.EntityProperty, new Binding
                    {
                        Path = new PropertyPath(bindingPath),
                        NotifyOnValidationError = true,
                        ValidatesOnDataErrors   = true,
                        ValidatesOnExceptions   = true,
                    });

                    return(ec);
                }
                else
                {
                    EntityLine el = new EntityLine
                    {
                        Type            = type,
                        Create          = false,
                        Implementations = implementations,
                    };

                    el.SetBinding(EntityLine.EntityProperty, new Binding
                    {
                        Path = new PropertyPath(bindingPath),
                        NotifyOnValidationError = true,
                        ValidatesOnDataErrors   = true,
                        ValidatesOnExceptions   = true
                    });

                    return(el);
                }
            }
            else if (type.IsEmbeddedEntity())
            {
                EntityLine el = new EntityLine
                {
                    Type            = type,
                    Create          = false,
                    Autocomplete    = false,
                    Find            = false,
                    Implementations = null,
                };

                el.SetBinding(EntityLine.EntityProperty, new Binding
                {
                    Path = new PropertyPath(bindingPath),
                    NotifyOnValidationError = true,
                    ValidatesOnDataErrors   = true,
                    ValidatesOnExceptions   = true
                });

                return(el);
            }
            else
            {
                ValueLine vl = new ValueLine()
                {
                    Type     = type,
                    Format   = token.Format,
                    UnitText = token.Unit,
                };

                if (type.UnNullify().IsEnum)
                {
                    vl.ItemSource = EnumEntity.GetValues(type.UnNullify()).PreAndNull(type.IsNullable()).ToObservableCollection();
                }

                vl.SetBinding(ValueLine.ValueProperty, new Binding
                {
                    Path = new PropertyPath(bindingPath), //odd
                    NotifyOnValidationError = true,
                    ValidatesOnDataErrors   = true,
                    ValidatesOnExceptions   = true,
                    Converter = Reflector.IsNumber(type) ? Converters.Identity : null,
                });

                return(vl);
            }
        }
Ejemplo n.º 38
0
 internal NetPropertyToken(QueryToken parent, Expression <Func <object> > pi, Func <string> displayName) :
     this(parent, ReflectionTools.GetPropertyInfo(pi), displayName)
 {
 }
Ejemplo n.º 39
0
 public Expression <Func <object, V> > GetLambdaExpression <V>(QueryToken token)
 {
     return(Expression.Lambda <Func <object, V> >(Expression.Convert(token.BuildExpression(Context), typeof(V)), Context.Parameter));
 }
Ejemplo n.º 40
0
        /// <summary>
        /// Create a new FunctionCallToken using the given function name and parameter tokens.
        /// </summary>
        /// <param name="name">The name of the function to call.</param>
        /// <param name="arguments">The arguments for the function.</param>
        /// <param name="source">The syntactically bound parent of this function</param>
        public FunctionCallToken(string name, IEnumerable<FunctionParameterToken> arguments, QueryToken source)
        {
            ExceptionUtils.CheckArgumentStringNotNullOrEmpty(name, "name");

            this.name = name;
            this.arguments = new ReadOnlyEnumerableForUriParser<FunctionParameterToken>(arguments ?? FunctionParameterToken.EmptyParameterList);
            this.source = source;
        }
Ejemplo n.º 41
0
            void ParseInternal()
            {
                try
                {
                    this.mainBlock = new BlockNode(null);
                    this.stack     = new Stack <BlockNode>();
                    this.errors    = new List <TemplateError>();
                    PushBlock(mainBlock);

                    var matches = TemplateUtils.KeywordsRegex.Matches(text);

                    if (matches.Count == 0)
                    {
                        stack.Peek().Nodes.Add(new LiteralNode(text));
                        stack.Pop();
                        return;
                    }

                    int index = 0;
                    foreach (Match match in matches.Cast <Match>())
                    {
                        if (index < match.Index)
                        {
                            stack.Peek().Nodes.Add(new LiteralNode(text.Substring(index, match.Index - index)));
                        }
                        var expr     = match.Groups["expr"].Value;
                        var keyword  = match.Groups["keyword"].Value;
                        var variable = match.Groups["dec"].Value;
                        switch (keyword)
                        {
                        case "":
                        case "raw":
                            var s = TemplateUtils.SplitToken(expr);
                            if (s == null)
                            {
                                AddError(true, "{0} has invalid format".FormatWith(expr));
                            }
                            else
                            {
                                var t = ValueProviderBase.TryParse(s.Value.Token, variable, this);

                                stack.Peek().Nodes.Add(new ValueNode(t, s.Value.Format, isRaw: keyword.Contains("raw")));

                                DeclareVariable(t);
                            }
                            break;

                        case "declare":
                        {
                            var t = ValueProviderBase.TryParse(expr, variable, this);

                            stack.Peek().Nodes.Add(new DeclareNode(t, this.AddError));

                            DeclareVariable(t);
                        }
                        break;

                        case "any":
                        {
                            ConditionBase cond = TemplateUtils.ParseCondition(expr, variable, this);
                            AnyNode       any  = new AnyNode(cond);
                            stack.Peek().Nodes.Add(any);
                            PushBlock(any.AnyBlock);
                            if (cond is ConditionCompare cc)
                            {
                                DeclareVariable(cc.ValueProvider);
                            }
                            break;
                        }

                        case "notany":
                        {
                            var an = (AnyNode?)PopBlock(typeof(AnyNode))?.owner;
                            if (an != null)
                            {
                                PushBlock(an.CreateNotAny());
                            }
                            break;
                        }

                        case "endany":
                        {
                            PopBlock(typeof(AnyNode));
                            break;
                        }

                        case "foreach":
                        {
                            ValueProviderBase?vp = ValueProviderBase.TryParse(expr, variable, this);
                            if (vp is TokenValueProvider tvp && tvp.ParsedToken.QueryToken != null && QueryToken.IsCollection(tvp.ParsedToken.QueryToken.Type))
                            {
                                AddError(false, $"@foreach[{expr}] is a collection, missing 'Element' token at the end");
                            }

                            var fn = new ForeachNode(vp);
                            stack.Peek().Nodes.Add(fn);
                            PushBlock(fn.Block);
                            if (vp != null)
                            {
                                vp.IsForeach = true;
                            }
                            DeclareVariable(vp);
                            break;
                        }

                        case "endforeach":
                        {
                            PopBlock(typeof(ForeachNode));
                        }
                        break;

                        case "if":
                        {
                            ConditionBase cond = TemplateUtils.ParseCondition(expr, variable, this);
                            IfNode        ifn  = new IfNode(cond, this);
                            stack.Peek().Nodes.Add(ifn);
                            PushBlock(ifn.IfBlock);
                            if (cond is ConditionCompare cc)
                            {
                                DeclareVariable(cc.ValueProvider);
                            }
                            break;
                        }

                        case "else":
                        {
                            var ifn = (IfNode?)PopBlock(typeof(IfNode))?.owner;
                            if (ifn != null)
                            {
                                PushBlock(ifn.CreateElse());
                            }
                            break;
                        }

                        case "endif":
                        {
                            PopBlock(typeof(IfNode));
                            break;
                        }

                        default:
                            AddError(true, "'{0}' is deprecated".FormatWith(keyword));
                            break;
                        }
                        index = match.Index + match.Length;
                    }

                    if (stack.Count != 1)
                    {
                        AddError(true, "Last block is not closed: {0}".FormatWith(stack.Peek()));
                    }

                    var lastM = matches.Cast <Match>().LastOrDefault();
                    if (lastM != null && lastM.Index + lastM.Length < text.Length)
                    {
                        stack.Peek().Nodes.Add(new LiteralNode(text.Substring(lastM.Index + lastM.Length)));
                    }

                    stack.Pop();
                }
                catch (Exception e)
                {
                    AddError(true, e.Message);
                }
            }
        /// <summary>
        /// Create a new BinaryOperatorQueryToken given the operator, left and right query.
        /// </summary>
        /// <param name="operatorKind">The operator represented by this node.</param>
        /// <param name="left">The left operand.</param>
        /// <param name="right">The right operand.</param>
        public BinaryOperatorQueryToken(BinaryOperatorKind operatorKind, QueryToken left, QueryToken right)
        {
            ExceptionUtils.CheckArgumentNotNull(left, "left");
            ExceptionUtils.CheckArgumentNotNull(right, "right");

            this.operatorKind = operatorKind;
            this.left         = left;
            this.right        = right;
        }
Ejemplo n.º 43
0
 /// <summary>
 /// Helper bind method that returns null. Parameter is unused.
 /// </summary>
 private QueryNode BindMethodReturnsNull(QueryToken token)
 {
     return(null);
 }
Ejemplo n.º 44
0
 /// <summary>
 /// Create an expand term token
 /// </summary>
 /// <param name="pathToNavigationProp">the nav prop for this expand term</param>
 /// <param name="filterOption">the filter option for this expand term</param>
 /// <param name="orderByOptions">the orderby options for this expand term</param>
 /// <param name="topOption">the top option for this expand term</param>
 /// <param name="skipOption">the skip option for this expand term</param>
 /// <param name="countQueryOption">the query count option for this expand term</param>
 /// <param name="levelsOption">the levels option for this expand term</param>
 /// <param name="searchOption">the search option for this expand term</param>
 /// <param name="selectOption">the select option for this expand term</param>
 /// <param name="expandOption">the expand option for this expand term</param>
 public ExpandTermToken(PathSegmentToken pathToNavigationProp, QueryToken filterOption, IEnumerable <OrderByToken> orderByOptions, long?topOption, long?skipOption, bool?countQueryOption, long?levelsOption, QueryToken searchOption, SelectToken selectOption, ExpandToken expandOption)
     : this(pathToNavigationProp, filterOption, orderByOptions, topOption, skipOption, countQueryOption, levelsOption, searchOption, selectOption, expandOption, null)
 {
 }
Ejemplo n.º 45
0
 public UnaryOperatorToken(UnaryOperatorCategory operatorCategory, QueryToken operand)
 {
     OperatorCategory = operatorCategory;
     Operand          = operand;
 }
Ejemplo n.º 46
0
        /// <summary>
        /// Create an expand term token
        /// </summary>
        /// <param name="pathToNavigationProp">the nav prop for this expand term</param>
        /// <param name="filterOption">the filter option for this expand term</param>
        /// <param name="orderByOptions">the orderby options for this expand term</param>
        /// <param name="topOption">the top option for this expand term</param>
        /// <param name="skipOption">the skip option for this expand term</param>
        /// <param name="countQueryOption">the query count option for this expand term</param>
        /// <param name="levelsOption">the levels option for this expand term</param>
        /// <param name="searchOption">the search option for this expand term</param>
        /// <param name="selectOption">the select option for this expand term</param>
        /// <param name="expandOption">the expand option for this expand term</param>
        public ExpandTermToken(PathSegmentToken pathToNavigationProp, QueryToken filterOption, IEnumerable <OrderByToken> orderByOptions, long?topOption, long?skipOption, bool?countQueryOption, long?levelsOption, QueryToken searchOption, SelectToken selectOption, ExpandToken expandOption)
        {
            ExceptionUtils.CheckArgumentNotNull(pathToNavigationProp, "property");

            this.pathToNavigationProp = pathToNavigationProp;
            this.filterOption         = filterOption;
            this.orderByOptions       = orderByOptions;
            this.topOption            = topOption;
            this.skipOption           = skipOption;
            this.countQueryOption     = countQueryOption;
            this.levelsOption         = levelsOption;
            this.searchOption         = searchOption;
            this.selectOption         = selectOption;
            this.expandOption         = expandOption;
        }
Ejemplo n.º 47
0
        public override void RenderLines(DynamicQueryOmniboxResult result, InlineCollection lines)
        {
            lines.AddMatch(result.QueryNameMatch);


            foreach (var item in result.Filters)
            {
                lines.Add(" ");

                QueryToken last = null;
                if (item.QueryTokenMatches != null)
                {
                    foreach (var tokenMatch in item.QueryTokenMatches)
                    {
                        if (last != null)
                        {
                            lines.Add(".");
                        }

                        lines.AddMatch(tokenMatch);

                        last = (QueryToken)tokenMatch.Value;
                    }
                }

                if (item.QueryToken != last)
                {
                    if (last != null)
                    {
                        lines.Add(".");
                    }

                    lines.Add(new Run(item.QueryToken.Key)
                    {
                        Foreground = Brushes.Gray
                    });
                }

                if (item.CanFilter.HasText())
                {
                    lines.Add(new Run(item.CanFilter)
                    {
                        Foreground = Brushes.Red
                    });
                }
                else if (item.Operation != null)
                {
                    lines.Add(new Bold(new Run(FilterValueConverter.ToStringOperation(item.Operation.Value))));

                    if ((item.Value as string) == DynamicQueryOmniboxResultGenerator.UnknownValue)
                    {
                        lines.Add(new Run(OmniboxMessage.Unknown.NiceToString())
                        {
                            Foreground = Brushes.Red
                        });
                    }
                    else if (item.ValueMatch != null)
                    {
                        lines.AddMatch(item.ValueMatch);
                    }
                    else if (item.Syntax != null && item.Syntax.Completion == FilterSyntaxCompletion.Complete)
                    {
                        lines.Add(new Bold(new Run(DynamicQueryOmniboxResultGenerator.ToStringValue(item.Value))));
                    }
                    else
                    {
                        lines.Add(new Run(DynamicQueryOmniboxResultGenerator.ToStringValue(item.Value))
                        {
                            Foreground = Brushes.Gray
                        });
                    }
                }
            }
        }
Ejemplo n.º 48
0
 private static SingleValueNode BindMethodReturnsBooleanPrimitive(QueryToken token)
 {
     return(_booleanPrimitiveNode);
 }
Ejemplo n.º 49
0
        internal static SubscriptionCreationOptions CreateSubscriptionOptionsFromGeneric <T>(
            DocumentConventions conventions,
            SubscriptionCreationOptions criteria,
            Expression <Func <T, bool> > predicate,
            Expression <Func <T, object> > project,
            Action <ISubscriptionIncludeBuilder <T> > includes)
        {
            criteria ??= new SubscriptionCreationOptions();
            var collectionName = conventions.GetCollectionName(typeof(T));

            if (criteria.Query == null)
            {
                var tType            = typeof(T);
                var includeRevisions = tType.IsConstructedGenericType && tType.GetGenericTypeDefinition() == typeof(Revision <>);
                if (includeRevisions)
                {
                    collectionName = conventions.GetCollectionName(tType.GenericTypeArguments[0]);
                }

                var builder = new StringBuilder("from '");
                StringExtensions.EscapeString(builder, collectionName);
                builder.Append('\'');
                if (includeRevisions)
                {
                    builder.Append(" (Revisions = true)");
                }

                criteria.Query = builder.Append(" as doc").ToString();
            }

            if (predicate != null)
            {
                var script = predicate.CompileToJavascript(
                    new JavascriptCompilationOptions(
                        JsCompilationFlags.BodyOnly,
                        JavascriptConversionExtensions.MathSupport.Instance,
                        new JavascriptConversionExtensions.DictionarySupport(),
                        JavascriptConversionExtensions.LinqMethodsSupport.Instance,
                        new JavascriptConversionExtensions.SubscriptionsWrappedConstantSupport(conventions),
                        new JavascriptConversionExtensions.ConstSupport(conventions),
                        new JavascriptConversionExtensions.ReplaceParameterWithNewName(predicate.Parameters[0], "this"),
                        JavascriptConversionExtensions.ToStringSupport.Instance,
                        JavascriptConversionExtensions.DateTimeSupport.Instance,
                        JavascriptConversionExtensions.TimeSpanSupport.Instance,
                        JavascriptConversionExtensions.InvokeSupport.Instance,
                        JavascriptConversionExtensions.NullCoalescingSupport.Instance,
                        JavascriptConversionExtensions.NestedConditionalSupport.Instance,
                        JavascriptConversionExtensions.StringSupport.Instance
                        ));

                criteria.Query = $"declare function predicate() {{ return {script} }}{Environment.NewLine}" +
                                 $"{criteria.Query}{Environment.NewLine}" +
                                 "where predicate.call(doc)";
            }

            if (project != null)
            {
                var script = project.CompileToJavascript(
                    new JavascriptCompilationOptions(
                        JsCompilationFlags.BodyOnly,
                        JavascriptConversionExtensions.MathSupport.Instance,
                        new JavascriptConversionExtensions.DictionarySupport(),
                        JavascriptConversionExtensions.LinqMethodsSupport.Instance,
                        new JavascriptConversionExtensions.ConstSupport(conventions),
                        JavascriptConversionExtensions.ToStringSupport.Instance,
                        JavascriptConversionExtensions.DateTimeSupport.Instance,
                        JavascriptConversionExtensions.TimeSpanSupport.Instance,
                        JavascriptConversionExtensions.InvokeSupport.Instance,
                        JavascriptConversionExtensions.NullCoalescingSupport.Instance,
                        JavascriptConversionExtensions.StringSupport.Instance,
                        JavascriptConversionExtensions.NestedConditionalSupport.Instance,
                        new JavascriptConversionExtensions.ReplaceParameterWithNewName(project.Parameters[0], "doc"),
                        new JavascriptConversionExtensions.IdentityPropertySupport(conventions),
                        JavascriptConversionExtensions.CounterSupport.Instance,
                        JavascriptConversionExtensions.CompareExchangeSupport.Instance,
                        new JavascriptConversionExtensions.LoadSupport(),
                        JavascriptConversionExtensions.MemberInit.Instance
                        ));
                criteria.Query += Environment.NewLine + "select " + script;
            }

            if (includes != null)
            {
                var builder = new IncludeBuilder <T>(conventions);
                includes(builder);

                if (builder.DocumentsToInclude != null && builder.DocumentsToInclude.Count > 0)
                {
                    criteria.Query += Environment.NewLine + "include ";

                    var first = true;
                    foreach (var inc in builder.DocumentsToInclude)
                    {
                        var include = "doc." + inc;
                        if (first == false)
                        {
                            criteria.Query += ",";
                        }
                        first = false;

                        if (IncludesUtil.RequiresQuotes(include, out var escapedInclude))
                        {
                            criteria.Query += $"'{escapedInclude}'";
                        }
                        else
                        {
                            criteria.Query += QueryToken.IsKeyword(include) ? $"'{include}'" : include;
                        }
                    }
                }
            }

            return(criteria);
        }
Ejemplo n.º 50
0
 internal CountToken(QueryToken parent)
 {
     this.parent = parent ?? throw new ArgumentNullException(nameof(parent));
 }
Ejemplo n.º 51
0
 private CollectionNode BindMethodThatReturnsCollectionQueryNode(QueryToken queryToken)
 {
     return(null);
 }
Ejemplo n.º 52
0
 /// <summary>
 /// Create a AnyAllQueryToken given the expression, parameter, and parent
 /// </summary>
 /// <param name="expression">The associated expression.</param>
 /// <param name="parameter">The parameter denoting source type.</param>
 /// <param name="parent">The parent token.  Pass null if this property has no parent.</param>
 protected LambdaToken(QueryToken expression, string parameter, QueryToken parent)
 {
     this.expression = expression;
     this.parameter  = parameter;
     this.parent     = parent;
 }
Ejemplo n.º 53
0
 /// <summary>
 /// We substitute the following methods for the MetadataBinder.Bind method to keep the tests from growing too large in scope.
 /// In practice this does the same thing.
 /// </summary>
 private SingleValueNode BindMethodThatReturnsSingleValueQueryNode(QueryToken queryToken)
 {
     return(this.parameterSingleValueQueryNode);
 }
        /// <summary>
        /// Parses the <paramref name="queryUri"/> and returns a new instance of <see cref="QueryDescriptorQueryToken"/>
        /// describing the query specified by the uri.
        /// </summary>
        /// <param name="queryUri">The absolute URI which holds the query to parse. This must be a path relative to the <paramref name="serviceBaseUri"/>.</param>
        /// <param name="serviceBaseUri">The base URI of the service.</param>
        /// <param name="maxDepth">The maximum depth of any single query part. Security setting to guard against DoS attacks causing stack overflows and such.</param>
        /// <returns>A new instance of <see cref="QueryDescriptorQueryToken"/> which represents the query specified in the <paramref name="queryUri"/>.</returns>
        public static QueryDescriptorQueryToken ParseUri(Uri queryUri, Uri serviceBaseUri, int maxDepth)
        {
            ExceptionUtils.CheckArgumentNotNull(queryUri, "queryUri");
            if (!queryUri.IsAbsoluteUri)
            {
                throw new ArgumentException(Strings.QueryDescriptorQueryToken_UriMustBeAbsolute(queryUri), "queryUri");
            }

            ExceptionUtils.CheckArgumentNotNull(serviceBaseUri, "serviceBaseUri");
            if (!serviceBaseUri.IsAbsoluteUri)
            {
                throw new ArgumentException(Strings.QueryDescriptorQueryToken_UriMustBeAbsolute(serviceBaseUri), "serviceBaseUri");
            }

            if (maxDepth <= 0)
            {
                throw new ArgumentException(Strings.QueryDescriptorQueryToken_MaxDepthInvalid, "maxDepth");
            }

            UriQueryPathParser pathParser = new UriQueryPathParser(maxDepth);
            QueryToken         path       = pathParser.ParseUri(queryUri, serviceBaseUri);

            List <QueryOptionQueryToken> queryOptions = UriUtils.ParseQueryOptions(queryUri);

            QueryToken filter      = null;
            string     filterQuery = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.FilterQueryOption);

            if (filterQuery != null)
            {
                UriQueryExpressionParser expressionParser = new UriQueryExpressionParser(maxDepth);
                filter = expressionParser.ParseFilter(filterQuery);
            }

            IEnumerable <OrderByQueryToken> orderByTokens = null;
            string orderByQuery = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.OrderByQueryOption);

            if (orderByQuery != null)
            {
                UriQueryExpressionParser expressionParser = new UriQueryExpressionParser(maxDepth);
                orderByTokens = expressionParser.ParseOrderBy(orderByQuery);
            }

            SelectQueryToken select      = null;
            string           selectQuery = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.SelectQueryOption);

            if (selectQuery != null)
            {
                UriQueryExpressionParser expressionParser = new UriQueryExpressionParser(maxDepth);
                select = expressionParser.ParseSelect(selectQuery);
            }

            ExpandQueryToken expand      = null;
            string           expandQuery = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.ExpandQueryOption);

            if (expandQuery != null)
            {
                UriQueryExpressionParser expressionParser = new UriQueryExpressionParser(maxDepth);
                expand = expressionParser.ParseExpand(expandQuery);
            }

            int?   skip      = null;
            string skipQuery = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.SkipQueryOption);

            if (skipQuery != null)
            {
                int skipValue;
                if (!UriPrimitiveTypeParser.TryUriStringToNonNegativeInteger(skipQuery, out skipValue))
                {
                    throw new ODataException(Strings.QueryDescriptorQueryToken_InvalidSkipQueryOptionValue(skipQuery));
                }

                skip = skipValue;
            }

            int?   top      = null;
            string topQuery = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.TopQueryOption);

            if (topQuery != null)
            {
                int topValue;
                if (!UriPrimitiveTypeParser.TryUriStringToNonNegativeInteger(topQuery, out topValue))
                {
                    throw new ODataException(Strings.QueryDescriptorQueryToken_InvalidTopQueryOptionValue(topQuery));
                }

                top = topValue;
            }

            string          inlineCountQuery = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.InlineCountQueryOption);
            InlineCountKind?inlineCount      = QueryTokenUtils.ParseInlineCountKind(inlineCountQuery);

            string format = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.FormatQueryOption);

            return(new QueryDescriptorQueryToken(
                       path,
                       filter,
                       orderByTokens,
                       select,
                       expand,
                       skip,
                       top,
                       inlineCount,
                       format,
                       queryOptions.Count == 0 ? null : new ReadOnlyCollection <QueryOptionQueryToken>(queryOptions)));
        }
Ejemplo n.º 55
0
 /// <summary>
 /// Create a AllToken given the expression, parameter, and parent
 /// </summary>
 /// <param name="expression">The associated expression.</param>
 /// <param name="parameter">The parameter denoting source type.</param>
 /// <param name="parent">The parent token.  Pass null if this property has no parent.</param>
 public AllToken(QueryToken expression, string parameter, QueryToken parent) : base(expression, parameter, parent)
 {
 }
Ejemplo n.º 56
0
 public virtual List <QueryToken> ExternalQueryToken(QueryToken parent)
 {
     return(Return(MethodInfo.GetCurrentMethod(),
                   () => DynamicQueryManager.Current.GetExtensions(parent).ToList()));
 }
Ejemplo n.º 57
0
        /// <summary>
        /// Parses the <paramref name="queryUri"/> and returns a new instance of <see cref="SyntacticTree"/>
        /// describing the query specified by the uri.
        /// </summary>
        /// <param name="queryUri">The absolute URI which holds the query to parse. This must be a path relative to the <paramref name="serviceBaseUri"/>.</param>
        /// <param name="serviceBaseUri">The base URI of the service.</param>
        /// <param name="maxDepth">The maximum depth of any single query part. Security setting to guard against DoS attacks causing stack overflows and such.</param>
        /// <returns>A new instance of <see cref="SyntacticTree"/> which represents the query specified in the <paramref name="queryUri"/>.</returns>
        public static SyntacticTree ParseUri(Uri queryUri, Uri serviceBaseUri, int maxDepth)
        {
            ExceptionUtils.CheckArgumentNotNull(queryUri, "queryUri");
            if (!queryUri.IsAbsoluteUri)
            {
                throw new ArgumentException(Strings.SyntacticTree_UriMustBeAbsolute(queryUri), "queryUri");
            }

            ExceptionUtils.CheckArgumentNotNull(serviceBaseUri, "serviceBaseUri");
            if (!serviceBaseUri.IsAbsoluteUri)
            {
                throw new ArgumentException(Strings.SyntacticTree_UriMustBeAbsolute(serviceBaseUri), "serviceBaseUri");
            }

            if (maxDepth <= 0)
            {
                throw new ArgumentException(Strings.SyntacticTree_MaxDepthInvalid, "maxDepth");
            }


            UriPathParser pathParser = new UriPathParser(maxDepth);
            var           path       = pathParser.ParsePathIntoSegments(queryUri, serviceBaseUri);

            // COMPAT 32: Differencies in query options parsing in WCF DS
            //
            // We allow non-system $ query options in the lexical space.
            // We allow multiple instances of a custom or non-system $ query option in the lexical space.
            // TODO: we need to decide whether we want to allow multiple system $ query options with the same name (OIPI suggests that this is valid); we currently don't.
            List <CustomQueryOptionToken> queryOptions     = UriUtils.ParseQueryOptions(queryUri);
            IDictionary <string, string>  parameterAliases = queryOptions.GetParameterAliases();

            QueryToken filter      = null;
            string     filterQuery = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.FilterQueryOption);

            if (filterQuery != null)
            {
                UriQueryExpressionParser expressionParser = new UriQueryExpressionParser(maxDepth);
                filter = expressionParser.ParseFilter(filterQuery);
            }

            IEnumerable <OrderByToken> orderByTokens = null;
            string orderByQuery = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.OrderByQueryOption);

            if (orderByQuery != null)
            {
                UriQueryExpressionParser expressionParser = new UriQueryExpressionParser(maxDepth);
                orderByTokens = expressionParser.ParseOrderBy(orderByQuery);
            }

            SelectToken select      = null;
            string      selectQuery = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.SelectQueryOption);

            if (selectQuery != null)
            {
                SelectExpandParser selectParser = new SelectExpandParser(selectQuery, ODataUriParserSettings.DefaultSelectExpandLimit);
                select = selectParser.ParseSelect();
            }

            ExpandToken expand      = null;
            string      expandQuery = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.ExpandQueryOption);

            if (expandQuery != null)
            {
                SelectExpandParser expandParser = new SelectExpandParser(expandQuery, ODataUriParserSettings.DefaultSelectExpandLimit);
                expand = expandParser.ParseExpand();
            }

            int?   skip      = null;
            string skipQuery = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.SkipQueryOption);

            if (skipQuery != null)
            {
                int skipValue;
                if (!UriPrimitiveTypeParser.TryUriStringToNonNegativeInteger(skipQuery, out skipValue))
                {
                    throw new ODataException(Strings.SyntacticTree_InvalidSkipQueryOptionValue(skipQuery));
                }

                skip = skipValue;
            }

            int?   top      = null;
            string topQuery = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.TopQueryOption);

            if (topQuery != null)
            {
                int topValue;
                if (!UriPrimitiveTypeParser.TryUriStringToNonNegativeInteger(topQuery, out topValue))
                {
                    throw new ODataException(Strings.SyntacticTree_InvalidTopQueryOptionValue(topQuery));
                }

                top = topValue;
            }

            string countQuery = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.CountQueryOption);
            bool?  count      = ParseQueryCount(countQuery);

            string format = queryOptions.GetQueryOptionValueAndRemove(UriQueryConstants.FormatQueryOption);

            return(new SyntacticTree(
                       parameterAliases,
                       path,
                       filter,
                       orderByTokens,
                       select,
                       expand,
                       skip,
                       top,
                       count,
                       format,
                       queryOptions.Count == 0 ? null : new ReadOnlyCollection <CustomQueryOptionToken>(queryOptions)));
        }
Ejemplo n.º 58
0
 internal DatePartStartToken(QueryToken parent, QueryTokenMessage name)
 {
     this.Name   = name;
     this.parent = parent ?? throw new ArgumentNullException(nameof(parent));
 }
Ejemplo n.º 59
0
        internal static SubscriptionCreationOptions CreateSubscriptionOptionsFromGeneric <T>(
            DocumentConventions conventions,
            SubscriptionCreationOptions criteria,
            Expression <Func <T, bool> > predicate,
            Expression <Func <T, object> > project,
            Action <ISubscriptionIncludeBuilder <T> > includes)
        {
            criteria ??= new SubscriptionCreationOptions();
            var           collectionName = conventions.GetCollectionName(typeof(T));
            StringBuilder queryBuilder;

            if (criteria.Query != null)
            {
                queryBuilder = new StringBuilder(criteria.Query);
            }
            else
            {
                queryBuilder = new StringBuilder();
                var tType            = typeof(T);
                var includeRevisions = tType.IsConstructedGenericType && tType.GetGenericTypeDefinition() == typeof(Revision <>);
                if (includeRevisions)
                {
                    collectionName = conventions.GetCollectionName(tType.GenericTypeArguments[0]);
                }

                queryBuilder.Append("from '");
                StringExtensions.EscapeString(queryBuilder, collectionName);
                queryBuilder.Append('\'');
                if (includeRevisions)
                {
                    queryBuilder.Append(" (Revisions = true)");
                }

                criteria.Query = queryBuilder.Append(" as doc").ToString();
            }

            if (predicate != null)
            {
                var script = predicate.CompileToJavascript(
                    new JavascriptCompilationOptions(
                        JsCompilationFlags.BodyOnly,
                        JavascriptConversionExtensions.MathSupport.Instance,
                        new JavascriptConversionExtensions.DictionarySupport(),
                        JavascriptConversionExtensions.LinqMethodsSupport.Instance,
                        new JavascriptConversionExtensions.SubscriptionsWrappedConstantSupport(conventions),
                        new JavascriptConversionExtensions.ConstSupport(conventions),
                        new JavascriptConversionExtensions.ReplaceParameterWithNewName(predicate.Parameters[0], "this"),
                        JavascriptConversionExtensions.ToStringSupport.Instance,
                        JavascriptConversionExtensions.DateTimeSupport.Instance,
                        JavascriptConversionExtensions.TimeSpanSupport.Instance,
                        JavascriptConversionExtensions.InvokeSupport.Instance,
                        JavascriptConversionExtensions.NullCoalescingSupport.Instance,
                        JavascriptConversionExtensions.NestedConditionalSupport.Instance,
                        JavascriptConversionExtensions.StringSupport.Instance,
                        new JavascriptConversionExtensions.IdentityPropertySupport(conventions)
                        ));

                queryBuilder
                .Insert(0, $"declare function predicate() {{ return {script} }}{Environment.NewLine}")
                .AppendLine()
                .Append("where predicate.call(doc)");
            }

            if (project != null)
            {
                var script = project.CompileToJavascript(
                    new JavascriptCompilationOptions(
                        JsCompilationFlags.BodyOnly,
                        JavascriptConversionExtensions.MathSupport.Instance,
                        new JavascriptConversionExtensions.DictionarySupport(),
                        JavascriptConversionExtensions.LinqMethodsSupport.Instance,
                        new JavascriptConversionExtensions.ConstSupport(conventions),
                        JavascriptConversionExtensions.ToStringSupport.Instance,
                        JavascriptConversionExtensions.DateTimeSupport.Instance,
                        JavascriptConversionExtensions.TimeSpanSupport.Instance,
                        JavascriptConversionExtensions.InvokeSupport.Instance,
                        JavascriptConversionExtensions.NullCoalescingSupport.Instance,
                        JavascriptConversionExtensions.StringSupport.Instance,
                        JavascriptConversionExtensions.NestedConditionalSupport.Instance,
                        new JavascriptConversionExtensions.ReplaceParameterWithNewName(project.Parameters[0], "doc"),
                        new JavascriptConversionExtensions.IdentityPropertySupport(conventions),
                        JavascriptConversionExtensions.CounterSupport.Instance,
                        JavascriptConversionExtensions.CompareExchangeSupport.Instance,
                        new JavascriptConversionExtensions.LoadSupport(),
                        JavascriptConversionExtensions.MemberInit.Instance
                        ));

                queryBuilder
                .AppendLine()
                .Append("select ")
                .Append(script);
            }

            if (includes != null)
            {
                var builder = new IncludeBuilder <T>(conventions);
                includes(builder);

                var numberOfIncludesAdded = 0;

                if (builder.DocumentsToInclude?.Count > 0)
                {
                    queryBuilder
                    .AppendLine()
                    .Append("include ");

                    foreach (var inc in builder.DocumentsToInclude)
                    {
                        var include = "doc." + inc;

                        if (numberOfIncludesAdded > 0)
                        {
                            queryBuilder.Append(",");
                        }

                        if (IncludesUtil.RequiresQuotes(include, out var escapedInclude))
                        {
                            queryBuilder
                            .Append("'")
                            .Append(escapedInclude)
                            .Append("'");
                        }
                        else
                        {
                            queryBuilder.Append(QueryToken.IsKeyword(include) ? $"'{include}'" : include);
                        }

                        numberOfIncludesAdded++;
                    }
                }

                if (builder.AllCounters)
                {
                    if (numberOfIncludesAdded == 0)
                    {
                        queryBuilder
                        .AppendLine()
                        .Append("include ");
                    }

                    var token = CounterIncludesToken.All(string.Empty);
                    token.WriteTo(queryBuilder);

                    numberOfIncludesAdded++;
                }
                else if (builder.CountersToInclude?.Count > 0)
                {
                    if (numberOfIncludesAdded == 0)
                    {
                        queryBuilder
                        .AppendLine()
                        .Append("include ");
                    }

                    foreach (var counterName in builder.CountersToInclude)
                    {
                        if (numberOfIncludesAdded > 0)
                        {
                            queryBuilder.Append(",");
                        }

                        var token = CounterIncludesToken.Create(string.Empty, counterName);
                        token.WriteTo(queryBuilder);

                        numberOfIncludesAdded++;
                    }
                }

                if (builder.TimeSeriesToInclude != null)
                {
                    foreach (var timeSeriesRange in builder.TimeSeriesToInclude)
                    {
                        if (numberOfIncludesAdded == 0)
                        {
                            queryBuilder
                            .AppendLine()
                            .Append("include ");
                        }

                        if (numberOfIncludesAdded > 0)
                        {
                            queryBuilder.Append(",");
                        }

                        var token = TimeSeriesIncludesToken.Create(string.Empty, timeSeriesRange);
                        token.WriteTo(queryBuilder);

                        numberOfIncludesAdded++;
                    }
                }
            }

            criteria.Query = queryBuilder.ToString();
            return(criteria);
        }
Ejemplo n.º 60
0
 /// <summary>
 /// Creates a FunctionParameterToken
 /// </summary>
 /// <param name="parameterName">the name of this parameter</param>
 /// <param name="valueToken">the syntactically parsed value</param>
 public FunctionParameterToken(string parameterName, QueryToken valueToken)
 {
     this.parameterName = parameterName;
     this.valueToken    = valueToken;
 }