Ejemplo n.º 1
0
        public override void OnResultExecuted(ResultExecutedContext resultExecutedContext)
        {
            base.OnResultExecuted(resultExecutedContext);

            if (resultExecutedContext == null)
            {
                throw new ArgumentNullException("resultExecutedContext", "Cannot apply OData Query with a null execution context.");
            }

            if (resultExecutedContext.HttpContext == null)
            {
                throw new ArgumentException("The HttpContext was null. Could not process OData Query request.");
            }

            var response = resultExecutedContext.HttpContext.Response;
            var request = resultExecutedContext.HttpContext.Request;

            var result = resultExecutedContext.Result;

            if (result != null)
            {
                var resultType = result.GetType();

                var responseType = resultType.GetGenericArguments().Single();

                var url = request.RawUrl;

                var uri = new Uri(url);

                var queryString = uri.Query;

                if (typeof (IQueryable).IsAssignableFrom(responseType) && (String.IsNullOrWhiteSpace(queryString) == false))
                {
                    var itemType = responseType.GetGenericArguments().Single();

                    var parser = new ODataUriParser(new ODataQueryParser(new ODataQueryPartParserStrategy()), new ExpressionODataQueryVisitor(new FilterExpressionBuilder()));

                    var expression = parser.Parse(itemType, uri);

                    var fn = expression.Compile();

                    // TODO: need to pass in current result here
                    var data = fn.DynamicInvoke();

                    var actionResult = Activator.CreateInstance(resultType) as ActionResult;

                    resultExecutedContext.Result = actionResult;
                }
            }
        }
Ejemplo n.º 2
0
        public void ParseSelectExpandForContainment()
        {
            ODataUriParser parser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, new Uri("http://host/People?$select=MyContainedDog&$expand=MyContainedDog"))
            {
                Settings = { SelectExpandLimit = 5 }
            };
            SelectExpandClause       containedSelectExpandClause = parser.ParseSelectAndExpand();
            IEnumerator <SelectItem> enumerator = containedSelectExpandClause.SelectedItems.GetEnumerator();

            enumerator.MoveNext();
            ExpandedNavigationSelectItem expandedNavigationSelectItem = enumerator.Current as ExpandedNavigationSelectItem;

            expandedNavigationSelectItem.Should().NotBeNull();
            (expandedNavigationSelectItem.NavigationSource is IEdmContainedEntitySet).Should().BeTrue();
        }
        internal static TKey IdFromLocationHeader <TKey>(this HttpResponseMessage response)
        {
            var location = response.Headers.Location;

            if (location == null)
            {
                return(default(TKey));
            }

            var parser = new ODataUriParser(model.Value, LocalHost, location);
            var path   = parser.ParsePath();
            var key    = path.OfType <KeySegment>().Single().Keys.Single().Value;

            return((TKey)key);
        }
Ejemplo n.º 4
0
        public void NoneQueryOptionShouldWork()
        {
            var uriParser = new ODataUriParser(HardCodedTestModel.TestModel, ServiceRoot, FullUri);
            var path      = uriParser.ParsePath();

            path.Should().HaveCount(1);
            path.LastSegment.ShouldBeEntitySetSegment(HardCodedTestModel.GetPeopleSet());
            uriParser.ParseFilter().Should().BeNull();
            uriParser.ParseSelectAndExpand().Should().BeNull();
            uriParser.ParseOrderBy().Should().BeNull();
            uriParser.ParseTop().Should().Be(null);
            uriParser.ParseSkip().Should().Be(null);
            uriParser.ParseCount().Should().Be(null);
            uriParser.ParseSearch().Should().BeNull();
        }
Ejemplo n.º 5
0
        [InlineData("ID,Orders/ID,Orders/Customer/ID", "Orders,Orders/Customer", true, "ID")] // deep expand and selects
        public void GetPropertiesToBeSelected_Selects_ExpectedProperties_OnCustomer(
            string select, string expand, bool specialCustomer, string structuralPropertiesToSelect)
        {
            // Arrange
            SelectExpandClause selectExpandClause =
                new ODataUriParser(_model.Model, serviceRoot: null).ParseSelectAndExpand(select, expand, _model.Customer, _model.Customers);
            IEdmEntityType entityType = specialCustomer ? _model.SpecialCustomer : _model.Customer;

            // Act
            SelectExpandNode selectExpandNode = new SelectExpandNode(selectExpandClause, entityType, _model.Model);
            var result = selectExpandNode.SelectedStructuralProperties;

            // Assert
            Assert.Equal(structuralPropertiesToSelect, String.Join(",", result.Select(p => p.Name).OrderBy(n => n)));
        }
