예제 #1
0
        public void RedundantlyParserFilter()
        {
            const string   queryOption = "CustomerID eq null";
            ODataUriParser parser      = this.CreateFilterUriParser(orderBase, queryOption);
            var            result      = parser.ParseFilter();

            ApprovalVerify(QueryNodeToStringVisitor.GetTestCaseAndResultString(result, queryOption));
            result = parser.ParseFilter();
            ApprovalVerify(QueryNodeToStringVisitor.GetTestCaseAndResultString(result, queryOption));

            this.TestAllInOneExtensionFilter(
                orderBase,
                "customerid eQ null",
                "CustomerID eq null");
        }
        public void ParseWithMixedCaseCustomUriFunction_EnableCaseInsensitive_ShouldWork()
        {
            try
            {
                FunctionSignatureWithReturnType myStringFunction
                    = new FunctionSignatureWithReturnType(EdmCoreModel.Instance.GetBoolean(true), EdmCoreModel.Instance.GetString(true), EdmCoreModel.Instance.GetString(true));

                // Add a custom uri function
                CustomUriFunctions.AddCustomUriFunction("myFirstMixedCasestringfunction", myStringFunction);

                // Uri with mixed-case, should work for resolver with case insensitive enabled.
                var            fullUri = new Uri("http://www.odata.com/OData/People" + "?$filter=mYFirstMixedCasesTrInGfUnCtIoN(Name, 'BlaBla')");
                ODataUriParser parser  = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://www.odata.com/OData/"), fullUri);
                parser.Resolver.EnableCaseInsensitive = true;

                var startsWithArgs = parser.ParseFilter().Expression.ShouldBeSingleValueFunctionCallQueryNode("myFirstMixedCasestringfunction")
                                     .Parameters.ToList();
                startsWithArgs[0].ShouldBeSingleValuePropertyAccessQueryNode(HardCodedTestModel.GetPersonNameProp());
                startsWithArgs[1].ShouldBeConstantQueryNode("BlaBla");
            }
            finally
            {
                Assert.True(CustomUriFunctions.RemoveCustomUriFunction("myFirstMixedCasestringfunction"));
            }
        }
예제 #3
0
        private void ParseUriAndVerify(
            Uri uri,
            Action <ODataPath, FilterClause, OrderByClause, SelectExpandClause, IDictionary <string, SingleValueNode> > verifyAction)
        {
            // run 2 test passes:
            // 1. low level api - ODataUriParser instance methods
            {
                List <CustomQueryOptionToken> queries = UriUtils.ParseQueryOptions(uri);
                ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://gobbledygook/"), uri);

                ODataPath            path         = parser.ParsePath();
                IEdmNavigationSource entitySource = ResolveEntitySource(path);
                IEdmEntitySet        entitySet    = entitySource as IEdmEntitySet;

                var dic = queries.ToDictionary(customQueryOptionToken => customQueryOptionToken.Name, customQueryOptionToken => queries.GetQueryOptionValue(customQueryOptionToken.Name));
                ODataQueryOptionParser queryOptionParser = new ODataQueryOptionParser(HardCodedTestModel.TestModel, entitySet.EntityType(), entitySet, dic)
                {
                    Configuration = { ParameterAliasValueAccessor = parser.ParameterAliasValueAccessor }
                };

                FilterClause       filterClause       = queryOptionParser.ParseFilter();
                SelectExpandClause selectExpandClause = queryOptionParser.ParseSelectAndExpand();
                OrderByClause      orderByClause      = queryOptionParser.ParseOrderBy();

                // Two parser should share same ParameterAliasNodes
                verifyAction(path, filterClause, orderByClause, selectExpandClause, parser.ParameterAliasNodes);
                verifyAction(path, filterClause, orderByClause, selectExpandClause, queryOptionParser.ParameterAliasNodes);
            }

            //2. high level api - ParseUri
            {
                ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://gobbledygook/"), uri);
                verifyAction(parser.ParsePath(), parser.ParseFilter(), parser.ParseOrderBy(), parser.ParseSelectAndExpand(), parser.ParameterAliasNodes);
            }
        }
