コード例 #1
0
        public void AdvancedMapODataServiceRoute_ConfiguresARoute_WithAnODataRouteAndVersionConstraints()
        {
            // Arrange
            HttpRouteCollection routes = new HttpRouteCollection();
            HttpConfiguration config = new HttpConfiguration(routes);
            IEdmModel model = new EdmModel();
            string routeName = "name";
            string routePrefix = "prefix";
            var pathHandler = new DefaultODataPathHandler();
            var conventions = new List<IODataRoutingConvention>();

            // Act
            config.MapODataServiceRoute(routeName, routePrefix, model, pathHandler, conventions);

            // Assert
            IHttpRoute odataRoute = routes[routeName];
            Assert.Single(routes);
            Assert.Equal(routePrefix + "/{*odataPath}", odataRoute.RouteTemplate);
            Assert.Equal(2, odataRoute.Constraints.Count);

            var odataPathConstraint = Assert.Single(odataRoute.Constraints.Values.OfType<ODataPathRouteConstraint>());
            Assert.Same(model, odataPathConstraint.EdmModel);
            Assert.IsType<DefaultODataPathHandler>(odataPathConstraint.PathHandler);
            Assert.NotNull(odataPathConstraint.RoutingConventions);

            var odataVersionConstraint = Assert.Single(odataRoute.Constraints.Values.OfType<ODataVersionConstraint>());
            Assert.NotNull(odataVersionConstraint.Version);
            Assert.Equal(ODataVersion.V4, odataVersionConstraint.Version);
        }
コード例 #2
0
        public void Match_UsesODataDefaultRoutingConventions_IfControllerFound(string expectedControllerName,
            string entitySetName)
        {
            // Arrange
            const string routeName = "api";
            var request = new HttpRequestMessage(HttpMethod.Get, "http://any/" + entitySetName);
            var routeCollection = new HttpRouteCollection { { routeName, new HttpRoute() } };
            var config = new HttpConfiguration(routeCollection);
            request.SetConfiguration(config);
            var pathHandler = new DefaultODataPathHandler();
            var model = GetEdmModel();
            config.MapHttpAttributeRoutes();
            var conventions = config.CreateODataDomainRoutingConventions<NorthwindDomainController>(model);
            var constraint = new DefaultODataPathRouteConstraint(pathHandler, model, routeName, conventions);
            config.EnsureInitialized();
            var values = new Dictionary<string, object>
            {
                { ODataRouteConstants.ODataPath, entitySetName },
            };

            // Act
            var matched = constraint.Match(request, route: null, parameterName: null, values: values,
                routeDirection: HttpRouteDirection.UriResolution);

            // Assert
            Assert.True(matched);
            Assert.Equal(expectedControllerName, values[ODataRouteConstants.Controller]);
        }
コード例 #3
0
        public static void UpdateConfiguration(HttpConfiguration configuration)
        {
            var controllers = new[] { typeof(EmployeesController), typeof(MetadataController) };
            TestAssemblyResolver resolver = new TestAssemblyResolver(new TypesInjectionAssembly(controllers));

            configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            configuration.Services.Replace(typeof(IAssembliesResolver), resolver);

            configuration.Routes.Clear();

            IEdmModel edmModel = UnBoundFunctionEdmModel.GetEdmModel();
            DefaultODataPathHandler pathHandler = new DefaultODataPathHandler();

            // only with attribute routing & metadata routing convention
            IList<IODataRoutingConvention> routingConventions = new List<IODataRoutingConvention>
            {
                new AttributeRoutingConvention(edmModel, configuration),
                new MetadataRoutingConvention()
            };
            configuration.MapODataServiceRoute("AttributeRouting", "AttributeRouting", edmModel, pathHandler, routingConventions);

            // only with convention routing
            configuration.MapODataServiceRoute("ConventionRouting", "ConventionRouting", edmModel, pathHandler, ODataRoutingConventions.CreateDefault());
            configuration.EnsureInitialized();
        }