Ejemplo n.º 6
0
        public void ParseParameterTemplateWithTemplateParser()
        {
            var uriParser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://host"), new Uri("http://host/People(1)/Fully.Qualified.Namespace.HasHat(onCat={why555})"))
            {
                EnableUriTemplateParsing = true
            };

            IEdmFunction function = HardCodedTestModel.TestModel.FindOperations("Fully.Qualified.Namespace.HasHat").Single(f => f.Parameters.Count() == 2).As <IEdmFunction>();
            var          path     = uriParser.ParsePath();
            OperationSegmentParameter parameter = path.LastSegment.ShouldBeOperationSegment(function).And.Parameters.Single();

            parameter.ShouldBeConstantParameterWithValueType("onCat", new UriTemplateExpression {
                LiteralText = "{why555}", ExpectedType = function.Parameters.Last().Type
            });
        }
Ejemplo n.º 7
0
        public void SpatialLengthNotLineString()
        {
            ODataUriParser parser = this.CreateExpandUriParser(orderBase, "LoggedInEmployee($orderby=geo.length(geometry'Polygon((10 30, 7 28, 6 6, 10 30))') lt 0.5)");

            try
            {
                parser.ParseSelectAndExpand();
                Assert.Fail("Should throw with ODataException");
            }
            catch (ODataException e)
            {
                var expected = ODataExpectedExceptions.ODataException("MetadataBinder_NoApplicableFunctionFound", "geo.length", "geo.length(Edm.GeometryLineString Nullable=true); geo.length(Edm.GeographyLineString Nullable=true)");
                expected.ExpectedMessage.Verifier.VerifyMatch("MetadataBinder_NoApplicableFunctionFound", e.Message, "geo.length", "geo.length(Edm.GeometryLineString Nullable=true); geo.length(Edm.GeographyLineString Nullable=true)");
            }
        }
Ejemplo n.º 8
0
        public void ParseParameterTemplateForFunctionImportWithTemplateParser()
        {
            var uriParser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("IsAddressGood(address={ADDR})", UriKind.Relative))
            {
                EnableUriTemplateParsing = true
            };

            IEdmFunctionImport functionImport = HardCodedTestModel.TestModel.EntityContainer.FindOperationImports("IsAddressGood").Single().As <IEdmFunctionImport>();
            var path = uriParser.ParsePath();
            OperationSegmentParameter parameter = path.LastSegment.ShouldBeOperationImportSegment(functionImport).And.Parameters.Single();

            parameter.ShouldBeConstantParameterWithValueType("address", new UriTemplateExpression {
                LiteralText = "{ADDR}", ExpectedType = functionImport.Function.Parameters.Single().Type
            });
        }
Ejemplo n.º 9
0
        [InlineData("ModelWithInheritance.*", null, true, "specialUpgrade,upgrade")]                      // select wild card actions -> select all
        public void GetActionsToBeSelected_Selects_ExpectedActions(
            string select, string expand, bool specialCustomer, string actionsToSelect)
        {
            // Arrange
            SelectExpandClause selectExpandClause =
                new ODataUriParser(_model.Model, serviceRoot: null).ParseSelectAndExpand(select, expand, _model.Customer, _model.Customers);
            IEdmEntityTypeReference entityType = new EdmEntityTypeReference(specialCustomer ? _model.SpecialCustomer : _model.Customer, false);

            // Act
            SelectExpandNode selectExpandNode = new SelectExpandNode(selectExpandClause, entityType, _model.Model);
            var result = selectExpandNode.SelectedActions;

            // Assert
            Assert.Equal(actionsToSelect, String.Join(",", result.Select(p => p.Name).OrderBy(n => n)));
        }
Ejemplo n.º 10
0
        public void SelectQueryOption()
        {
            var            selectString = "$batch";
            ODataUriParser parser       = this.CreateSelectUriParser(bossBase, selectString);

            try
            {
                parser.ParseSelectAndExpand();
            }
            catch (ODataException e)
            {
                var expected = ODataExpectedExceptions.ODataException("UriSelectParser_SystemTokenInSelectExpand", "$batch", "$batch");
                expected.ExpectedMessage.Verifier.VerifyMatch("UriSelectParser_SystemTokenInSelectExpand", e.Message, "$batch", "$batch");
            }
        }
Ejemplo n.º 11
0
        public void ParseParameterTemplateOfEnumTypeWithTemplateParser()
        {
            var uriParser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("GetPetCount(colorPattern={COLOR})", UriKind.Relative))
            {
                EnableUriTemplateParsing = true
            };

            IEdmOperationImport operationImport = HardCodedTestModel.TestModel.EntityContainer.FindOperationImports("GetPetCount").Single();
            var path = uriParser.ParsePath();
            OperationSegmentParameter parameter = path.LastSegment.ShouldBeOperationImportSegment(operationImport).And.Parameters.Single();

            parameter.ShouldBeConstantParameterWithValueType("colorPattern", new UriTemplateExpression {
                LiteralText = "{COLOR}", ExpectedType = operationImport.Operation.Parameters.Single().Type
            });
        }