예제 #4
0
        public void EmptyValueQueryOptionShouldWork(string relativeUriString, bool enableNoDollarQueryOptions)
        {
            var uriParser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, new Uri(FullUri, relativeUriString));

            uriParser.EnableNoDollarQueryOptions = enableNoDollarQueryOptions;
            var path = uriParser.ParsePath();

            path.Should().HaveCount(1);
            path.LastSegment.ShouldBeEntitySetSegment(HardCodedTestModel.GetPeopleSet());
            uriParser.ParseFilter().Should().BeNull();
            var results = uriParser.ParseSelectAndExpand();

            results.AllSelected.Should().BeTrue();
            results.SelectedItems.Should().HaveCount(0);
            uriParser.ParseOrderBy().Should().BeNull();
            Action action = () => uriParser.ParseTop();

            action.ShouldThrow <ODataException>().WithMessage(Strings.SyntacticTree_InvalidTopQueryOptionValue(""));
            action = () => uriParser.ParseSkip();
            action.ShouldThrow <ODataException>().WithMessage(Strings.SyntacticTree_InvalidSkipQueryOptionValue(""));
            action = () => uriParser.ParseCount();
            action.ShouldThrow <ODataException>().WithMessage(Strings.ODataUriParser_InvalidCount(""));
            action = () => uriParser.ParseSearch();
            action.ShouldThrow <ODataException>().WithMessage(Strings.UriQueryExpressionParser_ExpressionExpected(0, ""));
            uriParser.ParseSkipToken().Should().BeEmpty();
            uriParser.ParseDeltaToken().Should().BeEmpty();
        }
        public IRequest Parse <T>(string queryString)
            where T : class, new()
        {
            var requestUri = new Uri($"{nameof(T)}/{queryString}", UriKind.Relative);

            var parser = new ODataUriParser(GetEdmModel <T>(nameof(T)), requestUri)
            {
                Resolver = new StringAsEnumResolver()
                {
                    EnableCaseInsensitive = _uriParserSettings.EnableCaseInsensitive,
                },
            };

            bool?count = parser.ParseCount();
            long?top   = parser.ParseTop();
            long?skip  = parser.ParseSkip();

            var filter = parser.ParseFilter().Parse();

            return(new Request
            {
                Filter = filter,
                Select = parser.ParseSelectAndExpand().Parse(),
                Sorts = parser.ParseOrderBy().Parse(),
                Count = count.HasValue ? Convert.ToBoolean(count.Value) : false,
                Page = skip.HasValue ? Convert.ToInt32(skip.Value) + 1 : 1,
                PageSize = top.HasValue ? Convert.ToInt32(top.Value) : null
            });
        }
예제 #6
0
        public static void ParseFilter(this ODataUriParser query, Query result)
        {
            SearchClause search;

            try
            {
                search = query.ParseSearch();
            }
            catch (ODataException ex)
            {
                throw new ValidationException("Query $search clause not valid.", new ValidationError(ex.Message));
            }

            if (search != null)
            {
                result.FullText = SearchTermVisitor.Visit(search.Expression).ToString();
            }

            FilterClause filter;

            try
            {
                filter = query.ParseFilter();
            }
            catch (ODataException ex)
            {
                throw new ValidationException("Query $filter clause not valid.", new ValidationError(ex.Message));
            }

            if (filter != null)
            {
                result.Filter = FilterVisitor.Visit(filter.Expression);
            }
        }
예제 #7
0
        public void StringAsEnumTest()
        {
            Uri normalUri          = new Uri("http://host/Pet2Set?$filter=PetColorPattern eq Fully.Qualified.Namespace.ColorPattern'Blue'");
            Uri unqualifiedEnumUri = new Uri("http://host/Pet2Set?$filter=PetColorPattern eq 'Blue'");

            Uri normalUriReverse          = new Uri("http://host/Pet2Set?$filter=Fully.Qualified.Namespace.ColorPattern'Blue' eq PetColorPattern");
            Uri unqualifiedEnumUriReverse = new Uri("http://host/Pet2Set?$filter='Blue' eq PetColorPattern");

            var uriParser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, normalUri);

            VerifyEnumVsStringFilterExpression(uriParser.ParseFilter());

            uriParser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, normalUri)
            {
                Resolver = new StringAsEnumResolver()
            };
            VerifyEnumVsStringFilterExpression(uriParser.ParseFilter());

            uriParser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, unqualifiedEnumUri)
            {
                Resolver = new StringAsEnumResolver()
            };
            VerifyEnumVsStringFilterExpression(uriParser.ParseFilter());

            uriParser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, normalUriReverse);
            VerifyEnumVsStringFilterExpressionReverse(uriParser.ParseFilter());

            uriParser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, unqualifiedEnumUriReverse)
            {
                Resolver = new StringAsEnumResolver()
            };
            VerifyEnumVsStringFilterExpressionReverse(uriParser.ParseFilter());
        }
