Example #1
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 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");
 }
 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 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);
 }
Example #5
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);
					});
		}
        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);
        }
Example #7
0
        public static GraphNode operator *(NodeFuture future, string constant)
        {
            var node = new ConstantNode(constant);
            node.ActivationFunction = future.ActivationFunction;

            return future.Parent.Slash(node);
        }
 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 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();
            }
        }
        /// <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);
        }
        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();
            }
        }
Example #12
0
 public void ValueIsSetCorrectly()
 {
     ConstantNode constantNode = new ConstantNode(1);
     constantNode.Value.As<int>().Should().Be(1);
 }
Example #13
0
 public void TypeIsSetFromTheTypeOfTheValue()
 {
     ConstantNode constantNode = new ConstantNode(1);
     constantNode.TypeReference.FullName().Should().Be("Edm.Int32");
 }
        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;
            }
        }
Example #15
0
 public void KindIsConstantNode()
 {
     ConstantNode constantNode = new ConstantNode(1);
     constantNode.InternalKind.Should().Be(InternalQueryNodeKind.Constant);
 }
Example #16
0
 public static GraphNode operator /(RouteGlue state, string other)
 {
     var node = new ConstantNode(other);
     return node;
 }
Example #17
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);
 }
        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;
        }
        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);
        }
 public override void ValidateConstantNode(ConstantNode constantNode, ODataValidationSettings settings)
 {
     IncrementCount("ValidateConstantQueryNode");
     base.ValidateConstantNode(constantNode, settings);
 }
Example #21
0
 public void KindIsSetToConvertNode()
 {
     ConstantNode source = new ConstantNode(1);
     ConvertNode convertNode = new ConvertNode(source, EdmCoreModel.Instance.GetInt64(true));
     convertNode.InternalKind.Should().Be(InternalQueryNodeKind.Convert);
 }
Example #22
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");
 }
Example #23
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();
            }
        }
        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 void EnsureParentIsEntityForNavPropThrowsIfNotEntity()
 {
     var parent = new ConstantNode(null);
     Action targetMethod = () => InnerPathTokenBinder.EnsureParentIsEntityForNavProp(parent);
     targetMethod.ShouldThrow<ODataException>().WithMessage(ODataErrorStrings.MetadataBinder_NavigationPropertyNotFollowingSingleEntityType);
 }
Example #26
0
 public void TypeReferenceCannotBeNull()
 {
     ConstantNode source = new ConstantNode(1);
     Action createWithNullTargetType = () => new ConvertNode(source, null);
     createWithNullTargetType.ShouldThrow<Exception>(Error.ArgumentNull("typeReference").ToString());
 }
        /// <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
        }
        /// <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;
        }
Example #29
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);
        }
Example #30
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;
        }