Ejemplo n.º 12
0
        public static ODataUriParser ParseQuery(this IEdmModel model, string query)
        {
            query = query ?? string.Empty;

            var path = model.EntityContainer.EntitySets().First().Path.Path.Split('.').Last();

            if (query.StartsWith("?"))
            {
                query = query.Substring(1);
            }

            var parser = new ODataUriParser(model, new Uri($"{path}?{query}", UriKind.Relative));

            return(parser);
        }
Ejemplo n.º 13
0
        public void SpatialLengthPolygonNotFormedCorrectly()
        {
            ODataUriParser parser = this.CreateExpandUriParser(orderBase, "LoggedInEmployee($orderby=geo.length(geometry'Polygon(10 30, 7 28, 6 6, 10 30)') lt 0.5)");

            try
            {
                parser.ParseSelectAndExpand();
                Assert.Fail("Should throw with ODataException");
            }
            catch (ODataException e)
            {
                var expected = ODataExpectedExceptions.ODataException("UriQueryExpressionParser_UnrecognizedLiteralWithReason", "Edm.Geometry", "geometry'Polygon(10 30, 7 28, 6 6, 10 30)'", "11", "geo.length(geometry'Polygon(10 30, 7 28, 6 6, 10 30)') lt 0.5", "Expecting token type \"LeftParen\" with text \"\" but found \"Type:[2] Text:[10]\".");
                expected.ExpectedMessage.Verifier.VerifyMatch("UriQueryExpressionParser_UnrecognizedLiteralWithReason", e.Message, "Edm.Geometry", "geometry'Polygon(10 30, 7 28, 6 6, 10 30)'", "11", "geo.length(geometry'Polygon(10 30, 7 28, 6 6, 10 30)') lt 0.5", "Expecting token type \"LeftParen\" with text \"\" but found \"Type:[2] Text:[10]\".");
            }
        }
Ejemplo n.º 14
0
        public void SelectDoesNotExist()
        {
            var            selectString = "SpaghettiSquash";
            ODataUriParser parser       = this.CreateSelectUriParser(bossBase, selectString);

            try
            {
                parser.ParseSelectAndExpand();
            }
            catch (ODataException e)
            {
                var expected = ODataExpectedExceptions.ODataException("MetadataBinder_PropertyNotDeclared", this.employee.FullName(), "SpaghettiSquash");
                expected.ExpectedMessage.Verifier.VerifyMatch("MetadataBinder_PropertyNotDeclared", e.Message, this.employee.FullName(), "SpaghettiSquash");
            }
        }
Ejemplo n.º 15
0
        [InlineData("ID,Orders/ID,Orders/Customer/ID", "Orders,Orders/Customer", true, "ID")]           // deep expand and selects
        public void GetPropertiesToBeSelected_Selects_ExpectedProperties_OnCustomer(
            string select, string expand, bool specialCustomer, string structuralPropertiesToSelect)
        {
            // Arrange
            SelectExpandClause selectExpandClause =
                new ODataUriParser(_model.Model, serviceRoot: null).ParseSelectAndExpand(select, expand, _model.Customer, _model.Customers);
            IEdmEntityType entityType = specialCustomer ? _model.SpecialCustomer : _model.Customer;

            // Act
            SelectExpandNode selectExpandNode = new SelectExpandNode(selectExpandClause, entityType, _model.Model);
            var result = selectExpandNode.SelectedStructuralProperties;

            // Assert
            Assert.Equal(structuralPropertiesToSelect, String.Join(",", result.Select(p => p.Name).OrderBy(n => n)));
        }
Ejemplo n.º 16
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");
        }
Ejemplo n.º 17
0
        public void ParseQueryOptionsShouldWork(string relativeUriString, bool enableNoDollarQueryOptions)
        {
            var parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri(relativeUriString, UriKind.Relative));

            parser.EnableNoDollarQueryOptions = enableNoDollarQueryOptions;
            parser.ParseSelectAndExpand().Should().NotBeNull();
            parser.ParseFilter().Should().NotBeNull();
            parser.ParseOrderBy().Should().NotBeNull();
            parser.ParseTop().Should().Be(1);
            parser.ParseSkip().Should().Be(2);
            parser.ParseCount().Should().Be(true);
            parser.ParseSearch().Should().NotBeNull();
            parser.ParseSkipToken().Should().Be("abc");
            parser.ParseDeltaToken().Should().Be("def");
        }