예제 #8
0
파일: Program.cs 프로젝트: EricCote/WebApi2
        private static void TestStringRep()
        {
            Console.WriteLine("TestStringRep");
            var parser = new ODataUriParser(
                extModel.Model,
                ServiceRoot,
                new Uri("http://demo/odata.svc/People?$filter=Name eq 'Cyan' mul 3"));

            try
            {
                // Would throw exception
                parser.ParseFilter();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            var parser2 = new ODataUriParser(
                extModel.Model,
                ServiceRoot,
                new Uri("http://demo/odata.svc/People?$filter=Name eq 'Cyan' mul 3"))
            {
                Resolver = new StringRepResolver()
            };

            // Would work
            var clause2 = parser2.ParseFilter();

            Console.WriteLine(clause2.Expression.ToLogString());
        }
예제 #9
0
        public void FirstTest()
        {
            var intparam             = EdmCoreModel.Instance.GetInt32(false);
            var daysFromNowSignature = new FunctionSignatureWithReturnType(EdmCoreModel.Instance.GetDate(false), intparam);

            CustomUriFunctions.AddCustomUriFunction("daysFromNow", daysFromNowSignature);

            var filterPath = $"persons?$filter = Birthday gt daysFromNow(-3)";

            var uri          = new Uri(filterPath, UriKind.Relative);
            var model        = CreateModel("persons");
            var parser       = new ODataUriParser(model, new Uri("http://www.odata.com/OData"), uri);
            var filterClause = parser.ParseFilter();
            var parsedUri    = parser.ParseUri();
            var expression   = filterClause.Expression;

            var person1 = new Person {
                Id = 0, Name = "Hallo", Birthday = DateTime.Now.AddDays(-5)
            };
            var person2 = new Person {
                Id = 1, Name = "Hallo2", Birthday = DateTime.Now
            };
            var persons = new List <Person> {
                person1, person2
            };

            var p = persons.Where(i => Evaluate(expression, i)).ToList();

            Assert.IsTrue(p.Count == 1);
            Assert.IsTrue(p.FirstOrDefault().Name == "Hallo2");
        }
        public IEnumerable <string> Get(string filter)
        {
            new InMemoryODataQueryEngine <Tenant>().AddProperty((t) => t.Name);

            var model = new EdmModel();

            var  tenant     = new EdmEntityType("TenantModel", "Tenant");
            bool isNullable = false;
            var  idProperty = tenant.AddStructuralProperty("TenantId",
                                                           EdmCoreModel.Instance.GetInt32(isNullable));

            tenant.AddKeys(idProperty);
            tenant.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(isNullable));
            model.AddElement(tenant);

            var container = new EdmEntityContainer("TestModel", "DefaultContainer");

            container.AddEntitySet("tenants", tenant);
            model.AddElement(container);

            var expression = ODataUriParser.ParseFilter(filter, model, tenant).Expression;

            var expr = ConvertToTableQuery(expression);



            return(new string[] { "value1", "value2" });
        }
        public void OnGet()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.EntitySet <UserSettingGroup>("UserSettingGroups");
            var model = builder.GetEdmModel();

            var filterValue1 = "freeland"; // Wrong final url = http://localhost:46151/api/UserSettingGroups?$filter=name eq 'freel and '
            //var filterValue1 = "freelanz"; // Correct final url = http://localhost:46151/api/UserSettingGroups?$filter=name eq 'freelanz' and Id eq 1

            var parser1 = new ODataUriParser(model, new Uri($"http://localhost:46151/api"), new Uri($"http://localhost:46151/api/UserSettingGroups?$filter=name eq '{filterValue1}'"))
            {
                Resolver = new ODataUriResolver {
                    EnableCaseInsensitive = true
                }
            };
            var parser2 = new ODataUriParser(model, new Uri($"http://localhost:46151/api"), new Uri("http://localhost:46151/api/UserSettingGroups?$filter=Id eq 1"))
            {
                Resolver = new ODataUriResolver {
                    EnableCaseInsensitive = true
                }
            };
            var filter1 = parser1.ParseFilter();
            var filter2 = parser2.ParseFilter();
            var filter3 = new FilterClause(new BinaryOperatorNode(BinaryOperatorKind.And, filter1.Expression, filter2.Expression), filter1.RangeVariable);
            var uri     = parser1.ParseUri();

            uri.Filter = filter3;
            var final = uri.BuildUri(ODataUrlKeyDelimiter.Parentheses);
        }
