public void KindIsBinaryOperatorNode()
 {
     ConstantNode left = new ConstantNode(1);
     ConstantNode right = new ConstantNode(2);
     BinaryOperatorNode operatorNode = new BinaryOperatorNode(BinaryOperatorKind.Add, left, right);
     operatorNode.InternalKind.Should().Be(InternalQueryNodeKind.BinaryOperator);
 }
        public void ToODataString_EscapesThe_Uri()
        {

            //updatedat gt datetimeoffset'2014-04-04T07:00:00.0000000+00:00'
            var datetime1 = new ConstantNode(new DateTimeOffset(2014, 4, 4, 7, 0, 0, TimeSpan.FromHours(0)));
            var updatedAt = new MemberAccessNode(null, "updatedat");
            var gt1 = new BinaryOperatorNode(BinaryOperatorKind.GreaterThan, updatedAt, datetime1);

            // updatedat gt datetime'2014-04-04T07:0:0.000Z'
            var datetime2 = new ConstantNode(new DateTime(2014, 4, 4, 7, 0, 0, DateTimeKind.Utc));
            var someDate = new MemberAccessNode(null, "someDate");
            var gt2 = new BinaryOperatorNode(BinaryOperatorKind.GreaterThan, someDate, datetime2);

            // startswith(text,'this&''%%=,?#')
            var text = new MemberAccessNode(null, "text");
            var value = new ConstantNode("this&'%%=,?#");
            var startswith = new FunctionCallNode("startswith", new QueryNode[] { text, value });

            //updatedat gt datetimeoffset'2014-04-04T07:00:00.0000000+00:00' and startswith(text,'this&''%%=,?#')
            var and2 = new BinaryOperatorNode(BinaryOperatorKind.And, gt2, startswith);

            var and1 = new BinaryOperatorNode(BinaryOperatorKind.And, gt1, and2);

            var desc = new MobileServiceTableQueryDescription("someTable") { Filter = and1 };
            Assert.AreEqual(desc.ToODataString(), EscapedODataString);
        }
Exemplo n.º 3
0
        public static GraphNode operator *(NodeFuture future, string constant)
        {
            var node = new ConstantNode(constant);
            node.ActivationFunction = future.ActivationFunction;

            return future.Parent.Slash(node);
        }
Exemplo n.º 4
0
		public void Setup()
		{
			_customer = new Customer {Preferred = true};

			_actionNode = new ActionNode<Customer>(x => Trace.WriteLine("Called for " + x.Element.Object.Preferred));

			_constantNode = new ConstantNode<Customer>();

			_agenda = new PriorityQueueAgenda();

			_context = MockRepository.GenerateMock<RuleContext<Customer>>();
			var element = MockRepository.GenerateMock<SessionElement<Customer>>();
			element.Stub(x => x.Object).Return(_customer);
			_context.Stub(x => x.Element).Return(element);

			_context.Expect(x => x.EnqueueAgendaAction(0, null))
				.IgnoreArguments()
				.Repeat.AtLeastOnce()
				.WhenCalled(invocation =>
					{
						var priority = (int) invocation.Arguments[0];
						var action = invocation.Arguments[1] as Action;

						_agenda.Add(priority, action);
					});
		}
Exemplo n.º 5
0
        public GraphNode MapToGraph(string routePattern)
        {
            if (string.IsNullOrEmpty(routePattern))
            {
                throw new ArgumentException("Route pattern cannot be null", "routePattern");
            }

            if (routePattern == "/")
            {
                return null;
            }

            var parts = routePattern.Split('/').Where(o => !string.IsNullOrEmpty(o.Trim()));

            GraphNode node = null;
            foreach (var part in parts)
            {
                var thisNode = new ConstantNode(part);
                if (node != null)
                {
                    node.Slash(thisNode);
                }

                node = thisNode;
            }

            return node;
        }
 public void RightShouldBeSetCorrectly()
 {
     ConstantNode left = new ConstantNode(1);
     ConstantNode right = new ConstantNode(2);
     BinaryOperatorNode operatorNode = new BinaryOperatorNode(BinaryOperatorKind.Add, left, right);
     operatorNode.Right.Should().Be(right);
 }
 public void IfTypesCannotPromoteErrorIsThrown()
 {
     SingleValueNode node = new ConstantNode(7);
     var targetType = EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.GeographyMultiLineString, false);
     Action convertMethod = () => MetadataBindingUtils.ConvertToTypeIfNeeded(node, targetType);
     convertMethod.ShouldThrow<ODataException>().WithMessage(ODataErrorStrings.MetadataBinder_CannotConvertToType(node.TypeReference.FullName(), targetType.FullName()));
 }
 public void TypeReferenceIsSetCorrectlyFromOperands()
 {
     ConstantNode left = new ConstantNode(1);
     ConstantNode right = new ConstantNode(2);
     BinaryOperatorNode operatorNode = new BinaryOperatorNode(BinaryOperatorKind.Add, left, right);
     operatorNode.TypeReference.FullName().Should().Be("Edm.Int32");
 }