Ejemplo n.º 18
0
        public void PathActionReturnsContainedEntity()
        {
            ODataUriParser parser = new ODataUriParser(model, new Uri("http://www.potato.com/"), new Uri("http://www.potato.com/People(1)/Microsoft.Test.Taupo.OData.WCFService.GetBrothers"));
            var            result = parser.ParsePath();

            ApprovalVerify(QueryNodeToStringVisitor.ToString(result));
            OperationSegment operationSegment = result.LastSegment as OperationSegment;

            Assert.IsNotNull(operationSegment);
            Assert.IsTrue(operationSegment.EntitySet is IEdmContainedEntitySet);

            this.TestExtensions("people(1)/microsoft.Test.Taupo.OData.WCFService.GetBrothers",
                                "People(1)/GetBrothers",
                                "people(1)/getbrothers");
        }
Ejemplo n.º 19
0
        public void ParsePathExceptionDataTestWithAlias()
        {
            var    parser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("GetCoolestPersonWithStyle(styleID=@p1)/UndeclaredProperty?@p1=32", UriKind.Relative));
            Action action = () => parser.ParsePath();
            ODataUnrecognizedPathException ex = action.ShouldThrow <ODataUnrecognizedPathException>().And;

            ex.ParsedSegments.As <IEnumerable <ODataPathSegment> >().Count().Should().Be(1);
            ex.CurrentSegment.Should().Be("UndeclaredProperty");
            ex.UnparsedSegments.As <IEnumerable <string> >().Count().Should().Be(0);

            var aliasNode = parser.ParameterAliasNodes;

            aliasNode.Count.Should().Be(1);
            aliasNode["@p1"].ShouldBeConstantQueryNode(32);
        }
Ejemplo n.º 20
0
        public async Task ExecuteGetAsync(Uri requestUri, OeRequestHeaders headers, Stream responseStream, CancellationToken cancellationToken)
        {
            var odataParser = new ODataUriParser(_model, _baseUri, requestUri);

            odataParser.Resolver.EnableCaseInsensitive = true;
            ODataUri odataUri = odataParser.ParseUri();

            if (odataUri.Path.LastSegment is OperationImportSegment)
            {
                await ExecuteOperationAsync(odataUri, headers, null, responseStream, cancellationToken).ConfigureAwait(false);
            }
            else
            {
                await ExecuteQueryAsync(odataUri, headers, responseStream, cancellationToken).ConfigureAwait(false);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Parses the specified URI and wraps the results in a QueryContext.
        /// </summary>
        /// <param name="requestUri">The URI to parse.</param>
        /// <param name="model">The data store model.</param>
        /// <returns>The parsed URI wrapped in a QueryContext.</returns>
        public static QueryContext ParseUri(Uri requestUri, IEdmModel model)
        {
            var requestUriParts = requestUri.OriginalString.Split('?');
            var queryPath       = requestUriParts.First();

            if (requestUriParts.Count() > 1)
            {
                throw new NotSupportedException("Query option is not supported by the service yet.");
            }

            ODataUriParser uriParser = new ODataUriParser(model, ServiceConstants.ServiceBaseUri, new Uri(queryPath, UriKind.Absolute));

            return(new QueryContext {
                QueryPath = uriParser.ParsePath()
            });
        }
Ejemplo n.º 22
0
        public void ParseKeyTemplateWithTemplateParserWithWithWhitespaceOutsideofTempateExpressionTest()
        {
            var uriParser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("People(  {1} )", UriKind.Relative))
            {
                EnableUriTemplateParsing = true
            };

            var path       = uriParser.ParsePath();
            var keySegment = path.LastSegment.As <KeySegment>();
            KeyValuePair <string, object> keypair = keySegment.Keys.Single();

            keypair.Key.Should().Be("ID");
            keypair.Value.As <UriTemplateExpression>().ShouldBeEquivalentTo(new UriTemplateExpression {
                LiteralText = "{1}", ExpectedType = keySegment.EdmType.As <IEdmEntityType>().DeclaredKey.Single().Type
            });
        }
Ejemplo n.º 23
0
        public void UnqualifiedTypeNameShouldNotBeTreatedAsTypeCast()
        {
            var model      = new EdmModel();
            var entityType = new EdmEntityType("NS", "Entity");

            entityType.AddKeys(entityType.AddStructuralProperty("IdStr", EdmPrimitiveTypeKind.String, false));
            var container = new EdmEntityContainer("NS", "Container");
            var set       = container.AddEntitySet("Set", entityType);

            model.AddElements(new IEdmSchemaElement[] { entityType, container });

            var svcRoot     = new Uri("http://host", UriKind.Absolute);
            var parseResult = new ODataUriParser(model, svcRoot, new Uri("http://host/Set/Date", UriKind.Absolute)).ParseUri();

            Assert.True(parseResult.Path.LastSegment is KeySegment);
        }
Ejemplo n.º 24
0
        [InlineData(null, "NS.SpecialCustomer/SpecialOrders", true, "SpecialOrders")] // expand derived navigation property on derived type -> expand requested
        public void GetNavigationPropertiesToBeExpanded_Expands_ExpectedProperties(
            string select, string expand, bool specialCustomer, string navigationPropertiesToExpand)
        {
            // Arrange
            SelectExpandClause selectExpandClause =
                new ODataUriParser(_model.Model, serviceRoot: null).ParseSelectAndExpand(select, expand, _model.Customer, _model.Customers);

            IEdmEntityType entityType = specialCustomer ? _model.SpecialCustomer : _model.Customer;

            // Act
            SelectExpandNode selectExpandNode = new SelectExpandNode(selectExpandClause, entityType, _model.Model);
            var result = selectExpandNode.ExpandedNavigationProperties.Keys;

            // Assert
            Assert.Equal(navigationPropertiesToExpand, String.Join(",", result.Select(p => p.Name).OrderBy(n => n)));
        }
        public void CreateCollection_CopmplexType_Succeeds()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            OrderByClause orderByNode           = ODataUriParser.ParseOrderBy("Street desc, City asc", model.Model, model.Address);

            // Act
            ICollection <OrderByNode> nodes = OrderByNode.CreateCollection(orderByNode);

            // Assert
            Assert.Equal(2, nodes.Count());
            Assert.Equal("Street", (nodes.ToList()[0] as OrderByPropertyNode).Property.Name);
            Assert.Equal(OrderByDirection.Descending, nodes.ToList()[0].Direction);
            Assert.Equal("City", (nodes.ToList()[1] as OrderByPropertyNode).Property.Name);
            Assert.Equal(OrderByDirection.Ascending, nodes.ToList()[1].Direction);
        }