コード例 #4
0
        public void ParserThrows_SerializationException_UnqualifiedBoundAction(string url)
        {
            // Arrange
            IEdmModel model = GetModel();

            // Act
            ODataPath path = new DefaultODataPathHandler().Parse(model, url);
            Assert.NotNull(path); // Guard
            ODataDeserializerContext context = new ODataDeserializerContext { Path = path, Model = model };

            // Assert
            Assert.Throws<SerializationException>(() => ODataActionPayloadDeserializer.GetAction(context),
            "The last segment of the request URI '" + url + "' was not recognized as an OData action.");
        }
コード例 #5
0
        public void Can_find_action_overload_using_bindingparameter_type(string url)
        {
            // Arrange
            IEdmModel model = GetModel();
            ODataPath path = new DefaultODataPathHandler().Parse(model, _serviceRoot, url);
            Assert.NotNull(path); // Guard
            ODataDeserializerContext context = new ODataDeserializerContext { Path = path, Model = model };

            // Act
            IEdmAction action = ODataActionPayloadDeserializer.GetAction(context);

            // Assert
            Assert.NotNull(action);
            Assert.Equal("Wash", action.Name);
        }
コード例 #6
0
        public void Can_find_customized_namespace_action(string url)
        {
            // Arrange
            IEdmModel model = GetModel();
            ODataPath path = new DefaultODataPathHandler().Parse(model, _serviceRoot, url);
            Assert.NotNull(path); // Guard
            ODataDeserializerContext context = new ODataDeserializerContext { Path = path, Model = model };

            // Act
            IEdmAction action = ODataActionPayloadDeserializer.GetAction(context);

            // Assert
            Assert.NotNull(action);
            Assert.Equal("NSAction", action.Name);
        }
コード例 #7
0
        public void Can_Find_Action_QualifiedActionName(string actionName, string url)
        {
            // Arrange
            IEdmModel model = GetModel();

            // Act
            ODataPath path = new DefaultODataPathHandler().Parse(model, _serviceRoot, url);
            Assert.NotNull(path); // Guard
            ODataDeserializerContext context = new ODataDeserializerContext { Path = path, Model = model };
            IEdmAction action = ODataActionPayloadDeserializer.GetAction(context);

            // Assert
            Assert.NotNull(action);
            Assert.Equal(actionName, action.Name);
        }
コード例 #8
0
        public void Can_find_action_overload_using_bindingparameter_type()
        {
            // Arrange
            IEdmModel model = GetModel();
            string url = "Vehicles(8)/System.Web.OData.Builder.TestModels.Car/Wash";
            ODataPath path = new DefaultODataPathHandler().Parse(model, url);
            Assert.NotNull(path); // Guard
            ODataDeserializerContext context = new ODataDeserializerContext { Path = path, Model = model };

            // Act
            IEdmAction action = ODataActionPayloadDeserializer.GetAction(context);

            // Assert
            Assert.NotNull(action);
            Assert.Equal("Wash", action.Name);
        }
コード例 #9
0
        public void Validate_Throws_DollarCountAppliedOnNotCountableCollection(string uri, string message)
        {
            // Arrange
            IEdmModel model = GetEdmModel();
            var pathHandler = new DefaultODataPathHandler();
            string serviceRoot = "http://localhost/";
            ODataPath path = pathHandler.Parse(model, serviceRoot, uri);
            var context = new ODataQueryContext(
                model,
                EdmCoreModel.Instance.GetInt32(false).Definition,
                path);
            var option = new CountQueryOption("true", context);
            var settings = new ODataValidationSettings();

            // Act & Assert
            Assert.Throws<InvalidOperationException>(() => _validator.Validate(option, settings), message);
        }