Exemplo n.º 9
0
        public void Setup()
        {
            _called = null;

            var productionNode = new DelegateProductionNode<A>(16, (session,x) => _called = x);

            var constantNode = new ConstantNode<A>(42);

            var joinNode = new JoinNode<A>(69, constantNode);
            joinNode.AddActivation(productionNode);

            var engine = new OdoyuleRulesEngine(new OdoyuleRuntimeConfigurator());

            AlphaNode<A> alphaNode = engine.GetAlphaNode<A>();
            alphaNode.AddActivation(joinNode);

            using (Session session = engine.CreateSession())
            {
                session.Add(new A());
                session.Run();
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Promote the left and right operand types, supports enum property and string constant scenario.
        /// </summary>
        /// <param name="binaryOperatorKind">the operator kind</param>
        /// <param name="leftNode">the left operand</param>
        /// <param name="rightNode">the right operand</param>
        /// <param name="typeReference">type reference for the result BinaryOperatorNode.</param>
        public override void PromoteBinaryOperandTypes(
               BinaryOperatorKind binaryOperatorKind,
               ref SingleValueNode leftNode,
               ref SingleValueNode rightNode,
               out IEdmTypeReference typeReference)
        {
            typeReference = null;

            if (leftNode.TypeReference != null && rightNode.TypeReference != null)
            {
                if ((leftNode.TypeReference.IsEnum()) && (rightNode.TypeReference.IsString()) && rightNode is ConstantNode)
                {
                    string text = ((ConstantNode)rightNode).Value as string;
                    ODataEnumValue val;
                    IEdmTypeReference typeRef = leftNode.TypeReference;

                    if (TryParseEnum(typeRef.Definition as IEdmEnumType, text, out val))
                    {
                        rightNode = new ConstantNode(val, text, typeRef);
                        return;
                    }
                }
                else if ((rightNode.TypeReference.IsEnum()) && (leftNode.TypeReference.IsString()) && leftNode is ConstantNode)
                {
                    string text = ((ConstantNode)leftNode).Value as string;
                    ODataEnumValue val;
                    IEdmTypeReference typeRef = rightNode.TypeReference;
                    if (TryParseEnum(typeRef.Definition as IEdmEnumType, text, out val))
                    {
                        leftNode = new ConstantNode(val, text, typeRef);
                        return;
                    }
                }
            }

            // fallback
            base.PromoteBinaryOperandTypes(binaryOperatorKind, ref leftNode, ref rightNode, out typeReference);
        }
Exemplo n.º 11
0
        public void Setup()
        {
            _called = null;

            var configurator = new OdoyuleRuntimeConfigurator();

            var productionNode = new DelegateProductionNode<Tuple<A,B>>(16, (session, x) => _called = x);

            var constantNode = new ConstantNode<A>(42);

            JoinNode<A> joinNodeA = configurator.CreateNode(id => new JoinNode<A>(id, constantNode));

            var constantNode2 = new ConstantNode<B>(27);

            JoinNode<B> joinNodeB = configurator.CreateNode(id => new JoinNode<B>(id, constantNode2));

            OuterJoinNode<A, B> outerJoinNode = configurator.CreateNode(id => new OuterJoinNode<A, B>(id, joinNodeB));
            outerJoinNode.AddActivation(productionNode);

            joinNodeA.AddActivation(outerJoinNode);

            var engine = new OdoyuleRulesEngine(configurator);

            AlphaNode<A> alphaNode = engine.GetAlphaNode<A>();
            alphaNode.AddActivation(joinNodeA);

            AlphaNode<B> alphaNodeB = engine.GetAlphaNode<B>();
            alphaNodeB.AddActivation(joinNodeB);

            using (Session session = engine.CreateSession())
            {
                session.Add(new A());
                session.Add(new B());
                session.Run();
            }
        }
Exemplo n.º 12
0
 public void SourceIsSetCorrectly()
 {
     ConstantNode source = new ConstantNode(1);
     ConvertNode convertNode = new ConvertNode(source, source.TypeReference);
     convertNode.Source.As<ConstantNode>().Value.As<int>().Should().Be(1);
 }
Exemplo n.º 13
0
 public void KindIsSetToConvertNode()
 {
     ConstantNode source = new ConstantNode(1);
     ConvertNode convertNode = new ConvertNode(source, EdmCoreModel.Instance.GetInt64(true));
     convertNode.InternalKind.Should().Be(InternalQueryNodeKind.Convert);
 }
Exemplo n.º 14
0
 public void TypeIsSetFromTheTypeOfTheValue()
 {
     ConstantNode constantNode = new ConstantNode(1);
     constantNode.TypeReference.FullName().Should().Be("Edm.Int32");
 }
        public override void ValidateConstantNode(ConstantNode constantNode, ODataValidationSettings settings)
        {
            // Validate that client did not send a big constant in the query
            if (Convert.ToInt32(constantNode.Value) > 100)
            {
                throw new ODataException("Any constant that is more than 100 is not allowed.");
            }

            base.ValidateConstantNode(constantNode, settings);
        }
            private QueryNode ParseFunctionCallNode()
            {
                BinaryOperatorNode binaryNode = null;
                FunctionCallNode   node       = null;

                var stack = new Stack <FunctionCallNode>();

                while (_tokens.Count > 0)
                {
                    Token token = _tokens.Dequeue();

                    switch (token.TokenType)
                    {
                    case TokenType.Base64Binary:
                    case TokenType.Date:
                    case TokenType.DateTimeOffset:
                    case TokenType.Decimal:
                    case TokenType.Double:
                    case TokenType.Duration:
                    case TokenType.EdmType:
                    case TokenType.Enum:
                    case TokenType.False:
                    case TokenType.Guid:
                    case TokenType.Integer:
                    case TokenType.Null:
                    case TokenType.Single:
                    case TokenType.String:
                    case TokenType.TimeOfDay:
                    case TokenType.True:
                        ConstantNode constantNode = ConstantNodeParser.ParseConstantNode(token);

                        if (stack.Count > 0)
                        {
                            stack.Peek().AddParameter(constantNode);
                        }
                        else
                        {
                            if (binaryNode == null)
                            {
                                throw ODataException.BadRequest(ExceptionMessage.GenericUnableToParseFilter, "$filter");
                            }

                            binaryNode.Right = constantNode;
                        }

                        break;

                    case TokenType.BinaryOperator:
                        binaryNode = new BinaryOperatorNode(node, token.Value.ToBinaryOperatorKind(), null);
                        break;

                    case TokenType.CloseParentheses:
                        if (_groupingDepth == 0)
                        {
                            throw ODataException.BadRequest(ExceptionMessage.UnableToParseFilter($"the closing parenthesis not expected", token.Position), "$filter");
                        }

                        _groupingDepth--;

                        if (stack.Count > 0)
                        {
                            FunctionCallNode lastNode = stack.Pop();

                            if (stack.Count > 0)
                            {
                                stack.Peek().AddParameter(lastNode);
                            }
                            else
                            {
                                if (binaryNode != null)
                                {
                                    binaryNode.Right = lastNode;
                                }
                                else
                                {
                                    node = lastNode;
                                }
                            }
                        }

                        break;

                    case TokenType.Comma:
                        if (_tokens.Count > 0 && _tokens.Peek().TokenType == TokenType.CloseParentheses)
                        {
                            // If there is a comma in a function call, there should be another parameter followed by a closing comma
                            throw ODataException.BadRequest(ExceptionMessage.UnableToParseFilter($"the function {node?.Name} has a missing parameter or extra comma", token.Position), "$filter");
                        }

                        break;

                    case TokenType.FunctionName:
                        node = new FunctionCallNode(token.Value);
                        break;

                    case TokenType.OpenParentheses:
                        if (_tokens.Count > 0 && _tokens.Peek().TokenType == TokenType.CloseParentheses)
                        {
                            // All OData functions have at least 1 or 2 parameters
                            throw ODataException.BadRequest(ExceptionMessage.UnableToParseFilter($"the function {node?.Name} has no parameters specified", token.Position), "$filter");
                        }

                        _groupingDepth++;
                        stack.Push(node);
                        break;

                    case TokenType.PropertyName:
                        var propertyAccessNode = new PropertyAccessNode(PropertyPath.For(token.Value, _model));

                        if (stack.Count > 0)
                        {
                            stack.Peek().AddParameter(propertyAccessNode);
                        }
                        else
                        {
                            if (binaryNode == null)
                            {
                                throw ODataException.BadRequest(ExceptionMessage.GenericUnableToParseFilter, "$filter");
                            }

                            binaryNode.Right = propertyAccessNode;
                        }

                        break;

                    default:
                        throw ODataException.BadRequest(ExceptionMessage.UnableToParseFilter($"unexpected {token.Value}", token.Position), "$filter");
                    }
                }

                if (binaryNode != null)
                {
                    return(binaryNode);
                }

                return(node);
            }
Exemplo n.º 17
0
        public void Setup()
        {
            _called = null;

            var configurator = new RuntimeConfiguratorImpl();

            var productionNode = new DelegateProductionNode<A>(16, (session,x) => _called = x);

            var constantNode = new ConstantNode<A>(42);

            var joinNode = configurator.CreateNode(id => new JoinNode<A>(id, constantNode));

            var constantNode2 = new ConstantNode<A>(27);

            var joinNode2 = configurator.CreateNode(id => new JoinNode<A>(id, constantNode2));
            joinNode2.AddActivation(productionNode);

            joinNode.AddActivation(joinNode2);

            var engine = new OdoyuleRulesEngine(configurator);

            AlphaNode<A> alphaNode = engine.GetAlphaNode<A>();
            alphaNode.AddActivation(joinNode);

            using (StatefulSession session = engine.CreateSession())
            {
                session.Add(new A());
                session.Run();
            }
        }
Exemplo n.º 18
0
 public static GraphNode operator /(RouteGlue state, string other)
 {
     var node = new ConstantNode(other);
     return node;
 }
Exemplo n.º 19
0
 public override IEnumerable <string> Visit(ConstantNode nodeIn)
 {
     return(_emptyString);
 }
Exemplo n.º 20
0
        /// <summary>
        /// If the source node is not of the specified type, then we check if type promotion is possible and inject a convert node.
        /// If the source node is the same type as the target type (or if the target type is null), we just return the source node as is.
        /// </summary>
        /// <param name="source">The source node to apply the convertion to.</param>
        /// <param name="targetTypeReference">The target primitive type. May be null - this method will do nothing in that case.</param>
        /// <returns>The converted query node, or the original source node unchanged.</returns>
        internal static SingleValueNode ConvertToTypeIfNeeded(SingleValueNode source, IEdmTypeReference targetTypeReference)
        {
            Debug.Assert(source != null, "source != null");

            if (targetTypeReference == null)
            {
                return(source);
            }

            if (source.TypeReference != null)
            {
                if (source.TypeReference.IsEquivalentTo(targetTypeReference))
                {
                    // For source is type definition, if source's underlying type == target type.
                    // We create a conversion node from source to its underlying type (target type)
                    // so that the service can convert value of source clr type to underlying clr type.
                    if (source.TypeReference.IsTypeDefinition())
                    {
                        return(new ConvertNode(source, targetTypeReference));
                    }

                    return(source);
                }

                if (!TypePromotionUtils.CanConvertTo(source, source.TypeReference, targetTypeReference))
                {
                    throw new ODataException(ODataErrorStrings.MetadataBinder_CannotConvertToType(source.TypeReference.ODataFullName(), targetTypeReference.ODataFullName()));
                }
                else
                {
                    ConstantNode constantNode = source as ConstantNode;

                    if (source.TypeReference.IsEnum() && constantNode != null)
                    {
                        return(new ConstantNode(constantNode.Value, ODataUriUtils.ConvertToUriLiteral(constantNode.Value, ODataVersion.V4), targetTypeReference));
                    }

                    object primitiveValue;
                    if (MetadataUtilsCommon.TryGetConstantNodePrimitiveLDMF(source, out primitiveValue) && (primitiveValue != null))
                    {
                        // L F D M types : directly create a ConvertNode.
                        // 1. NodeToExpressionTranslator.cs won't allow implicitly converting single/double to decimal, which should be done here at Node tree level.
                        // 2. And prevent losing precision in float -> double, e.g. (double)1.234f => 1.2339999675750732d not 1.234d
                        object primitiveValue2 = ODataUriConversionUtils.CoerceNumericType(primitiveValue, targetTypeReference.AsPrimitive().Definition as IEdmPrimitiveType);

                        if (string.IsNullOrEmpty(constantNode.LiteralText))
                        {
                            return(new ConstantNode(primitiveValue2));
                        }

                        return(new ConstantNode(primitiveValue2, constantNode.LiteralText));
                    }
                    else
                    {
                        // other type conversion : ConvertNode
                        return(new ConvertNode(source, targetTypeReference));
                    }
                }
            }
            else
            {
                // If the source doesn't have a type (possibly an open property), then it's possible to convert it
                // cause we don't know for sure.
                return(new ConvertNode(source, targetTypeReference));
            }
        }
Exemplo n.º 21
0
 public override object Visit(ConstantNode nodeIn)
 {
     return(nodeIn.Value);
 }
Exemplo n.º 22
0
        public static async Task <IEnumerable <TKey> > TryFilterNode <TKey, TValue>(SingleValueNode node, bool notIsApplied, IReliableStateManager stateManager, string dictName, CancellationToken cancellationToken)
            where TKey : IComparable <TKey>, IEquatable <TKey>
        {
            if (node is UnaryOperatorNode asUONode)
            {
                // If NOT, negate tree and return isFilterable
                if (asUONode.OperatorKind == Microsoft.Data.OData.Query.UnaryOperatorKind.Not)
                {
                    if (isFilterableNode2(asUONode.Operand, !notIsApplied))
                    {
                        return(await TryFilterNode <TKey, TValue>(asUONode.Operand, !notIsApplied, stateManager, dictName, cancellationToken));
                    }

                    return(null);
                }
                else
                {
                    throw new NotSupportedException("Does not support the Negate unary operator");
                }
            }

            else if (node is BinaryOperatorNode asBONode)
            {
                // Filterable(A) AND Filterable(B)      => Intersect(Filter(A), Filter(B))
                // !Filterable(A) AND Filterable(B)     => Filter(B)
                // Filterable(A) AND !Filterable(B)     => Filter(A)
                // !Filterable(A) AND !Filterable(B)    => NF
                if ((asBONode.OperatorKind == BinaryOperatorKind.And && !notIsApplied) ||
                    (asBONode.OperatorKind == BinaryOperatorKind.Or && notIsApplied))
                {
                    bool leftFilterable  = isFilterableNode2(asBONode.Left, notIsApplied);
                    bool rightFilterable = isFilterableNode2(asBONode.Right, notIsApplied);

                    // Both are filterable: intersect
                    if (leftFilterable && rightFilterable)
                    {
                        IEnumerable <TKey> leftKeys = await TryFilterNode <TKey, TValue>(asBONode.Left, notIsApplied, stateManager, dictName, cancellationToken);

                        IEnumerable <TKey> rightKeys = await TryFilterNode <TKey, TValue>(asBONode.Right, notIsApplied, stateManager, dictName, cancellationToken);

                        if (leftKeys != null && rightKeys != null)
                        {
                            return(new IEnumerableUtility.IntersectEnumerable <TKey>(leftKeys, rightKeys));
                        }
                        else if (leftKeys != null)
                        {
                            return(await TryFilterNode <TKey, TValue>(asBONode.Left, notIsApplied, stateManager, dictName, cancellationToken));
                        }
                        else if (rightKeys != null)
                        {
                            return(await TryFilterNode <TKey, TValue>(asBONode.Right, notIsApplied, stateManager, dictName, cancellationToken));
                        }
                        else
                        {
                            return(null); //Both queries were candidates for filtering but the filterable indexes did not exist
                        }
                    }
                    else if (leftFilterable)
                    {
                        return(await TryFilterNode <TKey, TValue>(asBONode.Left, notIsApplied, stateManager, dictName, cancellationToken));
                    }
                    else if (rightFilterable)
                    {
                        return(await TryFilterNode <TKey, TValue>(asBONode.Right, notIsApplied, stateManager, dictName, cancellationToken));
                    }
                    else
                    {
                        return(null); // This should never be hit because if !Filterable(Left) && !Filterable(Right) => !Filterable(Me)
                    }
                }
                // Filterable(A) OR Filterable(B)      => Union(Filter(A), Filter(B))
                // !Filterable(A) OR Filterable(B)     => NF
                // Filterable(A) OR !Filterable(B)     => NF
                // !Filterable(A) OR !Filterable(B)    => NF
                else if ((asBONode.OperatorKind == BinaryOperatorKind.Or && !notIsApplied) ||
                         (asBONode.OperatorKind == BinaryOperatorKind.And && notIsApplied))
                {
                    bool leftFilterable  = isFilterableNode2(asBONode.Left, notIsApplied);
                    bool rightFilterable = isFilterableNode2(asBONode.Right, notIsApplied);

                    // Both are filterable queries: intersect, however if they are null that means there is no index for this property
                    if (leftFilterable && rightFilterable)
                    {
                        IEnumerable <TKey> leftKeys = await TryFilterNode <TKey, TValue>(asBONode.Left, notIsApplied, stateManager, dictName, cancellationToken);

                        IEnumerable <TKey> rightKeys = await TryFilterNode <TKey, TValue>(asBONode.Right, notIsApplied, stateManager, dictName, cancellationToken);

                        if (leftKeys != null && rightKeys != null)
                        {
                            return(new IEnumerableUtility.UnionEnumerable <TKey>(leftKeys, rightKeys));
                        }
                    }

                    return(null);
                }
                // If Equals, >=, >, <, <=
                else if ((asBONode.OperatorKind == BinaryOperatorKind.Equal && !notIsApplied) ||
                         (asBONode.OperatorKind == BinaryOperatorKind.NotEqual && notIsApplied) ||
                         (asBONode.OperatorKind == BinaryOperatorKind.GreaterThan) ||
                         (asBONode.OperatorKind == BinaryOperatorKind.GreaterThanOrEqual) ||
                         (asBONode.OperatorKind == BinaryOperatorKind.LessThan) ||
                         (asBONode.OperatorKind == BinaryOperatorKind.LessThanOrEqual))
                {
                    // Resolve the arbitrary order of the request
                    SingleValuePropertyAccessNode valueNode = asBONode.Left is SingleValuePropertyAccessNode ? asBONode.Left as SingleValuePropertyAccessNode : asBONode.Right as SingleValuePropertyAccessNode;
                    ConstantNode constantNode = asBONode.Left is ConstantNode ? asBONode.Left as ConstantNode : asBONode.Right as ConstantNode;

                    // If constant node is LEFT and AccessNode is RIGHT, we should flip the OperatorKind to standardize to "access operator constant"
                    // ie 21 gt Age is logical opposite of Age lt 21
                    BinaryOperatorKind operatorKind = asBONode.OperatorKind;
                    if (asBONode.Left is ConstantNode)
                    {
                        if (operatorKind == BinaryOperatorKind.GreaterThan)
                        {
                            operatorKind = BinaryOperatorKind.LessThan;
                        }
                        else if (operatorKind == BinaryOperatorKind.LessThan)
                        {
                            operatorKind = BinaryOperatorKind.GreaterThan;
                        }
                        else if (operatorKind == BinaryOperatorKind.LessThanOrEqual)
                        {
                            operatorKind = BinaryOperatorKind.GreaterThanOrEqual;
                        }
                        else if (operatorKind == BinaryOperatorKind.GreaterThanOrEqual)
                        {
                            operatorKind = BinaryOperatorKind.LessThanOrEqual;
                        }
                    }

                    string propertyName = valueNode.Property.Name;
                    Type   propertyType = constantNode.Value.GetType(); //Possible reliance on type bad if name of property and provided type conflict?

                    MethodInfo getIndexedDictionaryByPropertyName = typeof(ReliableStateExtensions).GetMethod("GetIndexedDictionaryByPropertyName", BindingFlags.NonPublic | BindingFlags.Static);
                    getIndexedDictionaryByPropertyName = getIndexedDictionaryByPropertyName.MakeGenericMethod(new Type[] { typeof(TKey), typeof(TValue), propertyType });
                    Task  indexedDictTask = (Task)getIndexedDictionaryByPropertyName.Invoke(null, new object[] { stateManager, dictName, propertyName });
                    await indexedDictTask;
                    var   indexedDict = indexedDictTask.GetType().GetProperty("Result").GetValue(indexedDictTask);

                    if (indexedDict == null)
                    {
                        return(null); // Filter does not exist or dictionary does not exist
                    }

                    MethodInfo filterHelper = typeof(ReliableStateExtensions).GetMethod("FilterHelper", BindingFlags.Public | BindingFlags.Static);
                    filterHelper = filterHelper.MakeGenericMethod(new Type[] { typeof(TKey), typeof(TValue), propertyType });
                    Task  filterHelperTask = (Task)filterHelper.Invoke(null, new object[] { indexedDict, constantNode.Value, operatorKind, notIsApplied, cancellationToken, stateManager, propertyName });
                    await filterHelperTask;
                    return((IEnumerable <TKey>)filterHelperTask.GetType().GetProperty("Result").GetValue(filterHelperTask));
                }
                // We choose to mark NotEquals as unfilterable. Theoretically with indexes with low number of keys may be slightly faster than not-filtering
                // But generally is same order of magnitude as not using filters
                else if ((asBONode.OperatorKind == BinaryOperatorKind.Equal && notIsApplied) ||
                         (asBONode.OperatorKind == BinaryOperatorKind.NotEqual && !notIsApplied))
                {
                    return(null);
                }
                else
                {
                    throw new NotSupportedException("Does not support Add, Subtract, Modulo, Multiply, Divide operations.");
                }
            }
            else if (node is ConvertNode asCNode)
            {
                return(await TryFilterNode <TKey, TValue>(asCNode.Source, notIsApplied, stateManager, dictName, cancellationToken));
            }
            else
            {
                throw new NotSupportedException("Only supports Binary and Unary operator nodes");
            }
        }
Exemplo n.º 23
0
 public void AddData(ConstantNode cons)
 {
     data.Add(cons);
 }
Exemplo n.º 24
0
 public override int Visit(ConstantNode nodeIn)
 {
     return(0);
 }
        /// <summary>
        /// This method can be replaced by MetadataUtilsCommon.TryGetConstantNodePrimitiveLDMF() and ODataUriConversionUtils.CoerceNumericType(), 
        /// which however is internal and inaccessible, so copy the same logic here for L F D M values.
        /// </summary>
        /// <param name="node">ConstantNode</param>
        /// <param name="targetType">Type</param>
        /// <returns>ConstantNode in correct type.</returns>
        private ConstantNode EnsureCorrectTypeAndPrecisionForLFDM(ConstantNode node, Type targetType)
        {
            if (node.Value != null)
            {
                // L F D M types :
                // 1. CLR won't allow implicitly converting single/double to decimal, which should be done here.
                // 2. And prevent losing precision in float -> double, e.g. (double)1.234f will be 1.2339999675750732d not 1.234d
                if (node.TypeReference.TypeKind() == EdmTypeKind.Primitive)
                {
                    IEdmPrimitiveTypeReference tmp = node.TypeReference.AsPrimitive();
                    IEdmPrimitiveType primitiveType = tmp.Definition as IEdmPrimitiveType;
                    switch (primitiveType.PrimitiveKind)
                    {
                        case EdmPrimitiveTypeKind.Single:
                            if ((targetType == typeof(double)) || (targetType == typeof(double?)))
                            {
                                return new ConstantNode(double.Parse(node.Value.ToString(), CultureInfo.InvariantCulture));
                            }
                            else if ((targetType == typeof(decimal)) || (targetType == typeof(decimal?)))
                            {
                                return new ConstantNode(decimal.Parse(node.Value.ToString(), CultureInfo.InvariantCulture));
                            }

                            break;
                        case EdmPrimitiveTypeKind.Double:
                            if ((targetType == typeof(decimal)) || (targetType == typeof(decimal?)))
                            {
                                return new ConstantNode(decimal.Parse(node.Value.ToString(), CultureInfo.InvariantCulture));
                            }

                            break;
                        default:
                            break;
                    }
                }
            }

            return node;
        }
Exemplo n.º 26
0
        public void BindLiteralShouldReturnIntValue()
        {
            ConstantNode result = LiteralBinder.BindLiteral(new LiteralToken(5)) as ConstantNode;

            Assert.Equal(5, result.Value);
        }
 public override T Visit(ConstantNode nodeIn)
 {
     SkipDebuggerBreak(nodeIn);                                                        return(Visited);
 }
Exemplo n.º 28
0
        /// <summary>
        /// Parse the constant entity collection node.
        /// </summary>
        /// <param name="nodeIn">The input constant node.</param>
        /// <returns>The parsed object.</returns>
        private object ParseEntityCollection(ConstantNode nodeIn)
        {
            ODataMessageReaderSettings settings = new ODataMessageReaderSettings();
            InMemoryMessage            message  = new InMemoryMessage()
            {
                Stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nodeIn.LiteralText)),
            };

            var entityType =
                ((nodeIn.TypeReference.Definition as IEdmCollectionType).ElementType as IEdmEntityTypeReference)
                .Definition as IEdmEntityType;
            object     list      = null;
            MethodInfo addMethod = null;

            using (
                ODataMessageReader reader = new ODataMessageReader(message as IODataRequestMessage, settings,
                                                                   this.UriParser.Model))
            {
                if (nodeIn.LiteralText.Contains("@odata.id"))
                {
                    ODataEntityReferenceLinks referenceLinks = reader.ReadEntityReferenceLinks();
                    foreach (var referenceLink in referenceLinks.Links)
                    {
                        var queryContext = new QueryContext(this.UriParser.ServiceRoot, referenceLink.Url,
                                                            this.DataSource.Model);
                        var target = queryContext.ResolveQuery(this.DataSource);

                        if (list == null)
                        {
                            // create the list. This would require the first type is not derived type.
                            Type listType = typeof(List <>).MakeGenericType(target.GetType());
                            addMethod = listType.GetMethod("Add");
                            list      = Activator.CreateInstance(listType);
                        }

                        addMethod.Invoke(list, new[] { target });
                    }

                    return(list);
                }

                var feedReader = reader.CreateODataFeedReader(
                    new EdmEntitySet(new EdmEntityContainer("NS", "Test"), "TestType", entityType),
                    entityType);
                ODataEntry entry = null;
                while (feedReader.Read())
                {
                    if (feedReader.State == ODataReaderState.EntryEnd)
                    {
                        entry = feedReader.Item as ODataEntry;
                        object item = ODataObjectModelConverter.ConvertPropertyValue(entry);


                        if (list == null)
                        {
                            // create the list. This would require the first type is not derived type.
                            var  type     = EdmClrTypeUtils.GetInstanceType(entry.TypeName);
                            Type listType = typeof(List <>).MakeGenericType(type);
                            addMethod = listType.GetMethod("Add");
                            list      = Activator.CreateInstance(listType);
                        }

                        addMethod.Invoke(list, new[] { item });
                    }
                }
                return(list);
            }
        }
        private void UpdateDeltaToken()
        {
            this.deltaToken = this.maxUpdatedAt;

            if (this.ordered)
            {
                this.Query.Ordering.Clear();
                this.Query.Ordering.Add(orderByUpdatedAtNode);
            }
            // .NET runtime system properties are of datetimeoffset type so we'll use the datetimeoffset odata token
            QueryNode tokenNode = new ConstantNode(deltaToken);
            QueryNode greaterThanDeltaNode = new BinaryOperatorNode(BinaryOperatorKind.GreaterThanOrEqual, updatedAtNode, tokenNode);
            if (this.originalFilter == null)
            {
                this.Query.Filter = greaterThanDeltaNode;
            }
            else
            {
                var originalFilterAndGreaterThanDeltaNode = new BinaryOperatorNode(BinaryOperatorKind.And, this.originalFilter, greaterThanDeltaNode);
                this.Query.Filter = originalFilterAndGreaterThanDeltaNode;
            }
        }