예제 #12
0
        protected void ApprovalVerifyFilterParser(Uri resourceRoot, string queryOption, IEdmModel model = null)
        {
            ODataUriParser parser = this.CreateFilterUriParser(resourceRoot, queryOption, model);
            var            result = parser.ParseFilter();

            ApprovalVerify(QueryNodeToStringVisitor.GetTestCaseAndResultString(result, queryOption));
        }
예제 #13
0
        protected IEnumerable <IEdmEntityObject> GetFilteredResult(IEnumerable <Dictionary <string, object> > group, string query, ParseContext parseContext)
        {
            // Create collection from group
            var collectionEntityTypeKey = parseContext.LatestStateDictionary
                                          .Keys.FirstOrDefault(p => p.Contains("collectionentitytype"));
            var entityRef     = (EdmEntityTypeReference)parseContext.LatestStateDictionary[collectionEntityTypeKey];
            var collectionRef = new EdmCollectionTypeReference(new EdmCollectionType(entityRef));
            var collection    = new EdmEntityObjectCollection(collectionRef);

            foreach (var entity in group)
            {
                var obj = new EdmEntityObject(entityRef);
                foreach (var kvp in entity)
                {
                    obj.TrySetPropertyValue(kvp.Key, kvp.Value);
                }
                collection.Add(obj);
            }
            // Create filter query using the entity supplied in the lateststatedictionary
            var serviceRoot    = new Uri(RequestFilterConstants.ODataServiceRoot);
            var resource       = entityRef.Definition.FullTypeName().Split(".").Last();
            var filterQuery    = "/" + resource + "?$filter=" + Uri.EscapeDataString(query.Substring(1, query.Length - 2).Replace("''", "'"));
            var oDataUriParser = new ODataUriParser(parseContext.Model, new Uri(filterQuery, UriKind.Relative));

            // Parse filterquery
            var filter         = oDataUriParser.ParseFilter();
            var odataFilter    = new ODataFilterPredicateParser();
            var filteredResult = odataFilter.ApplyFilter(parseContext.EdmEntityTypeSettings.FirstOrDefault(), collection, filter.Expression);

            return(filteredResult);
        }
        public void ParseWithCustomFunction_EnumParameter()
        {
            try
            {
                var enumType = new EdmEnumType("Fully.Qualified.Namespace", "NonFlagShape", EdmPrimitiveTypeKind.SByte, false);
                enumType.AddMember("Rectangle", new EdmEnumMemberValue(1));
                enumType.AddMember("Triangle", new EdmEnumMemberValue(2));
                enumType.AddMember("foursquare", new EdmEnumMemberValue(3));
                var enumTypeRef = new EdmEnumTypeReference(enumType, false);

                FunctionSignatureWithReturnType signature =
                    new FunctionSignatureWithReturnType(EdmCoreModel.Instance.GetBoolean(false), enumTypeRef);

                CustomUriFunctions.AddCustomUriFunction("enumFunc", signature);

                var            fullUri = new Uri("http://www.odata.com/OData/People" + "?$filter=enumFunc('Rectangle')");
                ODataUriParser parser  = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://www.odata.com/OData/"), fullUri);

                var enumFuncWithArgs = parser.ParseFilter().Expression.ShouldBeSingleValueFunctionCallQueryNode("enumFunc").Parameters.ToList();
                enumFuncWithArgs[0].ShouldBeEnumNode(enumType, "Rectangle");
            }
            finally
            {
                Assert.True(CustomUriFunctions.RemoveCustomUriFunction("enumFunc"));
            }
        }
        public void ParseWithMixedCaseCustomUriFunction_DisableCaseInsensitive_ShouldFailed()
        {
            bool exceptionThrown = false;

            try
            {
                FunctionSignatureWithReturnType myStringFunction
                    = new FunctionSignatureWithReturnType(EdmCoreModel.Instance.GetBoolean(true),
                                                          EdmCoreModel.Instance.GetString(true), EdmCoreModel.Instance.GetString(true));

                // Add a custom uri function
                CustomUriFunctions.AddCustomUriFunction("myMixedCasestringfunction", myStringFunction);

                // Uri with mixed-case, should fail for default resolver with case-insensitive disabled.
                var            fullUri = new Uri("http://www.odata.com/OData/People" + "?$filter=mYMixedCasesTrInGfUnCtIoN(Name, 'BlaBla')");
                ODataUriParser parser  = new ODataUriParser(HardCodedTestModel.TestModel,
                                                            new Uri("http://www.odata.com/OData/"), fullUri);
                parser.Resolver.EnableCaseInsensitive = false;

                parser.ParseFilter();
            }
            catch (ODataException e)
            {
                Assert.Equal("An unknown function with name 'mYMixedCasesTrInGfUnCtIoN' was found. " +
                             "This may also be a function import or a key lookup on a navigation property, which is not allowed.", e.Message);
                exceptionThrown = true;
            }
            finally
            {
                Assert.True(CustomUriFunctions.RemoveCustomUriFunction("myMixedCasestringfunction"));
            }

            Assert.True(exceptionThrown, "Exception should be thrown trying to parse mixed-case uri function when case-insensitive is disabled.");
        }