Ejemplo n.º 26
0
        public void ProjectAsWrapper_Element_ProjectedValueDoesNotContainInstance_IfSelectionIsPartial()
        {
            // Arrange
            Customer           customer     = new Customer();
            SelectExpandClause selectExpand = new ODataUriParser(_model.Model, serviceRoot: null).ParseSelectAndExpand("ID,Orders", "Orders", _model.Customer, _model.Customers);
            Expression         source       = Expression.Constant(customer);

            // Act
            Expression projection = _binder.ProjectAsWrapper(source, selectExpand, _model.Customer);

            // Assert
            Assert.Equal(ExpressionType.MemberInit, projection.NodeType);
            Assert.Empty((projection as MemberInitExpression).Bindings.Where(p => p.Member.Name == "Instance"));
            SelectExpandWrapper <Customer> customerWrapper = Expression.Lambda(projection).Compile().DynamicInvoke() as SelectExpandWrapper <Customer>;

            Assert.Null(customerWrapper.Instance);
        }
Ejemplo n.º 27
0
        public void ProjectAsWrapper_Element_ProjectedValueContains_SelectedStructuralProperties()
        {
            // Arrange
            Customer customer = new Customer {
                Name = "OData"
            };
            SelectExpandClause selectExpand = new ODataUriParser(_model.Model, serviceRoot: null).ParseSelectAndExpand("Name,Orders", "Orders", _model.Customer, _model.Customers);
            Expression         source       = Expression.Constant(customer);

            // Act
            Expression projection = _binder.ProjectAsWrapper(source, selectExpand, _model.Customer);

            // Assert
            SelectExpandWrapper <Customer> customerWrapper = Expression.Lambda(projection).Compile().DynamicInvoke() as SelectExpandWrapper <Customer>;

            Assert.Equal(customer.Name, customerWrapper.Container.ToDictionary()["Name"]);
        }
Ejemplo n.º 28
0
        public void TestStringAsEnumInFunctionParameter()
        {
            var uriParser = new ODataUriParser(
                Model,
                ServiceRoot,
                new Uri("http://host/GetColorCmykImport(co='Blue')"))
            {
                Resolver = new ODataUriResolver()
            };

            var path = uriParser.ParsePath();

            path.LastSegment
            .ShouldBeOperationImportSegment(GetColorCmykImport)
            .And.ShouldHaveParameterCount(1)
            .And.Parameters.Single().Value.As <ConstantNode>().Value.ShouldBeODataEnumValue("TestNS.Color", "Blue");
        }
        public void CaseInsensitiveTypeCastInQueryOptionOrderBy2()
        {
            var uriParser = new ODataUriParser(
                Model,
                ServiceRoot,
                new Uri("http://host/People?$orderby=cast(null, Edm.StRing)"))
            {
                Resolver = new ODataUriResolver()
                {
                    EnableCaseInsensitive = true
                }
            };

            var clause = uriParser.ParseOrderBy();

            clause.Expression.ShouldBeSingleValueFunctionCallQueryNode("cast", EdmCoreModel.Instance.GetString(false));
        }
Ejemplo n.º 30
0
        public void TestStringAsEnumInFunctionParameterWithNullValue()
        {
            var uriParser = new ODataUriParser(
                Model,
                ServiceRoot,
                new Uri("http://host/GetColorCmykImport(co=null)"))
            {
                Resolver = new StringAsEnumResolver()
            };

            var path = uriParser.ParsePath();

            path.LastSegment
            .ShouldBeOperationImportSegment(GetColorCmykImport)
            .And.ShouldHaveParameterCount(1)
            .And.ShouldHaveConstantParameter <object>("co", null);
        }