コード例 #10
0
        public ODataFunctionTests()
        {
            DefaultODataPathHandler pathHandler = new DefaultODataPathHandler();
            HttpConfiguration configuration =
                new[] { typeof(MetadataController), typeof(FCustomersController) }.GetHttpConfiguration();
            var model = GetUnTypedEdmModel();

            // without attribute routing
            configuration.MapODataServiceRoute("odata1", "odata", model, pathHandler, ODataRoutingConventions.CreateDefault());

            // only with attribute routing
            IList<IODataRoutingConvention> routingConventions = new List<IODataRoutingConvention>
            {
                new AttributeRoutingConvention(model, configuration)
            };
            configuration.MapODataServiceRoute("odata2", "attribute", model, pathHandler, routingConventions);

            _client = new HttpClient(new HttpServer(configuration));
        }
コード例 #11
0
        public void AdvancedMapODataServiceRoute_ConfiguresARoute_WithAnODataRouteConstraint()
        {
            HttpRouteCollection routes = new HttpRouteCollection();
            IEdmModel model = new EdmModel();
            string routeName = "name";
            string routePrefix = "prefix";
            var pathHandler = new DefaultODataPathHandler();
            var conventions = new List<IODataRoutingConvention>();

            routes.MapODataServiceRoute(routeName, routePrefix, model, pathHandler, conventions);

            IHttpRoute odataRoute = routes[routeName];
            Assert.Single(routes);
            Assert.Equal(routePrefix + "/{*odataPath}", odataRoute.RouteTemplate);
            var constraint = Assert.Single(odataRoute.Constraints);
            var odataConstraint = Assert.IsType<ODataPathRouteConstraint>(constraint.Value);
            Assert.Same(model, odataConstraint.EdmModel);
            Assert.Same(pathHandler, odataConstraint.PathHandler);
            Assert.Equal(conventions, odataConstraint.RoutingConventions);
        }
コード例 #12
0
        public void Unqualified_Works_CustomUriResolverHandler(string path, string template, string expect)
        {
            // Arrange
            DefaultODataPathHandler pathHandler = new DefaultODataPathHandler
            {
                ResolverSetttings = new ODataUriResolverSetttings
                {
                    CaseInsensitive = true,
                    UnqualifiedNameCall = true
                }
            };

            // Act
            ODataPath odataPath = pathHandler.Parse(_model, _serviceRoot, path);

            // Assert
            Assert.NotNull(odataPath);
            Assert.Equal(template, odataPath.PathTemplate);
            Assert.Equal(expect, odataPath.ToString());
        }
コード例 #13
0
        public void GetSingleEntityEntityType_ReturnsEntityTypeForSingleEntityResources(string odataPath, string typeName)
        {
            // Arrange
            IEdmModel model = SetupModel();
            IODataPathHandler pathHandler = new DefaultODataPathHandler();
            ODataPath path = pathHandler.Parse(model, "http://localhost/any", odataPath);
            // Guard
            Assert.NotNull(path);

            // Act
            IEdmEntityType entityType = ETagMessageHandler.GetSingleEntityEntityType(path);

            // Assert
            Assert.NotNull(entityType);
            Assert.Equal(typeName, entityType.FullName());
        }
コード例 #14
0
 private static ODataPath CreateUnboundPath(string actionName)
 {
     string path = String.Format("{0}", actionName);
     ODataPath odataPath = new DefaultODataPathHandler().Parse(_model, _serviceRoot, path);
     Assert.NotNull(odataPath); // Guard
     return odataPath;
 }
 private static ODataPath CreateBoundPath(string actionName)
 {
     string path = String.Format("Customers(1)/{0}", actionName);
     ODataPath odataPath = new DefaultODataPathHandler().Parse(_model, path);
     Assert.NotNull(odataPath); // Guard
     return odataPath;
 }