예제 #16
0
        public void EmptyValueQueryOptionShouldWork()
        {
            var uriParser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, new Uri(FullUri, "?$filter=&$select=&$expand=&$orderby=&$top=&$skip=&$count=&$search=&$unknow=&$unknowvalue&$skiptoken=&$deltatoken="));
            var path      = uriParser.ParsePath();

            path.Should().HaveCount(1);
            path.LastSegment.ShouldBeEntitySetSegment(HardCodedTestModel.GetPeopleSet());
            uriParser.ParseFilter().Should().BeNull();
            var results = uriParser.ParseSelectAndExpand();

            results.AllSelected.Should().BeTrue();
            results.SelectedItems.Should().HaveCount(0);
            uriParser.ParseOrderBy().Should().BeNull();
            Action action = () => uriParser.ParseTop();

            action.ShouldThrow <ODataException>().WithMessage(Strings.SyntacticTree_InvalidTopQueryOptionValue(""));
            action = () => uriParser.ParseSkip();
            action.ShouldThrow <ODataException>().WithMessage(Strings.SyntacticTree_InvalidSkipQueryOptionValue(""));
            action = () => uriParser.ParseCount();
            action.ShouldThrow <ODataException>().WithMessage(Strings.ODataUriParser_InvalidCount(""));
            action = () => uriParser.ParseSearch();
            action.ShouldThrow <ODataException>().WithMessage(Strings.UriQueryExpressionParser_ExpressionExpected(0, ""));
            uriParser.ParseSkipToken().Should().BeEmpty();
            uriParser.ParseDeltaToken().Should().BeEmpty();
        }