Ejemplo n.º 31
0
        public static void PassingRulesSucceeds()
        {
            const string request = @"company";

            IEdmModel      model  = CreateModel();
            ODataUriParser parser = new ODataUriParser(model, new Uri(request, UriKind.Relative));

            IEnumerable <ODataUrlValidationMessage> errors;

            parser.Validate(dummyRuleset, out errors);
            Assert.Collection <ODataUrlValidationMessage>(errors, (error) =>
            {
                Assert.Equal("dummyCode", error.MessageCode);
                Assert.Equal("dummyMessage", error.Message);
                Assert.Equal(OData.UriParser.Validation.Severity.Warning, error.Severity);
            });
        }
Ejemplo n.º 32
0
        public void ParseKeyTemplateAsSegmentWithTemplateParser()
        {
            var uriParser = new ODataUriParser(HardCodedTestModel.TestModel, new Uri("http://host"), new Uri("http://host/People/{1}"))
            {
                EnableUriTemplateParsing = true,
                UrlKeyDelimiter          = ODataUrlKeyDelimiter.Slash
            };

            var path       = uriParser.ParsePath();
            var keySegment = path.LastSegment.As <KeySegment>();
            KeyValuePair <string, object> keypair = keySegment.Keys.Single();

            keypair.Key.Should().Be("ID");
            keypair.Value.As <UriTemplateExpression>().ShouldBeEquivalentTo(new UriTemplateExpression {
                LiteralText = "{1}", ExpectedType = keySegment.EdmType.As <IEdmEntityType>().DeclaredKey.Single().Type
            });
        }
Ejemplo n.º 33
0
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext == null)
            {
                throw new ArgumentNullException(nameof (actionExecutedContext));
            }

            if (actionExecutedContext.Request == null)
            {
                throw new ArgumentException("The HttpActionExecutedContext cannot contain a null HttpRequestMessage.");
            }

            var request = actionExecutedContext.Request;
            var response = actionExecutedContext.Response;

            IQueryable query;
            if ((response != null) && response.TryGetContentValue(out query))
            {
                if ((request.RequestUri != null) && (String.IsNullOrWhiteSpace(request.RequestUri.Query) == false))
                {
                    var itemType = query.ElementType;

                    var requestUri = request.RequestUri;

                    var parser = new ODataUriParser(new ODataQueryParser(new ODataQueryPartParserStrategy()), new ExpressionODataQueryVisitor(new FilterExpressionBuilder()));

                    var expression = parser.Parse(itemType, requestUri);

                    var fn = expression.Compile();

                    var result = fn.DynamicInvoke(query);

                    var oldContent = (ObjectContent) response.Content;

                    var newContent = new ObjectContent(expression.ReturnType, result, oldContent.Formatter, oldContent.Headers.ContentType.MediaType);

                    response.Content = newContent;
                }
            }
        }
        public void ProjectAsWrapper_Element_ProjectedValueDoesNotContainInstance_IfSelectionIsPartial()
        {
            // Arrange
            Customer customer = new Customer();
            SelectExpandClause selectExpand = new ODataUriParser(_model.Model, serviceRoot: null).ParseSelectAndExpand("ID,Orders", "Orders", _model.Customer, _model.Customers);
            Expression source = Expression.Constant(customer);

            // Act
            Expression projection = _binder.ProjectAsWrapper(source, selectExpand, _model.Customer);

            // Assert
            Assert.Equal(ExpressionType.MemberInit, projection.NodeType);
            Assert.Empty((projection as MemberInitExpression).Bindings.Where(p => p.Member.Name == "Instance"));
            SelectExpandWrapper<Customer> customerWrapper = Expression.Lambda(projection).Compile().DynamicInvoke() as SelectExpandWrapper<Customer>;
            Assert.Null(customerWrapper.Instance);
        }
Ejemplo n.º 35
0
        [InlineData(null, "NS.SpecialCustomer/SpecialOrders", true, "SpecialOrders")] // expand derived navigation property on derived type -> expand requested
        public void GetNavigationPropertiesToBeExpanded_Expands_ExpectedProperties(
            string select, string expand, bool specialCustomer, string navigationPropertiesToExpand)
        {
            // Arrange
            SelectExpandClause selectExpandClause =
                new ODataUriParser(_model.Model, serviceRoot: null).ParseSelectAndExpand(select, expand, _model.Customer, _model.Customers);

            IEdmEntityType entityType = specialCustomer ? _model.SpecialCustomer : _model.Customer;

            // Act
            SelectExpandNode selectExpandNode = new SelectExpandNode(selectExpandClause, entityType, _model.Model);
            var result = selectExpandNode.ExpandedNavigationProperties.Keys;

            // Assert
            Assert.Equal(navigationPropertiesToExpand, String.Join(",", result.Select(p => p.Name).OrderBy(n => n)));
        }