コード例 #16
0
            internal static IDictionary<string, string> GetKeys(DefaultODataPathHandler pathHandler, IEdmModel edmModel, string serviceRoot, Uri uri)
            {
                ODataPath odataPath = pathHandler.Parse(edmModel, serviceRoot, uri.ToString());
                KeyValuePathSegment segment = odataPath.Segments.OfType<KeyValuePathSegment>().Last();
                if (segment == null)
                {
                    throw Error.InvalidOperation(SRResources.EntityReferenceMustHasKeySegment, uri);
                }

                return segment.Values;
            }
コード例 #17
0
            internal static object CovertEntityId(object source, ODataEntry entry, IEdmEntityTypeReference entityTypeReference, ODataDeserializerContext readContext)
            {
                Contract.Assert(entry != null);
                Contract.Assert(source != null);

                if (entry.Id == null || entry.Properties.Any())
                {
                    return source;
                }

                HttpRequestMessage request = readContext.Request;
                IEdmModel edmModel = readContext.Model;

                DefaultODataPathHandler pathHandler = new DefaultODataPathHandler();
                string serviceRoot = GetServiceRoot(request);
                IDictionary<string, string> keyValues = GetKeys(pathHandler, edmModel, serviceRoot, entry.Id);

                IList<IEdmStructuralProperty> keys = entityTypeReference.Key().ToList();

                if (keys.Count == 1 && keyValues.Count == 1)
                {
                    object propertyValue = ODataUriUtils.ConvertFromUriLiteral(keyValues.First().Value, ODataVersion.V4, edmModel, keys[0].Type);
                    DeserializationHelpers.SetDeclaredProperty(source, EdmTypeKind.Primitive, keys[0].Name, propertyValue, keys[0], readContext);
                    return source;
                }

                foreach (IEdmStructuralProperty key in keys)
                {
                    string value;
                    if (keyValues.TryGetValue(key.Name, out value))
                    {
                        object propertyValue = ODataUriUtils.ConvertFromUriLiteral(value, ODataVersion.V4, edmModel, key.Type);

                        DeserializationHelpers.SetDeclaredProperty(source, EdmTypeKind.Primitive, key.Name, propertyValue, key, readContext);
                    }
                }

                return source;
            }
コード例 #18
0
        public void GenerateLocationHeader_ForContainment()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            model.Model.SetAnnotationValue(model.OrderLine, new ClrTypeAnnotation(typeof(OrderLine)));
            var path = new DefaultODataPathHandler().Parse(
                model.Model,
                "http://localhost/",
                "MyOrders(1)/OrderLines");
            var request = GetODataRequest(model.Model);
            request.ODataProperties().Model = model.Model;
            request.ODataProperties().Path = path;
            var orderLine = new OrderLine { ID = 2 };
            var createdODataResult = new CreatedODataResult<OrderLine>(
                orderLine,
                _contentNegotiator,
                request,
                _formatters,
                _locationHeader);

            // Act
            var locationHeader = createdODataResult.GenerateLocationHeader();

            // Assert
            Assert.Equal("http://localhost/MyOrders(1)/OrderLines(2)", locationHeader.ToString());
        }
コード例 #19
0
        public void CanParseKeyAsSegmentUrl()
        {
            // Arrange
            string odataPath = "RoutingCustomers/112";
            string expectedText = "112";
            IEdmEntitySet expectedSet = _model.EntityContainer.EntitySets().SingleOrDefault(s => s.Name == "RoutingCustomers");
            var simplifiedParser = new DefaultODataPathHandler();
            simplifiedParser.ResolverSetttings.UrlConventions = ODataUrlConventions.ODataSimplified;

            // Act
            ODataPath path = simplifiedParser.Parse(_model, _serviceRoot, odataPath);
            ODataPathSegment segment = path.Segments.Last();

            // Assert
            Assert.NotNull(segment);
            Assert.Equal(expectedText, segment.ToString());
            Assert.IsType<KeyValuePathSegment>(segment);
            Assert.Same(expectedSet, path.NavigationSource);
            Assert.Same(expectedSet.EntityType(), path.EdmType);
        }