예제 #17
0
        public void ParseNoDollarQueryOptionsShouldReturnNullIfNoDollarQueryOptionsIsNotEnabled()
        {
            var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("People?filter=MyDog/Color eq 'Brown'&select=ID&expand=MyDog&orderby=ID&top=1&skip=2&count=true&search=FA&$unknown=&$unknownvalue&skiptoken=abc&deltatoken=def", UriKind.Relative));

            bool originalValue = parser.EnableNoDollarQueryOptions;

            try
            {
                // Ensure $-sign is required.
                parser.EnableNoDollarQueryOptions = false;

                parser.ParseFilter().Should().BeNull();
                parser.ParseSelectAndExpand().Should().BeNull();
                parser.ParseOrderBy().Should().BeNull();
                parser.ParseTop().Should().Be(null);
                parser.ParseSkip().Should().Be(null);
                parser.ParseCount().Should().Be(null);
                parser.ParseSearch().Should().BeNull();
                parser.ParseSkipToken().Should().BeNull();
                parser.ParseDeltaToken().Should().BeNull();
            }
            finally
            {
                // Restore original value
                parser.EnableNoDollarQueryOptions = originalValue;
            }
        }
        public void ParseWithCustomUriFunction_EnableCaseInsensitive_ShouldThrowDueToAmbiguity()
        {
            string lowerCaseName = "myfunction";
            string upperCaseName = lowerCaseName.ToUpper();

            FunctionSignatureWithReturnType myStringFunction
                = new FunctionSignatureWithReturnType(EdmCoreModel.Instance.GetBoolean(true), EdmCoreModel.Instance.GetString(true), EdmCoreModel.Instance.GetString(true));

            // Add two customer uri functions with same argument types, with names different in cases.
            CustomUriFunctions.AddCustomUriFunction(lowerCaseName, myStringFunction);
            CustomUriFunctions.AddCustomUriFunction(upperCaseName, myStringFunction);
            string rootUri     = "http://www.odata.com/OData/";
            string uriTemplate = rootUri + "People?$filter={0}(Name,'BlaBla')";

            try
            {
                int    strLen = lowerCaseName.Length;
                string mixedCaseFunctionName = lowerCaseName.Substring(0, strLen / 2).ToUpper() + lowerCaseName.Substring(strLen / 2);
                // Uri with mix-case function names referring to equivalent-argument-typed functions,
                // should result in exception for resolver with case insensitive enabled due to ambiguity (multiple equivalent matches).
                var            fullUri = new Uri(string.Format(uriTemplate, mixedCaseFunctionName));
                ODataUriParser parser  = new ODataUriParser(HardCodedTestModel.TestModel, new Uri(rootUri), fullUri);
                parser.Resolver.EnableCaseInsensitive = true;

                Action action = () => parser.ParseFilter();
                Assert.Throws <ODataException>(action);
            }
            finally
            {
                Assert.True(CustomUriFunctions.RemoveCustomUriFunction(lowerCaseName));
                Assert.True(CustomUriFunctions.RemoveCustomUriFunction(upperCaseName));
            }
        }
예제 #19
0
파일: Program.cs 프로젝트: EricCote/WebApi2
        private static void TestCombination2()
        {
            Console.WriteLine("TestCombination2");
            var parser = new ODataUriParser(
                extModel.Model,
                ServiceRoot,
                new Uri("http://demo/odata.svc/PetSet?$filter=Color eq TestNS.Color'Cyan'"));
            var path = parser.ParsePath();

            Console.WriteLine(path.ToLogString());
            var clause = parser.ParseFilter();

            Console.WriteLine(clause.Expression.ToLogString());

            var parser2 = new ODataUriParser(
                extModel.Model,
                ServiceRoot,
                new Uri("http://demo/odata.svc/petset?$FILTER=color EQ 'Cyan'"))
            {
                Resolver = new AllInOneResolver {
                    EnableCaseInsensitive = true
                }
            };

            var path2 = parser2.ParsePath();

            Console.WriteLine(path2.ToLogString());
            var clause2 = parser2.ParseFilter();

            Console.WriteLine(clause2.Expression.ToLogString());
        }
예제 #20
0
        public void ShouldBeNullOrderByOperatorInstance()
        {
            ODataUriParser parser = GetParser("/Enterprises");

            ISqlBinder binder = new SqlFilterBinder(parser.ParseFilter());

            binder.Query.Should().BeNull();
        }
예제 #21
0
        public void ShouldBeSingleValueFunctionOperatorResolverInstance()
        {
            ODataUriParser parser = GetParser("/Enterprises?$filter=contains(EnterpriseName,%27520%27)");

            ISqlBinder binder = new SqlFilterBinder(parser.ParseFilter());

            binder.Query.Should().BeOfType <SingleValueFunctionResolver>();
        }