Ejemplo n.º 36
0
        public void ProjectAsWrapper_ProjectedValueContainsConcurrencyProperties_EvenIfNotPresentInSelectClause(string select)
        {
            // Arrange
            Customer customer = new Customer { ID = 42, City = "any" };
            SelectExpandClause selectExpand = new ODataUriParser(_model.Model, serviceRoot: null)
                .ParseSelectAndExpand(select, null, _model.Customer, _model.Customers);
            Expression source = Expression.Constant(customer);

            // Act
            Expression projection = _binder.ProjectAsWrapper(source, selectExpand, _model.Customer);

            // Assert
            SelectExpandWrapper<Customer> customerWrapper = Expression.Lambda(projection).Compile().DynamicInvoke() as SelectExpandWrapper<Customer>;
            Assert.Equal(customer.City, customerWrapper.Container.ToDictionary(new IdentityPropertyMapper())["City"]);
        }
        public void GetPropertiesToBeSelected_Selects_ExpectedProperties_OnExpandedOrders(
            string select, string expand, bool specialOrder, string structuralPropertiesToSelect)
        {
            // Arrange
            SelectExpandClause selectExpandClause =
                new ODataUriParser(_model.Model, serviceRoot: null).ParseSelectAndExpand(select, expand, _model.Customer, _model.Customers);
            SelectExpandClause nestedSelectExpandClause = selectExpandClause.SelectedItems.OfType<ExpandedNavigationSelectItem>().Single().SelectAndExpand;

            IEdmEntityTypeReference entityType = new EdmEntityTypeReference((specialOrder ? _model.SpecialOrder : _model.Order), false);

            // Act
            SelectExpandNode selectExpandNode = new SelectExpandNode(nestedSelectExpandClause, entityType, _model.Model);
            var result = selectExpandNode.SelectedStructuralProperties;

            // Assert
            Assert.Equal(structuralPropertiesToSelect, String.Join(",", result.Select(p => p.Name).OrderBy(n => n)));
        }
        [InlineData("ModelWithInheritance.*", null, true, "specialUpgrade,upgrade")] // select wild card actions -> select all
        public void GetActionsToBeSelected_Selects_ExpectedActions(
            string select, string expand, bool specialCustomer, string actionsToSelect)
        {
            // Arrange
            SelectExpandClause selectExpandClause =
                new ODataUriParser(_model.Model, serviceRoot: null).ParseSelectAndExpand(select, expand, _model.Customer, _model.Customers);
            IEdmEntityTypeReference entityType = new EdmEntityTypeReference(specialCustomer ? _model.SpecialCustomer : _model.Customer, false);

            // Act
            SelectExpandNode selectExpandNode = new SelectExpandNode(selectExpandClause, entityType, _model.Model);
            var result = selectExpandNode.SelectedActions;

            // Assert
            Assert.Equal(actionsToSelect, String.Join(",", result.Select(p => p.Name).OrderBy(n => n)));
        }
        public void WriteObjectInline_CanExpandNavigationProperty_ContainingEdmObject()
        {
            // Arrange
            IEdmEntityType customerType = _customerSet.ElementType;
            IEdmNavigationProperty ordersProperty = customerType.NavigationProperties().Single(p => p.Name == "Orders");

            Mock<IEdmObject> orders = new Mock<IEdmObject>();
            orders.Setup(o => o.GetEdmType()).Returns(ordersProperty.Type);
            object ordersValue = orders.Object;

            Mock<IEdmEntityObject> customer = new Mock<IEdmEntityObject>();
            customer.Setup(c => c.TryGetPropertyValue("Orders", out ordersValue)).Returns(true);
            customer.Setup(c => c.GetEdmType()).Returns(customerType.AsReference());

            SelectExpandClause selectExpandClause = new ODataUriParser(_model, serviceRoot: null).ParseSelectAndExpand("Orders", "Orders", customerType, _customerSet);
            SelectExpandNode selectExpandNode = new SelectExpandNode();
            selectExpandNode.ExpandedNavigationProperties[ordersProperty] = selectExpandClause.SelectedItems.OfType<ExpandedNavigationSelectItem>().Single().SelectAndExpand;

            Mock<ODataWriter> writer = new Mock<ODataWriter>();

            Mock<ODataEdmTypeSerializer> ordersSerializer = new Mock<ODataEdmTypeSerializer>(_serializer.EdmType, ODataPayloadKind.Entry);
            ordersSerializer.Setup(s => s.WriteObjectInline(ordersValue, writer.Object, It.IsAny<ODataSerializerContext>())).Verifiable();

            Mock<ODataSerializerProvider> serializerProvider = new Mock<ODataSerializerProvider>();
            serializerProvider.Setup(p => p.GetEdmTypeSerializer(ordersProperty.Type)).Returns(ordersSerializer.Object);

            Mock<ODataEntityTypeSerializer> serializer = new Mock<ODataEntityTypeSerializer>(_serializer.EdmType, serializerProvider.Object);
            serializer.Setup(s => s.CreateSelectExpandNode(It.IsAny<EntityInstanceContext>())).Returns(selectExpandNode);
            serializer.CallBase = true;

            // Act
            serializer.Object.WriteObjectInline(customer.Object, writer.Object, _writeContext);

            //Assert
            ordersSerializer.Verify();
        }
        public void WriteObjectInline_ExpandsUsingInnerSerializerUsingRightContext_ExpandedNavigationProperties()
        {
            // Arrange
            IEdmEntityType customerType = _customerSet.ElementType;
            IEdmNavigationProperty ordersProperty = customerType.NavigationProperties().Single(p => p.Name == "Orders");
            SelectExpandClause selectExpandClause = new ODataUriParser(_model, serviceRoot: null).ParseSelectAndExpand("Orders", "Orders", customerType, _customerSet);
            SelectExpandNode selectExpandNode = new SelectExpandNode
            {
                ExpandedNavigationProperties = 
                { 
                    { ordersProperty, selectExpandClause.SelectedItems.OfType<ExpandedNavigationSelectItem>().Single().SelectAndExpand }
                }
            };
            Mock<ODataWriter> writer = new Mock<ODataWriter>();

            Mock<ODataEdmTypeSerializer> innerSerializer = new Mock<ODataEdmTypeSerializer>(_serializer.EdmType, ODataPayloadKind.Entry);
            innerSerializer
                .Setup(s => s.WriteObjectInline(_customer.Orders, writer.Object, It.IsAny<ODataSerializerContext>()))
                .Callback((object o, ODataWriter w, ODataSerializerContext context) =>
                    {
                        Assert.Same(context.EntitySet.Name, "Orders");
                        Assert.Same(context.SelectExpandClause, selectExpandNode.ExpandedNavigationProperties.Single().Value);
                    })
                .Verifiable();

            Mock<ODataSerializerProvider> serializerProvider = new Mock<ODataSerializerProvider>();
            serializerProvider.Setup(p => p.GetODataPayloadSerializer(_model, _customer.Orders.GetType())).Returns(innerSerializer.Object);
            Mock<ODataEntityTypeSerializer> serializer = new Mock<ODataEntityTypeSerializer>(_serializer.EdmType, serializerProvider.Object);
            serializer.Setup(s => s.CreateSelectExpandNode(It.IsAny<EntityInstanceContext>())).Returns(selectExpandNode);
            serializer.CallBase = true;
            _writeContext.SelectExpandClause = selectExpandClause;

            // Act
            serializer.Object.WriteObjectInline(_customer, writer.Object, _writeContext);

            // Assert
            innerSerializer.Verify();
            // check that the context is rolled back
            Assert.Same(_writeContext.EntitySet.Name, "Customers");
            Assert.Same(_writeContext.SelectExpandClause, selectExpandClause);
        }
        public void ProjectAsWrapper_Element_ProjectedValueContains_SelectedStructuralProperties()
        {
            // Arrange
            Customer customer = new Customer { Name = "OData" };
            SelectExpandClause selectExpand = new ODataUriParser(_model.Model, serviceRoot: null).ParseSelectAndExpand("Name,Orders", "Orders", _model.Customer, _model.Customers);
            Expression source = Expression.Constant(customer);

            // Act
            Expression projection = _binder.ProjectAsWrapper(source, selectExpand, _model.Customer);

            // Assert
            SelectExpandWrapper<Customer> customerWrapper = Expression.Lambda(projection).Compile().DynamicInvoke() as SelectExpandWrapper<Customer>;
            Assert.Equal(customer.Name, customerWrapper.Container.ToDictionary()["Name"]);
        }
        public void ProjectAsWrapper_Element_ProjectedValueContains_KeyPropertiesEvenIfNotPresentInSelectClause(string select)
        {
            // Arrange
            Customer customer = new Customer { ID = 42, FirstName = "OData" };
            SelectExpandClause selectExpand =
                new ODataUriParser(_model.Model, serviceRoot: null).ParseSelectAndExpand(select, null, _model.Customer, _model.Customers);
            Expression source = Expression.Constant(customer);

            // Act
            Expression projection = _binder.ProjectAsWrapper(source, selectExpand, _model.Customer);

            // Assert
            SelectExpandWrapper<Customer> customerWrapper = Expression.Lambda(projection).Compile().DynamicInvoke() as SelectExpandWrapper<Customer>;
            Assert.Equal(customer.ID, customerWrapper.Container.ToDictionary()["ID"]);
        }