コード例 #20
0
        public void PrefixFreeEnumValue_Works_PrefixFreeResolver(string path, string template, string expect)
        {
            // Arrange & Act
            // Arrange
            DefaultODataPathHandler pathHandler = new DefaultODataPathHandler
            {
                ResolverSetttings = new ODataUriResolverSetttings
                {
                    EnumPrefixFree = true
                }
            };

            // Act
            ODataPath odataPath = pathHandler.Parse(_model, _serviceRoot, path);

            // Assert
            Assert.NotNull(odataPath);
            Assert.Equal(template, odataPath.PathTemplate);
            Assert.Equal(expect, odataPath.ToString());
        }
コード例 #21
0
        public void SendAsync_ReturnsNotFoundForNullEntityResponse()
        {
            // Arrange
            Mock<MediaTypeFormatter> formatter = new Mock<MediaTypeFormatter>();
            formatter.Setup(f => f.CanWriteType(It.IsAny<Type>())).Returns(true);

            HttpResponseMessage originalResponse = new HttpResponseMessage(HttpStatusCode.OK);
            originalResponse.Content = new ObjectContent(typeof(string), null, formatter.Object);

            ODataNullValueMessageHandler handler = new ODataNullValueMessageHandler
            {
                InnerHandler = new TestMessageHandler(originalResponse)
            };

            ODataPath path = new DefaultODataPathHandler().Parse(BuildModel(), "http://localhost/any", "Customers(3)");
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/any");
            request.SetConfiguration(new HttpConfiguration());
            request.ODataProperties().Path = path;

            // Act 
            HttpResponseMessage response = handler.SendAsync(request).Result;

            // Assert
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        }
コード例 #22
0
        public void DefaultUriResolverHandler_Works_CaseInsensitive(string path, string template, string expect)
        {
            // Arrange & Act
            DefaultODataPathHandler pathHandler = new DefaultODataPathHandler
            {
                ResolverSetttings = new ODataUriResolverSetttings
                {
                    CaseInsensitive = true,
                }
            };

            ODataPath odataPath = pathHandler.Parse(_model, _serviceRoot, path);

            // Assert
            Assert.NotNull(odataPath);
            Assert.Equal(template, odataPath.PathTemplate);
            Assert.Equal(expect, odataPath.ToString());
        }
コード例 #23
0
        public void GetResponseStatusCode_ReturnsNoContentForProperties_AndNotFoundForEntities(string odataPath,
            HttpStatusCode? expected)
        {
            // Arrange
            IEdmModel model = BuildModel();
            IODataPathHandler pathHandler = new DefaultODataPathHandler();
            ODataPath path = pathHandler.Parse(model, "http://localhost/any", odataPath);
            // Guard
            Assert.NotNull(path);

            // Act
            HttpStatusCode? statusCode = ODataNullValueMessageHandler.GetUpdatedResponseStatusCodeOrNull(path);

            // Assert
            Assert.Equal(expected, statusCode);
        }
コード例 #24
0
        public void GetODataPayloadSerializer_ReturnsRawValueSerializer_ForDollarCountRequests(string uri, Type elementType)
        {
            // Arrange
            IEdmModel model = ODataCountTest.GetEdmModel();
            Type type = typeof(ICollection<>).MakeGenericType(elementType);
            var request = new HttpRequestMessage();
            var pathHandler = new DefaultODataPathHandler();
            var path = pathHandler.Parse(model, "http://localhost/", uri);
            request.ODataProperties().Path = path;
            ODataSerializerProvider serializerProvider = new DefaultODataSerializerProvider();

            // Act
            var serializer = serializerProvider.GetODataPayloadSerializer(model, type, request);

            // Assert
            Assert.NotNull(serializer);
            var rawValueSerializer = Assert.IsType<ODataRawValueSerializer>(serializer);
            Assert.Equal(ODataPayloadKind.Value, rawValueSerializer.ODataPayloadKind);
        }