예제 #22
0
        public void ShouldBeLessThanOperatorForInt()
        {
            ODataUriParser parser = GetParser("/Enterprises?$filter=MonitoredPrinters%20lt%20135");

            IQueryResolver resolver = new BinaryOperatorResolver(parser.ParseFilter().Expression as BinaryOperatorNode);

            resolver.Resolve().Should().Be("WHERE MonitoredPrinters < 135");
        }
예제 #23
0
        public void ShouldBeEqualOperatorForString()
        {
            ODataUriParser parser = GetParser("/Enterprises?$filter=CorporateName%20eq%20%27Diego%27");

            IQueryResolver resolver = new BinaryOperatorResolver(parser.ParseFilter().Expression as BinaryOperatorNode);

            resolver.Resolve().Should().Be("WHERE CorporateName LIKE 'Diego'");
        }
예제 #24
0
        public void ShouldBeLikeOperatorForEndsWithString()
        {
            ODataUriParser parser = GetParser("/Enterprises?$filter=endswith(EnterpriseName,%27520%27)");

            IQueryResolver resolver = new SingleValueFunctionResolver(parser.ParseFilter().Expression as SingleValueFunctionCallNode);

            resolver.Resolve().Should().Be("WHERE EnterpriseName LIKE '%520'");
        }
예제 #25
0
        public void ShouldBeBinaryOperatorResolverInstance()
        {
            ODataUriParser parser = GetParser("/Enterprises?$filter=CorporateName%20eq%20%27Diego%27");

            ISqlBinder binder = new SqlFilterBinder(parser.ParseFilter());

            binder.Query.Should().BeOfType <BinaryOperatorResolver>();
        }
예제 #26
0
        public void FilterLimitIsRespectedForFilter()
        {
            ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, new Uri("http://host/People?$filter=1 eq 1"))
            {
                Settings = { FilterLimit = 0 }
            };
            Action parseWithLimit = () => parser.ParseFilter();

            parseWithLimit.ShouldThrow <ODataException>().WithMessage(ODataErrorStrings.UriQueryExpressionParser_TooDeep);
        }
예제 #27
0
        public void FilterLimitWithInterestingTreeStructures()
        {
            ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, new Uri("http://host/People?$filter=MyDog/Color eq 'Brown' or MyDog/Color eq 'White'"))
            {
                Settings = { FilterLimit = 5 }
            };
            Action parseWithLimit = () => parser.ParseFilter();

            parseWithLimit.ShouldThrow <ODataException>().WithMessage(ODataErrorStrings.UriQueryExpressionParser_TooDeep);
        }
예제 #28
0
 /// <summary>Parses the text expression for $filter.</summary>
 /// <returns>The parsed filter clause.</returns>
 internal FilterClause ParseFilter()
 {
     try
     {
         return(odataUriParser.ParseFilter());
     }
     catch (ODataException ex)
     {
         throw new DataServiceException(400, null, ex.Message, null, ex);
     }
 }
예제 #29
0
        public void ExceptionSholdThrowForFunctionImport_EnableCaseInsensitive()
        {
            ODataUriParser parser = new ODataUriParser(this.model, this.serviceRoot, new Uri(orderBase, "?$filter=HasLotsOfOrders() eq 3"));

            parser.Resolver = new ODataUriResolver {
                EnableCaseInsensitive = true
            };

            Action action = () => parser.ParseFilter();

            action.ShouldThrow <ODataException>().WithMessage("An unknown function with name 'HasLotsOfOrders' was found. This may also be a function import or a key lookup on a navigation property, which is not allowed.");
        }
예제 #30
0
        private static void FilterOnOpenProperty()
        {
            Console.WriteLine("FilterOnOpenProperty");
            var parser = new ODataUriParser(
                extModel.Model,
                ServiceRoot,
                new Uri("http://demo/odata.svc/Resources?$filter=Name eq 'w'"));

            var filter = parser.ParseFilter();

            Console.WriteLine(filter.Expression.ToLogString());
        }