Exemplo n.º 30
0
        public void ODataUriBuilderWithEntitySet()
        {
            Uri            fullUri        = new Uri("http://www.example.com/People?$filter=MyDog%2FColor%20eq%20%27Brown%27&$select=ID&$expand=MyDog%2CMyCat/$ref&$orderby=ID&$top=1&$skip=2&$count=true&$search=FA");
            ODataUriParser odataUriParser = new ODataUriParser(this.GetModel(), serviceRoot, fullUri);

            odataUriParser.UrlKeyDelimiter = ODataUrlKeyDelimiter.Parentheses;
            SetODataUriParserSettingsTo(this.settings, odataUriParser.Settings);
            ODataUri odataUri = odataUriParser.ParseUri();

            //verify path
            EntitySetSegment entitySet = (EntitySetSegment)odataUri.Path.FirstSegment;

            Assert.AreEqual(entitySet.EntitySet.Name, "People");
            Assert.AreEqual(odataUri.Path.Count, 1);

            //verify $filter
            BinaryOperatorNode            binaryOperator      = (BinaryOperatorNode)odataUri.Filter.Expression;
            SingleValuePropertyAccessNode singleValueProperty = (SingleValuePropertyAccessNode)binaryOperator.Left;
            SingleNavigationNode          singleNavigation    = (SingleNavigationNode)singleValueProperty.Source;
            ConstantNode constantNode = (ConstantNode)binaryOperator.Right;

            Assert.AreEqual(binaryOperator.OperatorKind, BinaryOperatorKind.Equal);
            Assert.AreEqual(singleValueProperty.Property.Name, "Color");
            Assert.AreEqual(singleNavigation.NavigationProperty.Name, "MyDog");
            Assert.AreEqual(constantNode.LiteralText, "'Brown'");

            //verify $select and $expand
            IEnumerable <SelectItem> selectItems = odataUri.SelectAndExpand.SelectedItems;
            IEnumerable <ExpandedNavigationSelectItem> expandedNavigationSelectItem = selectItems.Where(I => I.GetType() == typeof(ExpandedNavigationSelectItem)).OfType <ExpandedNavigationSelectItem>();
            IEnumerable <ExpandedReferenceSelectItem>  expandedReferenceSelectItem  = selectItems.Where(I => I.GetType() == typeof(ExpandedReferenceSelectItem)).OfType <ExpandedReferenceSelectItem>();
            IEnumerable <PathSelectItem> pathSelectItem = selectItems.Where(I => I.GetType() == typeof(PathSelectItem)).OfType <PathSelectItem>();

            Assert.AreEqual(expandedNavigationSelectItem.Count(), 1);
            Assert.AreEqual(expandedReferenceSelectItem.Count(), 1);
            Assert.AreEqual(pathSelectItem.Count(), 2);
            NavigationPropertySegment navigationProperty = (NavigationPropertySegment)expandedNavigationSelectItem.First().PathToNavigationProperty.FirstSegment;

            Assert.AreEqual(navigationProperty.NavigationProperty.Name, "MyDog");
            navigationProperty = (NavigationPropertySegment)expandedReferenceSelectItem.First().PathToNavigationProperty.FirstSegment;
            Assert.AreEqual(navigationProperty.NavigationProperty.Name, "MyCat");

            //verify $orderby
            SingleValuePropertyAccessNode orderby = (SingleValuePropertyAccessNode)odataUri.OrderBy.Expression;

            Assert.AreEqual(orderby.Property.Name, "ID");

            //verify $top
            Assert.AreEqual(odataUri.Top, 1);

            //verify $skip
            Assert.AreEqual(odataUri.Skip, 2);

            //verify $count
            Assert.AreEqual(odataUri.QueryCount, true);

            //verify $search
            SearchTermNode searchTermNode = (SearchTermNode)odataUri.Search.Expression;

            Assert.AreEqual(searchTermNode.Text, "FA");

            Uri actualUri = odataUri.BuildUri(ODataUrlKeyDelimiter.Parentheses);

            Assert.AreEqual(new Uri("http://www.example.com/People?$filter=MyDog%2FColor%20eq%20%27Brown%27&$select=ID%2CMyCat&$expand=MyDog%2CMyCat%2F%24ref&$orderby=ID&$top=1&$skip=2&$count=true&$search=FA"), actualUri);

            actualUri = odataUri.BuildUri(ODataUrlKeyDelimiter.Slash);
            Assert.AreEqual(new Uri("http://www.example.com/People?$filter=MyDog%2FColor%20eq%20%27Brown%27&$select=ID%2CMyCat&$expand=MyDog%2CMyCat%2F%24ref&$orderby=ID&$top=1&$skip=2&$count=true&$search=FA"), actualUri);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Validate the arguments to either isof or cast
        /// </summary>
        /// <param name="state">the current state of the binding algorithm</param>
        /// <param name="isCast">flag to indicate which function we're validating</param>
        /// <param name="args">the list of arguments, which could be changed</param>
        /// <returns>the return type of the function.</returns>
        private static IEdmTypeReference ValidateIsOfOrCast(BindingState state, bool isCast, ref List <QueryNode> args)
        {
            if (args.Count != 1 && args.Count != 2)
            {
                throw new ODataErrorException(
                          ODataErrorStrings.MetadataBinder_CastOrIsOfExpressionWithWrongNumberOfOperands(args.Count));
            }

            ConstantNode typeArgument = args.Last() as ConstantNode;

            IEdmTypeReference returnType = null;

            if (typeArgument != null)
            {
                returnType = TryGetTypeReference(state.Model, typeArgument.Value as string, state.Configuration.Resolver);
            }

            if (returnType == null)
            {
                throw new ODataException(ODataErrorStrings.MetadataBinder_CastOrIsOfFunctionWithoutATypeArgument);
            }

            if (returnType.IsCollection())
            {
                throw new ODataException(ODataErrorStrings.MetadataBinder_CastOrIsOfCollectionsNotSupported);
            }

            // if we only have one argument, then add the implicit range variable as the first argument.
            if (args.Count == 1)
            {
                args = new List <QueryNode>()
                {
                    new EntityRangeVariableReferenceNode(
                        state.ImplicitRangeVariable.Name,
                        state.ImplicitRangeVariable as EntityRangeVariable),
                    args[0]
                };
            }
            else if (!(args[0] is SingleValueNode))
            {
                throw new ODataException(ODataErrorStrings.MetadataBinder_CastOrIsOfCollectionsNotSupported);
            }

            if (isCast && (args.Count == 2))
            {
                // throw if cast enum to not-string :
                if ((args[0].GetEdmTypeReference() is IEdmEnumTypeReference) &&
                    !string.Equals(typeArgument.Value as string, Microsoft.OData.Core.Metadata.EdmConstants.EdmStringTypeName, StringComparison.Ordinal))
                {
                    throw new ODataException(ODataErrorStrings.CastBinder_EnumOnlyCastToOrFromString);
                }

                // throw if cast not-string to enum :
                while (returnType is IEdmEnumTypeReference)
                {
                    IEdmTypeReference edmTypeReference = args[0].GetEdmTypeReference();
                    if (edmTypeReference == null)
                    {
                        // Support cast null to enum
                        break;
                    }

                    IEdmPrimitiveTypeReference referenceTmp = edmTypeReference as IEdmPrimitiveTypeReference;
                    if (referenceTmp != null)
                    {
                        IEdmPrimitiveType typeTmp = referenceTmp.Definition as IEdmPrimitiveType;
                        if ((typeTmp != null) && (typeTmp.PrimitiveKind == EdmPrimitiveTypeKind.String))
                        {
                            break;
                        }
                    }

                    throw new ODataException(ODataErrorStrings.CastBinder_EnumOnlyCastToOrFromString);
                }
            }

            if (isCast)
            {
                return(returnType);
            }
            else
            {
                return(EdmCoreModel.Instance.GetBoolean(true));
            }
        }
Exemplo n.º 32
0
        /// <summary>
        /// Tries to create a <see cref="ConstantNode"/> for the given token if it represents a literal.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="node">The node, if one was created.</param>
        /// <returns>Whether or not the token represented a literal.</returns>
        internal static bool TryCreateLiteral(ExpressionToken token, out ConstantNode node)
        {
            switch (token.Kind)
            {
            case ExpressionTokenKind.NullLiteral:
                node = new ConstantNode(null);
                break;

            case ExpressionTokenKind.BooleanLiteral:
                node = ParseTypedLiteral(typeof(bool), XmlConstants.EdmBooleanTypeName, token);
                break;

            case ExpressionTokenKind.DecimalLiteral:
                node = ParseTypedLiteral(typeof(decimal), XmlConstants.EdmDecimalTypeName, token);
                break;

            case ExpressionTokenKind.StringLiteral:
                node = ParseTypedLiteral(typeof(string), XmlConstants.EdmStringTypeName, token);
                break;

            case ExpressionTokenKind.Int64Literal:
                node = ParseTypedLiteral(typeof(Int64), XmlConstants.EdmInt64TypeName, token);
                break;

            case ExpressionTokenKind.IntegerLiteral:
                node = ParseTypedLiteral(typeof(Int32), XmlConstants.EdmInt32TypeName, token);
                break;

            case ExpressionTokenKind.DoubleLiteral:
                node = ParseTypedLiteral(typeof(double), XmlConstants.EdmDoubleTypeName, token);
                break;

            case ExpressionTokenKind.SingleLiteral:
                node = ParseTypedLiteral(typeof(Single), XmlConstants.EdmSingleTypeName, token);
                break;

            case ExpressionTokenKind.GuidLiteral:
                node = ParseTypedLiteral(typeof(Guid), XmlConstants.EdmGuidTypeName, token);
                break;

            case ExpressionTokenKind.BinaryLiteral:
                node = ParseTypedLiteral(typeof(byte[]), XmlConstants.EdmBinaryTypeName, token);
                break;

            case ExpressionTokenKind.DurationLiteral:
                node = ParseTypedLiteral(typeof(TimeSpan), XmlConstants.EdmDurationTypeName, token);
                break;

            case ExpressionTokenKind.DateTimeOffsetLiteral:
                node = ParseTypedLiteral(typeof(DateTimeOffset), XmlConstants.EdmDateTimeOffsetTypeName, token);
                break;

            case ExpressionTokenKind.GeographylLiteral:
                node = ParseTypedLiteral(typeof(Geography), XmlConstants.EdmGeographyTypeName, token);
                break;

            case ExpressionTokenKind.GeometryLiteral:
                node = ParseTypedLiteral(typeof(Geometry), XmlConstants.EdmGeometryTypeName, token);
                break;

            default:
                node = null;
                return(false);
            }

            Debug.Assert(token.IsLiteral, "Token must be a value.");
            return(true);
        }
Exemplo n.º 33
0
 public static string ToLogString(this ConstantNode node)
 {
     return(string.Format("Constant:[{0},{1}]", node.TypeReference, Object2String(node.Value)));
 }
 public virtual TResult Visit(ConstantNode node) => DefaultResult();
Exemplo n.º 35
0
 public void ValueIsSetCorrectly()
 {
     ConstantNode constantNode = new ConstantNode(1);
     constantNode.Value.As<int>().Should().Be(1);
 }
Exemplo n.º 36
0
 public override void ValidateConstantNode(ConstantNode constantNode, ODataValidationSettings settings)
 {
     IncrementCount("ValidateConstantQueryNode");
     base.ValidateConstantNode(constantNode, settings);
 }
Exemplo n.º 37
0
 public void KindIsConstantNode()
 {
     ConstantNode constantNode = new ConstantNode(1);
     constantNode.InternalKind.Should().Be(InternalQueryNodeKind.Constant);
 }
Exemplo n.º 38
0
 /// <summary>
 /// Visit a ConstantNode
 /// </summary>
 /// <param name="nodeIn">the node to visit</param>
 /// <returns>true, indicating that the node has been visited.</returns>
 public override bool Visit(ConstantNode nodeIn)
 {
     validate(nodeIn);
     return(true);
 }
Exemplo n.º 39
0
 public void TypeReferenceCannotBeNull()
 {
     ConstantNode source = new ConstantNode(1);
     Action createWithNullTargetType = () => new ConvertNode(source, null);
     createWithNullTargetType.ShouldThrow<Exception>(Error.ArgumentNull("typeReference").ToString());
 }
Exemplo n.º 40
0
        public void ODataUriBuilderWithEntitySet()
        {
            Uri            fullUri        = new Uri("http://www.example.com/People?$filter=MyDog%2FColor%20eq%20%27Brown%27&$select=ID&$expand=MyDog&$orderby=ID&$top=1&$skip=2&$count=true&$search=FA");
            ODataUriParser odataUriParser = new ODataUriParser(this.GetModel(), serviceRoot, fullUri);

            odataUriParser.UrlConventions = ODataUrlConventions.Default;
            SetODataUriParserSettingsTo(this.settings, odataUriParser.Settings);
            ODataUri odataUri = odataUriParser.ParseUri();

            //verify path
            EntitySetSegment entitySet = (EntitySetSegment)odataUri.Path.FirstSegment;

            Assert.AreEqual(entitySet.EntitySet.Name, "People");
            Assert.AreEqual(odataUri.Path.Count, 1);

            //verify $filter
            BinaryOperatorNode            binaryOperator      = (BinaryOperatorNode)odataUri.Filter.Expression;
            SingleValuePropertyAccessNode singleValueProperty = (SingleValuePropertyAccessNode)binaryOperator.Left;
            SingleNavigationNode          singleNavigation    = (SingleNavigationNode)singleValueProperty.Source;
            ConstantNode constantNode = (ConstantNode)binaryOperator.Right;

            Assert.AreEqual(binaryOperator.OperatorKind, BinaryOperatorKind.Equal);
            Assert.AreEqual(singleValueProperty.Property.Name, "Color");
            Assert.AreEqual(singleNavigation.NavigationProperty.Name, "MyDog");
            Assert.AreEqual(constantNode.LiteralText, "'Brown'");

            //verify $select and $expand
            IEnumerable <SelectItem> selectItems = odataUri.SelectAndExpand.SelectedItems;

            foreach (ExpandedNavigationSelectItem selectItem in selectItems)
            {
                NavigationPropertySegment navigationProperty = (NavigationPropertySegment)selectItem.PathToNavigationProperty.FirstSegment;
                Assert.AreEqual(navigationProperty.NavigationProperty.Name, "MyDog");
                break;
            }

            //verify $orderby
            SingleValuePropertyAccessNode orderby = (SingleValuePropertyAccessNode)odataUri.OrderBy.Expression;

            Assert.AreEqual(orderby.Property.Name, "ID");

            //verify $top
            Assert.AreEqual(odataUri.Top, 1);

            //verify $skip
            Assert.AreEqual(odataUri.Skip, 2);

            //verify $count
            Assert.AreEqual(odataUri.QueryCount, true);

            //verify $search
            SearchTermNode searchTermNode = (SearchTermNode)odataUri.Search.Expression;

            Assert.AreEqual(searchTermNode.Text, "FA");

            ODataUriBuilder odataUriBuilder = new ODataUriBuilder(ODataUrlConventions.Default, odataUri);
            Uri             actualUri       = odataUriBuilder.BuildUri();

            Assert.AreEqual(new Uri("http://www.example.com/People?$filter=MyDog%2FColor%20eq%20%27Brown%27&$select=ID%2CMyDog&$expand=MyDog&$orderby=ID&$top=1&$skip=2&$count=true&$search=FA"), actualUri);

            ODataUriBuilder uriBuilderWithKeyAsSegment = new ODataUriBuilder(ODataUrlConventions.KeyAsSegment, odataUri);

            actualUri = uriBuilderWithKeyAsSegment.BuildUri();
            Assert.AreEqual(new Uri("http://www.example.com/People?$filter=MyDog%2FColor%20eq%20%27Brown%27&$select=ID%2CMyDog&$expand=MyDog&$orderby=ID&$top=1&$skip=2&$count=true&$search=FA"), actualUri);
        }
Exemplo n.º 41
0
 public void TypeReferenceIsSetCorrectly()
 {
     ConstantNode source = new ConstantNode(1);
     ConvertNode convertNode = new ConvertNode(source, EdmCoreModel.Instance.GetInt64(true));
     convertNode.TypeReference.FullName().Should().Be("Edm.Int64");
 }
 public override QueryNode Visit(ConstantNode nodeIn)
 {
     return(nodeIn);
 }
 public void EnsureParentIsEntityForNavPropThrowsIfNotEntity()
 {
     var parent = new ConstantNode(null);
     Action targetMethod = () => InnerPathTokenBinder.EnsureParentIsEntityForNavProp(parent);
     targetMethod.ShouldThrow<ODataException>().WithMessage(ODataErrorStrings.MetadataBinder_NavigationPropertyNotFollowingSingleEntityType);
 }
Exemplo n.º 44
0
        public static Expression <Func <TModel, bool> > FilterObjectSet(SingleValuePropertyAccessNode rule, ConstantNode constant, BinaryOperatorKind kind, string name = "model")
        {
            Type type = typeof(TModel);
            var  par  = Expression.Parameter(type, name);

            Type       fieldPropertyType;
            Expression fieldPropertyExpression;

            FieldInfo fieldInfo = type.GetField(rule.Property.Name);

            if (fieldInfo == null)
            {
                PropertyInfo propertyInfo = type.GetProperty(rule.Property.Name);

                if (propertyInfo == null)
                {
                    throw new Exception();
                }

                fieldPropertyType       = propertyInfo.PropertyType;
                fieldPropertyExpression = Expression.Property(par, propertyInfo);
            }
            else
            {
                fieldPropertyType       = fieldInfo.FieldType;
                fieldPropertyExpression = Expression.Field(par, fieldInfo);
            }
            object data2 = null;

            if (fieldPropertyType.IsGenericType && fieldPropertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(fieldPropertyType);
                data2 = conv.ConvertFrom(constant.LiteralText);
                //data2 = Convert.ChangeType(constant.LiteralText, Nullable.GetUnderlyingType());
            }
            else
            {
                data2 = Convert.ChangeType(constant.LiteralText, fieldPropertyType);
            }

            if (fieldPropertyType == typeof(string))
            {
                data2 = data2.ToString().Replace("'", "");
            }
            BinaryExpression eq = null;

            switch (kind)
            {
            case BinaryOperatorKind.Or:
                eq = Expression.Or(fieldPropertyExpression,
                                   Expression.Constant(data2, fieldPropertyType));
                break;

            case BinaryOperatorKind.And:
                eq = Expression.And(fieldPropertyExpression,
                                    Expression.Constant(data2, fieldPropertyType));
                break;

            case BinaryOperatorKind.Equal:
                eq = Expression.Equal(fieldPropertyExpression,
                                      Expression.Constant(data2, fieldPropertyType));
                break;

            case BinaryOperatorKind.NotEqual:
                eq = Expression.NotEqual(fieldPropertyExpression,
                                         Expression.Constant(data2, fieldPropertyType));
                break;

            case BinaryOperatorKind.GreaterThan:
                eq = Expression.GreaterThan(fieldPropertyExpression,
                                            Expression.Constant(data2));
                break;

            case BinaryOperatorKind.GreaterThanOrEqual:
                eq = Expression.GreaterThanOrEqual(fieldPropertyExpression,
                                                   Expression.Constant(data2, fieldPropertyType));
                break;

            case BinaryOperatorKind.LessThan:
                eq = Expression.LessThan(fieldPropertyExpression,
                                         Expression.Constant(data2, fieldPropertyType));
                break;

            case BinaryOperatorKind.LessThanOrEqual:
                eq = Expression.LessThanOrEqual(fieldPropertyExpression,
                                                Expression.Constant(data2, fieldPropertyType));
                break;

            case BinaryOperatorKind.Add:
                eq = Expression.Add(fieldPropertyExpression,
                                    Expression.Constant(data2, fieldPropertyType));
                break;

            case BinaryOperatorKind.Subtract:
                eq = Expression.Subtract(fieldPropertyExpression,
                                         Expression.Constant(data2, fieldPropertyType));
                break;

            case BinaryOperatorKind.Multiply:
                eq = Expression.Multiply(fieldPropertyExpression,
                                         Expression.Constant(data2, fieldPropertyType));
                break;

            case BinaryOperatorKind.Divide:
                eq = Expression.Divide(fieldPropertyExpression,
                                       Expression.Constant(data2, fieldPropertyType));
                break;

            case BinaryOperatorKind.Modulo:
                eq = Expression.Modulo(fieldPropertyExpression,
                                       Expression.Constant(data2, fieldPropertyType));
                break;

            case BinaryOperatorKind.Has:
                break;
            }
            ;
            return(Expression.Lambda <Func <TModel, bool> >(eq, par));
        }
Exemplo n.º 45
0
        /// <summary>
        /// Compares top query nodes.
        /// </summary>
        /// <param name="left">Left side of comparison</param>
        /// <param name="right">Right side of comparison</param>
        /// <returns>True if equal, otherwise false</returns>
        //private bool Compare(TopNode left, TopNode right)
        //{
        //    if (left.ItemType != right.ItemType) return false;
        //    if (!this.Compare(left.Amount, right.Amount)) return false;
        //    return this.Compare(left.Collection, right.Collection);
        //}

        /// <summary>
        /// Compares key lookup query nodes.
        /// </summary>
        /// <param name="left">Left side of comparison</param>
        /// <param name="right">Right side of comparison</param>
        /// <returns>True if equal, otherwise false</returns>
        //private bool Compare(KeyLookupNode left, KeyLookupNode right)
        //{
        //    if (left.EntityTypeReference != right.EntityTypeReference) return false;
        //    if (left.EntitySet != right.EntitySet) return false;
        //    if (left.TypeReference != right.TypeReference) return false;
        //    if (left.KeyPropertyValues.Count() != right.KeyPropertyValues.Count()) return false;

        //    for (int i = 0; i < left.KeyPropertyValues.Count(); ++i)
        //    {
        //        KeyPropertyValue leftKpv= left.KeyPropertyValues.ElementAt(i);
        //        KeyPropertyValue rightKpv = right.KeyPropertyValues.ElementAt(i);

        //        if (leftKpv.KeyProperty != rightKpv.KeyProperty) return false;
        //        if (!this.Compare(leftKpv.KeyValue, rightKpv.KeyValue)) return false;
        //    }

        //    return this.Compare(left.Source, right.Source);
        //}

        /// <summary>
        /// Compares entity set query nodes.
        /// </summary>
        /// <param name="left">Left side of comparison</param>
        /// <param name="right">Right side of comparison</param>
        /// <returns>True if equal, otherwise false</returns>
        //private bool Compare(EntitySetNode left, EntitySetNode right)
        //{
        //    if (left.EntityItemType != right.EntityItemType) return false;
        //    if (left.EntitySet != right.EntitySet) return false;
        //    if (left.ItemType != right.ItemType) return false;
        //    if (left.OverrideType != right.OverrideType) return false;
        //    return true;
        //}

        /// <summary>
        /// Compares constant query nodes.
        /// </summary>
        /// <param name="left">Left side of comparison</param>
        /// <param name="right">Right side of comparison</param>
        /// <returns>True if equal, otherwise false</returns>        
        private bool Compare(ConstantNode left, ConstantNode right)
        {
            if (left.TypeReference != right.TypeReference) return false;
            if (left.Value != right.Value) return false;
            return true;
        }
Exemplo n.º 46
0
        internal static ConstantNode ParseConstantNode(Token token)
        {
            switch (token.TokenType)
            {
            case TokenType.Date:
                var dateTimeValue = DateTime.ParseExact(token.Value, ODataDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
                return(ConstantNode.Date(token.Value, dateTimeValue));

            case TokenType.DateTimeOffset:
                var dateTimeOffsetValue = DateTimeOffset.Parse(token.Value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
                return(ConstantNode.DateTimeOffset(token.Value, dateTimeOffsetValue));

            case TokenType.Decimal:
                var decimalText  = token.Value.Substring(0, token.Value.Length - 1);
                var decimalValue = decimal.Parse(decimalText, CultureInfo.InvariantCulture);
                return(ConstantNode.Decimal(token.Value, decimalValue));

            case TokenType.Double:
                var doubleText = token.Value.EndsWith("d", StringComparison.OrdinalIgnoreCase)
                        ? token.Value.Substring(0, token.Value.Length - 1)
                        : token.Value;
                var doubleValue = double.Parse(doubleText, CultureInfo.InvariantCulture);
                return(ConstantNode.Double(token.Value, doubleValue));

            case TokenType.Duration:
                var durationText = token.Value.Substring(9, token.Value.Length - 10)
                                   .Replace("P", string.Empty)
                                   .Replace("DT", ".")
                                   .Replace("H", ":")
                                   .Replace("M", ":")
                                   .Replace("S", string.Empty);
                var durationTimeSpanValue = TimeSpan.Parse(durationText, CultureInfo.InvariantCulture);
                return(ConstantNode.Duration(token.Value, durationTimeSpanValue));

            case TokenType.Enum:
                var firstQuote        = token.Value.IndexOf('\'');
                var edmEnumTypeName   = token.Value.Substring(0, firstQuote);
                var edmEnumType       = (EdmEnumType)EdmType.GetEdmType(edmEnumTypeName);
                var edmEnumMemberName = token.Value.Substring(firstQuote + 1, token.Value.Length - firstQuote - 2);
                var enumValue         = edmEnumType.GetClrValue(edmEnumMemberName);

                return(new ConstantNode(edmEnumType, token.Value, enumValue));

            case TokenType.False:
                return(ConstantNode.False);

            case TokenType.Guid:
                var guidValue = Guid.ParseExact(token.Value, "D");
                return(ConstantNode.Guid(token.Value, guidValue));

            case TokenType.Integer:
                var integerText = token.Value;

                if (integerText == "0")
                {
                    return(ConstantNode.Int32Zero);
                }
                else if (integerText == "0l" || integerText == "0L")
                {
                    return(ConstantNode.Int64Zero);
                }

                var is64BitSuffix = integerText.EndsWith("l", StringComparison.OrdinalIgnoreCase);

                if (!is64BitSuffix && int.TryParse(integerText, out int int32Value))
                {
                    return(ConstantNode.Int32(token.Value, int32Value));
                }

                var int64Text  = !is64BitSuffix ? integerText : integerText.Substring(0, integerText.Length - 1);
                var int64Value = long.Parse(int64Text, CultureInfo.InvariantCulture);
                return(ConstantNode.Int64(token.Value, int64Value));

            case TokenType.Null:
                return(ConstantNode.Null);

            case TokenType.Single:
                var singleText  = token.Value.Substring(0, token.Value.Length - 1);
                var singleValue = float.Parse(singleText, CultureInfo.InvariantCulture);
                return(ConstantNode.Single(token.Value, singleValue));

            case TokenType.String:
                var stringText = token.Value.Trim('\'').Replace("''", "'");
                return(ConstantNode.String(token.Value, stringText));

            case TokenType.TimeOfDay:
                var timeSpanTimeOfDayValue = TimeSpan.Parse(token.Value, CultureInfo.InvariantCulture);
                return(ConstantNode.Time(token.Value, timeSpanTimeOfDayValue));

            case TokenType.True:
                return(ConstantNode.True);

            default:
                throw new NotSupportedException(token.TokenType.ToString());
            }
        }
Exemplo n.º 47
0
        public override IDictionary<IEdmOperationParameter, SingleValueNode> ResolveOperationParameters(IEdmOperation operation, IDictionary<string, SingleValueNode> input)
        {
            Dictionary<IEdmOperationParameter, SingleValueNode> result = new Dictionary<IEdmOperationParameter, SingleValueNode>(EqualityComparer<IEdmOperationParameter>.Default);
            foreach (var item in input)
            {
                IEdmOperationParameter functionParameter = null;
                if (EnableCaseInsensitive)
                {
                    functionParameter = ODataUriResolver.ResolveOpearationParameterNameCaseInsensitive(operation, item.Key);
                }
                else
                {
                    functionParameter = operation.FindParameter(item.Key);
                }

                // ensure parameter name existis
                if (functionParameter == null)
                {
                    throw new ODataException(Strings.ODataParameterWriterCore_ParameterNameNotFoundInOperation(item.Key, operation.Name));
                }

                SingleValueNode newVal = item.Value;

                if (functionParameter.Type.IsEnum()
                    && newVal is ConstantNode
                    && newVal.TypeReference != null
                    && newVal.TypeReference.IsString())
                {
                    string text = ((ConstantNode)item.Value).Value as string;
                    ODataEnumValue val;
                    IEdmTypeReference typeRef = functionParameter.Type;

                    if (TryParseEnum(typeRef.Definition as IEdmEnumType, text, out val))
                    {
                        newVal = new ConstantNode(val, text, typeRef);
                    }
                }

                result.Add(functionParameter, newVal);
            }

            return result;
        }
 public override void ValidateConstantNode(ConstantNode constantNode, ODataValidationSettings settings)
 {
     IncrementCount("ValidateConstantQueryNode");
     base.ValidateConstantNode(constantNode, settings);
 }
Exemplo n.º 49
0
        public void BindLiteralShouldSetLiteralTextFromToken()
        {
            ConstantNode result = LiteralBinder.BindLiteral(new LiteralToken(1, "originalText")) as ConstantNode;

            Assert.Equal("originalText", result.LiteralText);
        }
        private ConstantNode ParseTypeConstruction()
        {
            var typeIdentifier = this.lexer.Token.Text;
            var errorPos = this.lexer.Token.Position;
            this.lexer.NextToken();
            ConstantNode typeExpression = null;

            if (this.lexer.Token.Kind == QueryTokenKind.StringLiteral)
            {
                errorPos = this.lexer.Token.Position;
                ConstantNode stringExpr = this.ParseStringLiteral();
                string literalValue = stringExpr.Value.ToString();

                try
                {
                    if (typeIdentifier == "datetime")
                    {
                        var date = DateTime.Parse(literalValue);
                        typeExpression = new ConstantNode(date);
                    }
                    else if (typeIdentifier == "datetimeoffset")
                    {
                        var date = DateTimeOffset.Parse(literalValue);
                        typeExpression = new ConstantNode(date);
                    }
                    else if (typeIdentifier == "guid")
                    {
                        var guid = Guid.Parse(literalValue);
                        typeExpression = new ConstantNode(guid);
                    }
                }
                catch (Exception ex)
                {
                    this.ParseError(ex.Message, errorPos);
                }
            }

            if (typeExpression == null)
            {
                this.ParseError("The specified odata query has invalid '{0}' type creation expression.".FormatInvariant(typeIdentifier), errorPos);
            }

            return typeExpression;
        }
Exemplo n.º 51
0
        public void AddTopConstant(ConstantExpression topConstant, ODataPath path)
        {
            ConstantNode topNode = OeCacheComparerParameterValues.CreateTopConstantNode((int)topConstant.Value, path);

            AddConstant(topConstant, topNode);
        }
Exemplo n.º 52
0
 public override object Visit(ConstantNode nodeIn)
 {
     return(null);
 }
Exemplo n.º 53
0
 public int Visit(ConstantNode caller)
 {
     return(caller.Value);
 }
Exemplo n.º 54
0
 /// <summary>
 /// Visit a ConstantNode
 /// </summary>
 /// <param name="nodeIn">the node to visit</param>
 /// <returns>Defined by the implementer</returns>
 public virtual T Visit(ConstantNode nodeIn)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 55
0
 public double Visit(ConstantNode caller)
 {
     return(caller.Value);
 }
Exemplo n.º 56
0
 public static Instruction MoveToMemory <T>(ConstantNode <T> addr, ConstantNode <T> val)
 {
     return(new Instruction(
                map => string.Format("mov [{0}], {1}", addr.Value, val.Value),
                use(), define()));
 }
Exemplo n.º 57
0
        /// <summary>
        /// Override this method to restrict the 'constant' inside the filter query.
        /// </summary>
        /// <remarks>
        /// This method is intended to be called from method overrides in subclasses. This method also supports unit-testing scenarios and is not intended to be called from user code.
        /// Call the Validate method to validate a <see cref="FilterQueryOption"/> instance.
        /// </remarks>
        /// <param name="constantNode"></param>
        /// <param name="settings"></param>
        public virtual void ValidateConstantNode(ConstantNode constantNode, ODataValidationSettings settings)
        {
            if (constantNode == null)
            {
                throw Error.ArgumentNull("constantNode");
            }

            if (settings == null)
            {
                throw Error.ArgumentNull("settings");
            }

            // no default validation logic here
        }
Exemplo n.º 58
0
 public static Instruction Or <T>(RegisterNode dst, ConstantNode <T> c)
 {
     return(binopInstruction("or", dst, c));
 }
Exemplo n.º 59
0
        public void CreateLambdaNodeForAllTokenShouldCreateAllNode()
        {
            BindingState bindingState = new BindingState(configuration);
            EntityCollectionNode parent = new EntitySetNode(HardCodedTestModel.GetPeopleSet());
            SingleValueNode expression = new ConstantNode(true);
            RangeVariable rangeVariable = new EntityRangeVariable("bob", HardCodedTestModel.GetPersonTypeReference(), parent);
            var resultNode = NodeFactory.CreateLambdaNode(bindingState, parent, expression, rangeVariable, QueryTokenKind.All);

            var node = resultNode.ShouldBeAllQueryNode().And;
            node.Body.Should().BeSameAs(expression);
            node.Source.Should().BeSameAs(parent);
        }
Exemplo n.º 60
0
        public void AddSkipTokenConstant(ConstantExpression skipTokenConstant, String propertyName)
        {
            ConstantNode skipTokenNode = OeCacheComparerParameterValues.CreateSkipTokenConstantNode(skipTokenConstant.Value, propertyName);

            AddConstant(skipTokenConstant, skipTokenNode);
        }