Пример #1
0
        /// <summary>
        /// Resolves a name to an <see cref="IEdmEntitySet"/> instance.
        /// </summary>
        /// <param name="model">The model to resolve the name against.</param>
        /// <param name="entitySetName">The name of the entity set to look up.</param>
        /// <returns>An <see cref="IEdmEntitySet"/> instance with the specified <paramref name="entitySetName"/> or null if no such entity set exists.</returns>
        public static IEdmEntitySet TryResolveEntitySet(this IEdmModel model, string entitySetName)
        {
            ExceptionUtils.CheckArgumentNotNull(model, "model");
            ExceptionUtils.CheckArgumentStringNotNullOrEmpty(entitySetName, "entitySetName");

            IEnumerable <IEdmEntityContainer> entityContainers = model.EntityContainers();

            if (entityContainers == null)
            {
                return(null);
            }

            IEdmEntitySet entitySet = null;

            foreach (IEdmEntityContainer container in entityContainers)
            {
                entitySet = container.FindEntitySet(entitySetName);
                if (entitySet != null)
                {
                    break;
                }
            }

            return(entitySet);
        }
        public void NavigationLinksGenerationConvention_GeneratesLinksWithoutCast_ForBaseProperties()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.EntitySet <SportBike>("vehicles");
            builder.EntitySet <Manufacturer>("manufacturers");

            IEdmModel              model = builder.GetEdmModel();
            IEdmEntitySet          vehiclesEdmEntitySet           = model.EntityContainers().Single().FindEntitySet("vehicles");
            IEdmEntityType         sportbikeType                  = model.AssertHasEntityType(typeof(SportBike));
            IEdmNavigationProperty motorcycleManufacturerProperty = sportbikeType.AssertHasNavigationProperty(model, "Manufacturer", typeof(MotorcycleManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);

            HttpConfiguration configuration = new HttpConfiguration();
            string            routeName     = "Route";

            configuration.Routes.MapODataServiceRoute(routeName, null, model);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.SetConfiguration(configuration);
            request.ODataProperties().RouteName = routeName;

            EntitySetLinkBuilderAnnotation linkBuilder = model.GetEntitySetLinkBuilder(vehiclesEdmEntitySet);

            var serializerContext = new ODataSerializerContext {
                Model = model, EntitySet = vehiclesEdmEntitySet, Url = request.GetUrlHelper()
            };
            var entityContext = new EntityInstanceContext(serializerContext, sportbikeType.AsReference(), new SportBike {
                Model = 2009, Name = "Ninja"
            });

            Uri uri = linkBuilder.BuildNavigationLink(entityContext, motorcycleManufacturerProperty, ODataMetadataLevel.Default);

            Assert.Equal("http://localhost/vehicles(Model=2009,Name='Ninja')/Manufacturer", uri.AbsoluteUri);
        }
        public void GenerateActionLink_GeneratesLinkWithCast_IfEntitySetTypeDoesnotMatchActionEntityType()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var vehicles    = builder.EntitySet <Vehicle>("vehicles");
            var car         = builder.Entity <Car>();
            var paintAction = car.Action("Paint");

            IEdmModel model          = builder.GetEdmModel();
            var       vehiclesEdmSet = model.EntityContainers().Single().FindEntitySet("vehicles");
            var       carEdmType     = model.FindDeclaredType("System.Web.Http.OData.Builder.TestModels.Car") as IEdmEntityType;

            HttpConfiguration configuration = new HttpConfiguration();

            configuration.Routes.MapHttpRoute(ODataRouteNames.InvokeBoundActionWithCast, "{controller}({boundId})/{entityType}/{odataAction}");

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;
            request.Properties[HttpPropertyKeys.HttpRouteDataKey]     = new HttpRouteData(new HttpRoute());

            Uri link = ActionLinkGenerationConvention.GenerateActionLink(
                new EntityInstanceContext(model, vehiclesEdmSet, carEdmType, request.GetUrlHelper(), new Car {
                Model = 2009, Name = "Accord"
            }),
                paintAction);

            Assert.Equal("http://localhost/vehicles(Model=2009,Name='Accord')/System.Web.Http.OData.Builder.TestModels.Car/Paint", link.AbsoluteUri);
        }
        public void GenerateActionLink_GeneratesLinkWithoutCast_IfEntitySetTypeMatchesActionEntityType()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var cars        = builder.EntitySet <Car>("cars");
            var paintAction = cars.EntityType.Action("Paint");

            IEdmModel model      = builder.GetEdmModel();
            var       carsEdmSet = model.EntityContainers().Single().FindEntitySet("cars");

            HttpConfiguration configuration = new HttpConfiguration();

            configuration.Routes.MapHttpRoute(ODataRouteNames.InvokeBoundAction, "{controller}({boundId})/{odataAction}");

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;
            request.Properties[HttpPropertyKeys.HttpRouteDataKey]     = new HttpRouteData(new HttpRoute());

            Uri link = ActionLinkGenerationConvention.GenerateActionLink(
                new EntityInstanceContext(model, carsEdmSet, carsEdmSet.ElementType, request.GetUrlHelper(), new Car {
                Model = 2009, Name = "Accord"
            }),
                paintAction);

            Assert.Equal("http://localhost/cars(Model=2009,Name='Accord')/Paint", link.AbsoluteUri);
        }
        public void Apply_Doesnot_Override_UserConfiguration()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var vehicles    = builder.EntitySet <Vehicle>("vehicles");
            var car         = builder.AddEntity(typeof(Car));
            var paintAction = vehicles.EntityType.Action("Paint");

            paintAction.HasActionLink(ctxt => new Uri("http://localhost/ActionTestWorks"));

            _convention.Apply(paintAction, builder);

            IEdmModel model          = builder.GetEdmModel();
            var       vehiclesEdmSet = model.EntityContainers().Single().FindEntitySet("vehicles");
            var       carEdmType     = model.FindDeclaredType("System.Web.Http.OData.Builder.TestModels.Car") as IEdmEntityType;
            var       paintEdmAction = model.GetAvailableProcedures(model.FindDeclaredType("System.Web.Http.OData.Builder.TestModels.Car") as IEdmEntityType).Single();

            HttpConfiguration configuration = new HttpConfiguration();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;
            request.Properties[HttpPropertyKeys.HttpRouteDataKey]     = new HttpRouteData(new HttpRoute());

            ActionLinkBuilder actionLinkBuilder = model.GetActionLinkBuilder(paintEdmAction);

            Uri link = actionLinkBuilder.BuildActionLink(new EntityInstanceContext(model, vehiclesEdmSet, carEdmType, request.GetUrlHelper(), new Car {
                Model = 2009, Name = "Accord"
            }));

            Assert.Equal(
                "http://localhost/ActionTestWorks",
                link.AbsoluteUri);
        }
Пример #6
0
        /// <summary>
        /// Constructs an instance of <see cref="ODataQueryContext"/> with EdmModel and Entity's CLR type.
        /// By default we assume the full name of the CLR type is used for the name for the EntitySet stored in the model.
        /// </summary>
        /// <param name="model">The EdmModel that includes the Entity and EntitySet information.</param>
        /// <param name="entityClrType">The entity's CLR type information.</param>
        public ODataQueryContext(IEdmModel model, Type entityClrType)
        {
            if (model == null)
            {
                throw Error.ArgumentNull("model");
            }

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

            // check if we can successfully retrieve an entitySet from the model with the given entityClrType
            IEnumerable <IEdmEntityContainer> containers = model.EntityContainers();
            List <IEdmEntitySet> entities = new List <IEdmEntitySet>();

            foreach (IEdmEntityContainer container in containers)
            {
                entities.AddRange(container.EntitySets().Where(s => s.ElementType.IsEquivalentTo(model.GetEdmType(entityClrType))));
            }

            if (entities == null || entities.Count == 0)
            {
                throw Error.InvalidOperation(SRResources.EntitySetNotFound, entityClrType.FullName);
            }

            if (entities.Count > 1)
            {
                throw Error.InvalidOperation(SRResources.MultipleEntitySetMatchedClrType, entityClrType.FullName);
            }

            Model         = model;
            EntityClrType = entityClrType;
            EntitySet     = entities[0];
        }
Пример #7
0
        public void Can_DeserializePayload_InUntypedMode()
        {
            // Arrange
            IEdmModel           model   = GetModel();
            IEdmFunctionImport  action  = model.EntityContainers().Single().FunctionImports().SingleOrDefault(f => f.Name == "Complex");
            string              body    = @"{ ""Quantity"": 1 , ""Address"": { ""StreetAddress"":""1 Microsoft Way"", ""City"": ""Redmond"", ""State"": ""WA"", ""ZipCode"": 98052 } }";
            ODataMessageWrapper message = new ODataMessageWrapper(GetStringAsStream(body));

            message.SetHeader("Content-Type", "application/json;odata=verbose");
            ODataMessageReaderSettings settings = new ODataMessageReaderSettings();
            ODataMessageReader         reader   = new ODataMessageReader(message as IODataRequestMessage, settings, model);

            ODataActionPayloadDeserializer deserializer = new ODataActionPayloadDeserializer(new DefaultODataDeserializerProvider());
            ODataPath path = CreatePath(model, action.Name);
            ODataDeserializerContext context = new ODataDeserializerContext {
                Path = path, Model = model, ResourceType = typeof(ODataUntypedActionParameters)
            };

            // Act
            ODataUntypedActionParameters payload = deserializer.Read(reader, typeof(ODataUntypedActionParameters), context) as ODataUntypedActionParameters;

            // Assert
            Assert.NotNull(payload);
            Assert.Same(action, payload.Action);
            Assert.True(payload.ContainsKey("Quantity"));
            Assert.Equal(1, payload["Quantity"]);
            Assert.True(payload.ContainsKey("Address"));
            dynamic address = payload["Address"] as EdmComplexObject;

            Assert.IsType <EdmComplexObject>(address);
            Assert.Equal("1 Microsoft Way", address.StreetAddress);
            Assert.Equal("Redmond", address.City);
            Assert.Equal("WA", address.State);
            Assert.Equal(98052, address.ZipCode);
        }
Пример #8
0
        public void Can_deserialize_payload_with_primitive_parameters()
        {
            string actionName  = "Primitive";
            int    quantity    = 1;
            string productCode = "PCode";
            string body        = "{" + string.Format(@" ""Quantity"": {0} , ""ProductCode"": ""{1}"" ", quantity, productCode) + "}";

            ODataMessageWrapper message = new ODataMessageWrapper(GetStringAsStream(body));

            message.SetHeader("Content-Type", "application/json;odata=verbose");

            IEdmModel                      model        = GetModel();
            ODataMessageReader             reader       = new ODataMessageReader(message as IODataRequestMessage, new ODataMessageReaderSettings(), model);
            ODataActionPayloadDeserializer deserializer = new ODataActionPayloadDeserializer(new DefaultODataDeserializerProvider());
            ODataPath                      path         = CreatePath(model, actionName);
            ODataDeserializerContext       context      = new ODataDeserializerContext {
                Path = path, Model = model
            };
            ODataActionParameters payload = deserializer.Read(reader, context) as ODataActionParameters;

            Assert.NotNull(payload);
            Assert.Same(
                model.EntityContainers().Single().FunctionImports().SingleOrDefault(f => f.Name == "Primitive"),
                ODataActionPayloadDeserializer.GetFunctionImport(context));
            Assert.True(payload.ContainsKey("Quantity"));
            Assert.Equal(quantity, payload["Quantity"]);
            Assert.True(payload.ContainsKey("ProductCode"));
            Assert.Equal(productCode, payload["ProductCode"]);
        }
Пример #9
0
        /// <summary>
        /// Constructs an instance of <see cref="ODataQueryContext"/> with EdmModel and Entity's CLR type. 
        /// By default we assume the full name of the CLR type is used for the name for the EntitySet stored in the model.
        /// </summary>
        /// <param name="model">The EdmModel that includes the Entity and EntitySet information.</param>
        /// <param name="entityClrType">The entity's CLR type information.</param>
        public ODataQueryContext(IEdmModel model, Type entityClrType)
        {
            if (model == null)
            {
                throw Error.ArgumentNull("model");
            }

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

            // check if we can successfully retrieve an entitySet from the model with the given entityClrType
            IEnumerable<IEdmEntityContainer> containers = model.EntityContainers();
            List<IEdmEntitySet> entities = new List<IEdmEntitySet>();
            foreach (IEdmEntityContainer container in containers)
            {
                entities.AddRange(container.EntitySets().Where(s => s.ElementType.IsEquivalentTo(model.GetEdmType(entityClrType))));
            }

            if (entities == null || entities.Count == 0)
            {
                throw Error.InvalidOperation(SRResources.EntitySetNotFound, entityClrType.FullName);
            }

            if (entities.Count > 1)
            {
                throw Error.InvalidOperation(SRResources.MultipleEntitySetMatchedClrType, entityClrType.FullName);
            }

            Model = model;
            EntityClrType = entityClrType;
            EntitySet = entities[0];
        }
Пример #10
0
        public void Can_deserialize_payload_with_primitive_collection_parameters()
        {
            string actionName = "PrimitiveCollection";
            string body       = @"{ ""Name"": ""Avatar"", ""Ratings"": [ 5, 5, 3, 4, 5, 5, 4, 5, 5, 4 ] }";

            int[] expectedRatings       = new int[] { 5, 5, 3, 4, 5, 5, 4, 5, 5, 4 };
            ODataMessageWrapper message = new ODataMessageWrapper(GetStringAsStream(body));

            message.SetHeader("Content-Type", "application/json;odata=verbose");
            IEdmModel          model  = GetModel();
            ODataMessageReader reader = new ODataMessageReader(message as IODataRequestMessage, new ODataMessageReaderSettings(), model);

            ODataActionPayloadDeserializer deserializer = new ODataActionPayloadDeserializer(new DefaultODataDeserializerProvider());
            ODataPath path = CreatePath(model, actionName);
            ODataDeserializerContext context = new ODataDeserializerContext {
                Path = path, Model = model
            };
            ODataActionParameters payload = deserializer.Read(reader, context) as ODataActionParameters;

            Assert.NotNull(payload);
            Assert.Same(
                model.EntityContainers().Single().FunctionImports().SingleOrDefault(f => f.Name == "PrimitiveCollection"),
                ODataActionPayloadDeserializer.GetFunctionImport(context));
            Assert.True(payload.ContainsKey("Name"));
            Assert.Equal("Avatar", payload["Name"]);
            Assert.True(payload.ContainsKey("Ratings"));
            IList <int> ratings = payload["Ratings"] as IList <int>;

            Assert.Equal(10, ratings.Count);
            Assert.True(expectedRatings.Zip(ratings, (expected, actual) => expected - actual).All(diff => diff == 0));
        }
Пример #11
0
        public void ModelBuilder_BindsToTheClosestEntitySet_ForNavigationProperties()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.EntitySet <Vehicle>("vehicles");
            builder.EntitySet <CarManufacturer>("car_manufacturers");
            builder.EntitySet <MotorcycleManufacturer>("motorcycle_manufacturers");

            IEdmModel model = builder.GetEdmModel();

            model.AssertHasEntitySet("vehicles", typeof(Vehicle));
            IEdmEntitySet vehicles = model.EntityContainers().Single().FindEntitySet("vehicles");

            IEdmEntityType car        = model.AssertHasEntityType(typeof(Car));
            IEdmEntityType motorcycle = model.AssertHasEntityType(typeof(Motorcycle));
            IEdmEntityType sportbike  = model.AssertHasEntityType(typeof(SportBike));

            Assert.Equal(2, vehicles.NavigationTargets.Count());
            vehicles.AssertHasNavigationTarget(
                car.AssertHasNavigationProperty(model, "Manufacturer", typeof(CarManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne),
                "car_manufacturers");
            vehicles.AssertHasNavigationTarget(
                motorcycle.AssertHasNavigationProperty(model, "Manufacturer", typeof(MotorcycleManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne),
                "motorcycle_manufacturers");
            vehicles.AssertHasNavigationTarget(
                sportbike.AssertHasNavigationProperty(model, "Manufacturer", typeof(MotorcycleManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne),
                "motorcycle_manufacturers");
        }
Пример #12
0
        public void ModelBuilder_Ignores_IgnoredTypeAndTheirDerivedTypes()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.EntitySet <Vehicle>("Vehicles");
            builder.Ignore <Motorcycle>();

            IEdmModel model = builder.GetEdmModel();

            // ignore motorcycle, sportbike and MotorcycleManufacturer
            Assert.Equal(_totalExpectedSchemaTypesForVehiclesModel - 3, model.SchemaElements.Count());
            Assert.Equal(1, model.EntityContainers().Single().EntitySets().Count());
            model.AssertHasEntitySet("Vehicles", typeof(Vehicle));

            var vehicle = model.AssertHasEntityType(typeof(Vehicle));

            Assert.Equal(2, vehicle.Key().Count());
            Assert.Equal(3, vehicle.Properties().Count());
            vehicle.AssertHasKey(model, "Model", EdmPrimitiveTypeKind.Int32);
            vehicle.AssertHasKey(model, "Name", EdmPrimitiveTypeKind.String);
            vehicle.AssertHasPrimitiveProperty(model, "WheelCount", EdmPrimitiveTypeKind.Int32, isNullable: false);

            var car = model.AssertHasEntityType(typeof(Car));

            Assert.Equal(vehicle, car.BaseEntityType());
            Assert.Equal(2, car.Key().Count());
            Assert.Equal(5, car.Properties().Count());
            car.AssertHasPrimitiveProperty(model, "SeatingCapacity", EdmPrimitiveTypeKind.Int32, isNullable: false);
            car.AssertHasNavigationProperty(model, "Manufacturer", typeof(CarManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);
        }
        public void NavigationLinksGenerationConvention_GeneratesLinksWithCast_ForDerivedProperties()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.EntitySet <Vehicle>("vehicles");
            builder.EntitySet <Manufacturer>("manufacturers");

            IEdmModel              model = builder.GetEdmModel();
            IEdmEntitySet          vehiclesEdmEntitySet = model.EntityContainers().Single().FindEntitySet("vehicles");
            IEdmEntityType         carType = model.AssertHasEntityType(typeof(Car));
            IEdmNavigationProperty carManufacturerProperty = carType.AssertHasNavigationProperty(model, "Manufacturer", typeof(CarManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);

            HttpConfiguration configuration = new HttpConfiguration();
            string            routeName     = "Route";

            configuration.Routes.MapODataRoute(routeName, null, model);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.SetConfiguration(configuration);
            request.SetODataRouteName(routeName);

            EntitySetLinkBuilderAnnotation linkBuilder = model.GetEntitySetLinkBuilder(vehiclesEdmEntitySet);

            var serializerContext = new ODataSerializerContext {
                Model = model, EntitySet = vehiclesEdmEntitySet, Url = request.GetUrlHelper()
            };
            var entityContext = new EntityInstanceContext(serializerContext, carType.AsReference(), new Car {
                Model = 2009, Name = "Accord"
            });

            Uri uri = linkBuilder.BuildNavigationLink(entityContext, carManufacturerProperty, ODataMetadataLevel.Default);

            Assert.Equal("http://localhost/vehicles(Model=2009,Name='Accord')/System.Web.Http.OData.Builder.TestModels.Car/Manufacturer", uri.AbsoluteUri);
        }
        public void GenerateNavigationLink_GeneratesCorrectLink_EvenIfRouteDataPointsToADifferentController()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var orders = builder.AddEntitySet("Orders", builder.AddEntity(typeof(NavigationLinksGenerationConventionTest_Order)));

            IEdmModel model        = builder.GetEdmModel();
            var       edmEntitySet = model.EntityContainers().Single().EntitySets().Single();

            HttpConfiguration configuration = new HttpConfiguration();
            var route = configuration.Routes.MapHttpRoute(ODataRouteNames.PropertyNavigation, "{controller}({parentId})/{navigationProperty}");
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;
            request.Properties[HttpPropertyKeys.HttpRouteDataKey]     = new HttpRouteData(route, new HttpRouteValueDictionary(new { controller = "Customers" }));

            Uri uri =
                NavigationLinksGenerationConvention.GenerateNavigationPropertyLink(
                    new EntityInstanceContext
            {
                EdmModel       = model,
                EntityInstance = new NavigationLinksGenerationConventionTest_Order {
                    ID = 100
                },
                EntitySet  = edmEntitySet,
                EntityType = edmEntitySet.ElementType,
                UrlHelper  = request.GetUrlHelper()
            },
                    edmEntitySet.ElementType.NavigationProperties().Single(),
                    orders,
                    includeCast: false);

            Assert.Equal("http://localhost/Orders(100)/Customer", uri.AbsoluteUri);
        }
Пример #15
0
        public void Can_deserialize_payload_with_complex_parameters()
        {
            string actionName = "Complex";
            string body       = @"{ ""Quantity"": 1 , ""Address"": { ""StreetAddress"":""1 Microsoft Way"", ""City"": ""Redmond"", ""State"": ""WA"", ""ZipCode"": 98052 } }";

            ODataMessageWrapper message = new ODataMessageWrapper(GetStringAsStream(body));

            message.SetHeader("Content-Type", "application/json;odata=verbose");
            IEdmModel          model  = GetModel();
            ODataMessageReader reader = new ODataMessageReader(message as IODataRequestMessage, new ODataMessageReaderSettings(), model);

            ODataActionPayloadDeserializer deserializer = new ODataActionPayloadDeserializer(new DefaultODataDeserializerProvider());
            ODataPath path = CreatePath(model, actionName);
            ODataDeserializerContext context = new ODataDeserializerContext {
                Path = path, Model = model
            };
            ODataActionParameters payload = deserializer.Read(reader, context) as ODataActionParameters;

            Assert.NotNull(payload);
            Assert.Same(
                model.EntityContainers().Single().FunctionImports().SingleOrDefault(f => f.Name == "Complex"),
                ODataActionPayloadDeserializer.GetFunctionImport(context));
            Assert.True(payload.ContainsKey("Quantity"));
            Assert.Equal(1, payload["Quantity"]);
            Assert.True(payload.ContainsKey("Address"));
            MyAddress address = payload["Address"] as MyAddress;

            Assert.NotNull(address);
            Assert.Equal("1 Microsoft Way", address.StreetAddress);
            Assert.Equal("Redmond", address.City);
            Assert.Equal("WA", address.State);
            Assert.Equal(98052, address.ZipCode);
        }
        public void GenerateActionLink_GeneratesLinkWithoutCast_IfEntitySetTypeMatchesActionEntityType()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var cars        = builder.EntitySet <Car>("cars");
            var paintAction = cars.EntityType.Action("Paint");

            IEdmModel model      = builder.GetEdmModel();
            var       carsEdmSet = model.EntityContainers().Single().FindEntitySet("cars");

            HttpConfiguration configuration = new HttpConfiguration();

            configuration.EnableOData(model);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;
            request.Properties[HttpPropertyKeys.HttpRouteDataKey]     = new HttpRouteData(new HttpRoute());

            Uri link = ActionLinkGenerationConvention.GenerateActionLink(
                new EntityInstanceContext()
            {
                EdmModel       = model,
                EntitySet      = carsEdmSet,
                EntityType     = carsEdmSet.ElementType,
                UrlHelper      = request.GetUrlHelper(),
                PathHandler    = new DefaultODataPathHandler(model),
                EntityInstance = new Car {
                    Model = 2009, Name = "Accord"
                }
            },
                paintAction);

            Assert.Equal("http://localhost/cars(Model=2009,Name='Accord')/Paint", link.AbsoluteUri);
        }
        public void SelfLinksGenerationConvention_Uses_GetByIdWithoutCast_IfDerivedTypeDoesnotHaveNavigationProperty()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var motorcycles = builder.EntitySet <Motorcycle>("motorcycles");

            IEdmModel      model = builder.GetEdmModel();
            IEdmEntitySet  vehiclesEdmEntitySet = model.EntityContainers().Single().EntitySets().Single();
            IEdmEntityType sportbikeType        = model.AssertHasEntityType(typeof(SportBike));

            HttpConfiguration configuration = new HttpConfiguration();

            configuration.Routes.MapHttpRoute(ODataRouteNames.GetById, "{controller}({id})");

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;
            request.Properties[HttpPropertyKeys.HttpRouteDataKey]     = new HttpRouteData(new HttpRoute());

            IEntitySetLinkBuilder linkBuilder = model.GetEntitySetLinkBuilder(vehiclesEdmEntitySet);

            Uri uri = linkBuilder.BuildEditLink(
                new EntityInstanceContext(model, vehiclesEdmEntitySet, sportbikeType, request.GetUrlHelper(), new SportBike {
                Model = 2009, Name = "Ninja"
            }));

            Assert.Equal("http://localhost/motorcycles(Model=2009,Name='Ninja')", uri.AbsoluteUri);
        }
Пример #18
0
        public void CanCreateEdmModel_WithNonBindableAction()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            // Act
            ActionConfiguration actionConfiguration = builder.Action("ActionName");

            actionConfiguration.ReturnsFromEntitySet <Customer>("Customers");

            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmEntityContainer container = model.EntityContainers().SingleOrDefault();

            Assert.NotNull(container);
            Assert.Equal(1, container.Elements.OfType <IEdmFunctionImport>().Count());
            Assert.Equal(1, container.Elements.OfType <IEdmEntitySet>().Count());
            IEdmFunctionImport action = container.Elements.OfType <IEdmFunctionImport>().Single();

            Assert.False(action.IsComposable);
            Assert.True(action.IsSideEffecting);
            Assert.False(action.IsBindable);
            Assert.False(model.IsAlwaysBindable(action));
            Assert.Equal("ActionName", action.Name);
            Assert.NotNull(action.ReturnType);
            Assert.NotNull(action.EntitySet);
            Assert.Equal("Customers", (action.EntitySet as IEdmEntitySetReferenceExpression).ReferencedEntitySet.Name);
            Assert.Equal(typeof(Customer).FullName, (action.EntitySet as IEdmEntitySetReferenceExpression).ReferencedEntitySet.ElementType.FullName());
            Assert.Empty(action.Parameters);
        }
Пример #19
0
        public void CanConfigureManyBinding_For_NavigationPropertiesInDerivedType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            builder
            .EntitySet <Vehicle>("vehicles")
            .HasManyBinding((Motorcycle m) => m.Manufacturers, "manufacturers");

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            var vehicles = model.EntityContainers().Single().FindEntitySet("vehicles");

            Assert.NotNull(vehicles);

            var motorcycle = model.AssertHasEntityType(typeof(Motorcycle));
            var motorcycleManufacturerProperty = motorcycle.AssertHasNavigationProperty(model, "Manufacturers", typeof(MotorcycleManufacturer), isNullable: false, multiplicity: EdmMultiplicity.Many);

            var motorcycleManufacturerPropertyTargetSet = vehicles.FindNavigationTarget(motorcycleManufacturerProperty);

            Assert.NotNull(motorcycleManufacturerPropertyTargetSet);
            Assert.Equal("manufacturers", motorcycleManufacturerPropertyTargetSet.Name);
        }
Пример #20
0
        public void CanAddNavigationLink_For_DerivedNavigationProperty()
        {
            ODataModelBuilder builder = new ODataModelBuilder();

            var vehicle       = builder.AddEntity(typeof(Vehicle));
            var motorcycle    = builder.AddEntity(typeof(Motorcycle)).DerivesFrom(vehicle);
            var manufacturer  = builder.AddEntity(typeof(MotorcycleManufacturer));
            var manufacturers = builder.AddEntitySet("manufacturers", manufacturer);
            var navProperty   = motorcycle.AddNavigationProperty(typeof(Motorcycle).GetProperty("Manufacturer"), EdmMultiplicity.One);

            var vehicles = builder.AddEntitySet("vehicles", vehicle);
            var binding  = vehicles.AddBinding(navProperty, manufacturers);

            vehicles.HasNavigationPropertyLink(navProperty, new NavigationLinkBuilder((ctxt, property) => new Uri("http://works/"), followsConventions: false));

            IEdmModel model             = builder.GetEdmModel();
            var       motorcycleEdmType = model.AssertHasEntityType(typeof(Motorcycle));
            var       edmNavProperty    = motorcycleEdmType.AssertHasNavigationProperty(model, "Manufacturer", typeof(MotorcycleManufacturer), isNullable: false, multiplicity: EdmMultiplicity.One);
            var       vehiclesEdmSet    = model.EntityContainers().Single().FindEntitySet("vehicles");

            Assert.NotNull(model.GetEntitySetLinkBuilder(vehiclesEdmSet));
            Assert.Equal(
                "http://works/",
                model.GetEntitySetLinkBuilder(vehiclesEdmSet).BuildNavigationLink(new EntityInstanceContext(), edmNavProperty, ODataMetadataLevel.Default).AbsoluteUri);
        }
Пример #21
0
        public void CanCreateEdmModel_WithBindableAction()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.Entity <Customer>();

            customer.HasKey(c => c.CustomerId);
            customer.Property(c => c.Name);
            // Act
            ActionConfiguration sendEmail = customer.Action("ActionName");
            IEdmModel           model     = builder.GetEdmModel();

            // Assert
            IEdmEntityContainer container = model.EntityContainers().SingleOrDefault();

            Assert.NotNull(container);
            Assert.Equal(1, container.Elements.OfType <IEdmFunctionImport>().Count());
            IEdmFunctionImport action = container.Elements.OfType <IEdmFunctionImport>().Single();

            Assert.False(action.IsComposable);
            Assert.True(action.IsSideEffecting);
            Assert.True(action.IsBindable);
            Assert.True(model.IsAlwaysBindable(action));
            Assert.Equal("ActionName", action.Name);
            Assert.Null(action.ReturnType);
            Assert.Equal(1, action.Parameters.Count());
            Assert.Equal(BindingParameterConfiguration.DefaultBindingParameterName, action.Parameters.Single().Name);
            Assert.Equal(typeof(Customer).FullName, action.Parameters.Single().Type.FullName());
        }
        public void GenerateNavigationLink_GeneratesCorrectLink_EvenIfRouteDataPointsToADifferentController()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var orders = builder.AddEntitySet("Orders", builder.AddEntity(typeof(NavigationLinksGenerationConventionTest_Order)));

            IEdmModel model        = builder.GetEdmModel();
            var       edmEntitySet = model.EntityContainers().Single().EntitySets().Single();

            HttpConfiguration configuration = new HttpConfiguration();
            string            routeName     = "Route";

            configuration.Routes.MapODataRoute(routeName, null, model);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.SetConfiguration(configuration);
            request.SetODataRouteName(routeName);

            Uri uri =
                NavigationLinksGenerationConvention.GenerateNavigationPropertyLink(
                    new EntityInstanceContext
            {
                EdmModel       = model,
                EntityInstance = new NavigationLinksGenerationConventionTest_Order {
                    ID = 100
                },
                EntitySet  = edmEntitySet,
                EntityType = edmEntitySet.ElementType,
                Url        = request.GetUrlHelper()
            },
                    edmEntitySet.ElementType.NavigationProperties().Single(),
                    orders,
                    includeCast: false);

            Assert.Equal("http://localhost/Orders(100)/Customer", uri.AbsoluteUri);
        }
Пример #23
0
        public void CanConfigureLinks_For_NavigationPropertiesInDerivedType()
        {
            ODataModelBuilder builder = new ODataModelBuilder();

            var vehiclesSet = builder.EntitySet <Vehicle>("vehicles");

            vehiclesSet.HasNavigationPropertyLink(
                vehiclesSet.HasOptionalBinding((Motorcycle m) => m.Manufacturer, "manufacturers").NavigationProperty,
                (ctxt, property) =>
                new Uri(String.Format("http://localhost/vehicles/{0}/{1}/{2}",
                                      ctxt.GetPropertyValue("Model"), ctxt.GetPropertyValue("Name"), property.Name)), followsConventions: false);

            IEdmModel model      = builder.GetEdmModel();
            var       vehicles   = model.EntityContainers().Single().FindEntitySet("vehicles");
            var       motorcycle = model.AssertHasEntityType(typeof(Motorcycle));
            var       motorcycleManufacturerProperty =
                motorcycle.AssertHasNavigationProperty(
                    model, "Manufacturer", typeof(MotorcycleManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);

            var serializerContext = new ODataSerializerContext {
                Model = model, EntitySet = vehicles
            };
            var entityContext = new EntityInstanceContext(serializerContext, motorcycle.AsReference(), new Motorcycle {
                Name = "Motorcycle1", Model = 2009
            });

            Uri link = model.GetEntitySetLinkBuilder(vehicles).BuildNavigationLink(entityContext, motorcycleManufacturerProperty, ODataMetadataLevel.Default);

            Assert.Equal("http://localhost/vehicles/2009/Motorcycle1/Manufacturer", link.AbsoluteUri);
        }
Пример #24
0
        /// <summary>
        /// Calculates the operations that are always bindable to the given type.
        /// </summary>
        /// <param name="bindingType">The binding type in question.</param>
        /// <param name="model">The model to search for operations.</param>
        /// <param name="edmTypeResolver">The edm type resolver to get the parameter type.</param>
        /// <returns>An enumeration of operations that are always bindable to the given type.</returns>
        internal static IEdmFunctionImport[] CalculateAlwaysBindableOperationsForType(IEdmType bindingType, IEdmModel model, EdmTypeResolver edmTypeResolver)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(model != null, "model != null");
            Debug.Assert(edmTypeResolver != null, "edmTypeResolver != null");

            List <IEdmFunctionImport> operations = new List <IEdmFunctionImport>();

            foreach (IEdmEntityContainer container in model.EntityContainers())
            {
                foreach (IEdmFunctionImport functionImport in container.FunctionImports())
                {
                    if (!functionImport.IsBindable || !model.IsAlwaysBindable(functionImport))
                    {
                        continue;
                    }

                    IEdmFunctionParameter bindingParameter = functionImport.Parameters.FirstOrDefault();
                    if (bindingParameter == null)
                    {
                        continue;
                    }

                    IEdmType resolvedBindingType = edmTypeResolver.GetParameterType(bindingParameter).Definition;
                    if (resolvedBindingType.IsAssignableFrom(bindingType))
                    {
                        operations.Add(functionImport);
                    }
                }
            }

            return(operations.ToArray());
        }
        public void SelfLinksGenerationConvention_Uses_GetByIdWithCast_IfDerivedTypeHasNavigationProperty()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var vehicles = builder.EntitySet <Vehicle>("vehicles");

            IEdmModel      model = builder.GetEdmModel();
            IEdmEntitySet  vehiclesEdmEntitySet = model.EntityContainers().Single().EntitySets().Single();
            IEdmEntityType carType = model.AssertHasEntityType(typeof(Car));

            HttpConfiguration configuration = new HttpConfiguration();

            configuration.Routes.MapHttpRoute(ODataRouteNames.GetByIdWithCast, "{controller}({id})/{entitytype}");

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;
            request.Properties[HttpPropertyKeys.HttpRouteDataKey]     = new HttpRouteData(new HttpRoute());

            IEntitySetLinkBuilder linkBuilder = model.GetEntitySetLinkBuilder(vehiclesEdmEntitySet);

            Uri uri = linkBuilder.BuildEditLink(
                new EntityInstanceContext(model, vehiclesEdmEntitySet, carType, request.GetUrlHelper(), new Car {
                Model = 2009, Name = "Accord"
            }));

            Assert.Equal("http://localhost/vehicles(Model=2009,Name='Accord')/System.Web.Http.OData.Builder.TestModels.Car", uri.AbsoluteUri);
        }
Пример #26
0
        public void ActionLink_PreservesFollowsConventions(bool value)
        {
            // Arrange
            ODataModelBuilder            builder                  = new ODataModelBuilder();
            ActionConfiguration          configuration            = new ActionConfiguration(builder, "IgnoreAction");
            Mock <IEdmTypeConfiguration> bindingParameterTypeMock = new Mock <IEdmTypeConfiguration>();

            bindingParameterTypeMock.Setup(o => o.Kind).Returns(EdmTypeKind.Entity);
            Type entityType = typeof(object);

            bindingParameterTypeMock.Setup(o => o.ClrType).Returns(entityType);
            configuration.SetBindingParameter("IgnoreParameter", bindingParameterTypeMock.Object,
                                              alwaysBindable: false);
            configuration.HasActionLink((a) => { throw new NotImplementedException(); }, followsConventions: value);
            builder.AddProcedure(configuration);
            builder.AddEntity(entityType);

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmFunctionImport functionImport =
                model.EntityContainers().Single().Elements.OfType <IEdmFunctionImport>().Single();
            ActionLinkBuilder actionLinkBuilder = model.GetActionLinkBuilder(functionImport);

            Assert.Equal(value, actionLinkBuilder.FollowsConventions);
        }
Пример #27
0
        private static ODataPath CreatePath(IEdmModel model, string actionName)
        {
            IEdmFunctionImport functionImport =
                model.EntityContainers().Single().FindFunctionImports(actionName).Single();

            return(new ODataPath(new ActionPathSegment(functionImport)));
        }
        public void NavigationLinksGenerationConvention_GeneratesLinksWithCast_ForDerivedProperties()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.EntitySet <Vehicle>("vehicles");
            builder.EntitySet <Manufacturer>("manufacturers");

            IEdmModel              model = builder.GetEdmModel();
            IEdmEntitySet          vehiclesEdmEntitySet = model.EntityContainers().Single().FindEntitySet("vehicles");
            IEdmEntityType         carType = model.AssertHasEntityType(typeof(Car));
            IEdmNavigationProperty carManufacturerProperty = carType.AssertHasNavigationProperty(model, "Manufacturer", typeof(CarManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);

            HttpConfiguration configuration = new HttpConfiguration();

            configuration.Routes.MapHttpRoute(ODataRouteNames.PropertyNavigationWithCast, "{controller}({parentid})/{entitytype}/{navigationproperty}");

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;
            request.Properties[HttpPropertyKeys.HttpRouteDataKey]     = new HttpRouteData(new HttpRoute());

            IEntitySetLinkBuilder linkBuilder = model.GetEntitySetLinkBuilder(vehiclesEdmEntitySet);

            Uri uri = linkBuilder.BuildNavigationLink(
                new EntityInstanceContext(model, vehiclesEdmEntitySet, carType, request.GetUrlHelper(), new Car {
                Model = 2009, Name = "Accord"
            }),
                carManufacturerProperty);

            Assert.Equal("http://localhost/vehicles(Model=2009,Name='Accord')/System.Web.Http.OData.Builder.TestModels.Car/Manufacturer", uri.AbsoluteUri);
        }
        public void SelfLinksGenerationConvention_Throws_If_RouteInCorrect()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var motorcycles = builder.EntitySet <Motorcycle>("motorcycles");

            IEdmModel      model = builder.GetEdmModel();
            IEdmEntitySet  vehiclesEdmEntitySet = model.EntityContainers().Single().EntitySets().Single();
            IEdmEntityType sportbikeType        = model.AssertHasEntityType(typeof(SportBike));

            HttpConfiguration configuration = new HttpConfiguration();

            configuration.Routes.MapHttpRoute(ODataRouteNames.GetById, "{Cntroller}({id})");

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;
            request.Properties[HttpPropertyKeys.HttpRouteDataKey]     = new HttpRouteData(new HttpRoute());

            IEntitySetLinkBuilder linkBuilder = model.GetEntitySetLinkBuilder(vehiclesEdmEntitySet);

            Assert.Throws <InvalidOperationException>(
                () => linkBuilder.BuildEditLink(new EntityInstanceContext(model, vehiclesEdmEntitySet, sportbikeType, request.GetUrlHelper(), new SportBike {
                Model = 2009, Name = "Ninja"
            })),
                "EditLink generation failed. Check that you have the 'OData.GetById' route correctly registered.");
        }
Пример #30
0
        public void GenerateSelfLinkWithCast_Works()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var vehicles = builder.AddEntitySet("cars", builder.AddEntity(typeof(Car)));

            IEdmModel     model            = builder.GetEdmModel();
            IEdmEntitySet carsEdmEntitySet = model.EntityContainers().Single().EntitySets().Single();

            HttpConfiguration configuration = new HttpConfiguration();
            string            routeName     = "Route";

            configuration.Routes.MapODataRoute(routeName, null, model);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.SetConfiguration(configuration);
            request.SetODataRouteName(routeName);

            string idLink =
                SelfLinksGenerationConvention.GenerateSelfLink(
                    vehicles,
                    new EntityInstanceContext()
            {
                EdmModel       = model,
                EntitySet      = carsEdmEntitySet,
                EntityType     = carsEdmEntitySet.ElementType,
                Url            = request.GetUrlHelper(),
                EntityInstance = new Car {
                    Model = 2009, Name = "Accord"
                }
            },
                    includeCast: true);

            Assert.Equal("http://localhost/cars(Model=2009,Name='Accord')/System.Web.Http.OData.Builder.TestModels.Car", idLink);
        }
        public void GenerateSelfLinkWithoutCast_Works()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var vehicles = builder.AddEntitySet("cars", builder.AddEntity(typeof(Car)));

            IEdmModel     model            = builder.GetEdmModel();
            IEdmEntitySet carsEdmEntitySet = model.EntityContainers().Single().EntitySets().Single();

            HttpConfiguration configuration = new HttpConfiguration();

            configuration.Routes.MapHttpRoute(ODataRouteNames.GetById, "{controller}({id})");

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;
            request.Properties[HttpPropertyKeys.HttpRouteDataKey]     = new HttpRouteData(new HttpRoute());

            Uri uri =
                SelfLinksGenerationConvention.GenerateSelfLink(
                    vehicles,
                    new EntityInstanceContext(model, carsEdmEntitySet, carsEdmEntitySet.ElementType, request.GetUrlHelper(), new Car {
                Model = 2009, Name = "Accord"
            }),
                    includeCast: false);

            Assert.Equal("http://localhost/cars(Model=2009,Name='Accord')", uri.AbsoluteUri);
        }
 public UnboundFunctionPathSegmentTest()
 {
     ODataModelBuilder builder = new ODataModelBuilder();
     builder.EntityType<MyCustomer>().HasKey(c => c.Id).Property(c => c.Name);
     builder.EntitySet<MyCustomer>("Customers");
     FunctionConfiguration function = builder.Function("TopCustomer");
     function.ReturnsFromEntitySet<MyCustomer>("Customers");
     builder.Function("MyFunction").Returns<string>();
     _model = builder.GetEdmModel();
     _container = _model.EntityContainers().Single();
 }
 public UnboundActionPathSegmentTest()
 {
     ODataModelBuilder builder = new ODataModelBuilder();
     builder.Entity<MyCustomer>().HasKey(c => c.Id).Property(c => c.Name);
     builder.EntitySet<MyCustomer>("Customers");
     ActionConfiguration action = builder.Action("CreateCustomer");
     action.ReturnsFromEntitySet<MyCustomer>("Customers");
     builder.Action("MyAction").Returns<string>();
     builder.Action("ActionWithoutReturn");
     _model = builder.GetEdmModel();
     _container = _model.EntityContainers().Single();
 }
 public ODataEntityDeserializerTests()
 {
     _edmModel = EdmTestHelpers.GetModel();
     IEdmEntitySet entitySet = _edmModel.EntityContainers().Single().FindEntitySet("Products");
     _readContext = new ODataDeserializerContext
     {
         Path = new ODataPath(new EntitySetPathSegment(entitySet)),
         Model = _edmModel
     };
     _productEdmType = _edmModel.GetEdmTypeReference(typeof(Product)).AsEntity();
     _supplierEdmType = _edmModel.GetEdmTypeReference(typeof(Supplier)).AsEntity();
     _deserializerProvider = new DefaultODataDeserializerProvider();
 }
        /// <summary>
        /// Constructs a concurrent cache for looking up bindable procedures for any EntityType in the provided model.
        /// </summary>
        public BindableProcedureFinder(IEdmModel model)
        {
            var query =
                from ec in model.EntityContainers()
                from fi in ec.FunctionImports()
                where fi.IsBindable && fi.Parameters.First().Type.TypeKind() == EdmTypeKind.Entity
                group fi by fi.Parameters.First().Type.Definition into fgroup
                select new { EntityType = fgroup.Key as IEdmEntityType, BindableFunctions = fgroup.ToList() };

            foreach (var match in query)
            {
                _map[match.EntityType] = match.BindableFunctions;
            }
        }
Пример #36
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ODataPathParser" /> class.
        /// </summary>
        /// <param name="model">The model to use for segment parsing.</param>
        public ODataPathParser(IEdmModel model)
        {
            if (model == null)
            {
                throw Error.ArgumentNull("model");
            }

            IEnumerable<IEdmEntityContainer> containers = model.EntityContainers();
            int containerCount = containers.Count();
            if (containerCount != 1)
            {
                throw Error.InvalidOperation(SRResources.ParserModelMustHaveOneContainer, containerCount);
            }
            Model = model;
            Container = containers.Single();
        }
 private static ODataPath CreatePath(IEdmModel model, string actionName)
 {
     IEdmActionImport actionImport =
         model.EntityContainers().Single().FindOperationImports(actionName).Single() as IEdmActionImport;
     Assert.NotNull(actionImport);
     return new ODataPath(new ActionPathSegment(actionImport));
 }
 static ODataActionPayloadDeserializerTest()
 {
     _model = GetModel();
     _container = _model.EntityContainers().SingleOrDefault();
     _deserializer = new ODataActionPayloadDeserializer(new DefaultODataDeserializerProvider());
 }
 private static IEdmEntityContainer ExtractEntityContainer(IEdmModel model)
 {
     IEnumerable<IEdmEntityContainer> containers = model.EntityContainers();
     int containerCount = containers.Count();
     if (containerCount != 1)
     {
         throw Error.Argument("model", SRResources.ParserModelMustHaveOneContainer, containerCount);
     }
     return containers.Single();
 }
Пример #40
0
        /// <summary>
        /// Constructs an instance of <see cref="ODataQueryContext"/> with EdmModel, Entity's CLR type and the corresponding
        /// EntitySet stored in the model. If the given EntitySet is not in the model, this constructor will throw.
        /// </summary>
        /// <param name="model">The EdmModel that includes the Entity and EntitySet information.</param>
        /// <param name="entityClrType">The entity's CLR type information.</param>
        /// <param name="entitySet">The corresponding EntitySet stored in the model.</param>
        public ODataQueryContext(IEdmModel model, Type entityClrType, IEdmEntitySet entitySet)
        {
            if (model == null)
            {
                throw Error.ArgumentNull("model");
            }

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

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

            // check if the model contains the entitySet
            IEnumerable<IEdmEntityContainer> containers = model.EntityContainers();
            if (containers != null)
            {
                IEdmEntityContainer singleContainer = containers.Single();

                if (singleContainer != null)
                {
                    IEnumerable<IEdmEntitySet> entitySets = singleContainer.EntitySets();
                    if (!entitySets.Contains(entitySet))
                    {
                        throw Error.Argument(parameterName: "entitySet", messageFormat: SRResources.EntitySetMustBeInTheModel);
                    }
                }
            }

            // Check if the model contains the entityClrType
            IEdmEntityType edmType = model.GetEdmType(entityClrType) as IEdmEntityType;
            if (edmType == null)
            {
                throw Error.Argument("entityClrType", SRResources.EntityClrTypeNotFound, entityClrType.FullName);
            }

            // Check if the entitySetName matches the entityClrType
            if (!edmType.IsEquivalentTo(entitySet.ElementType))
            {
                throw Error.Argument("entityClrType", SRResources.EntityClrTypeNotMatchEntitySet, entityClrType.FullName, entitySet.Name);
            }

            // Now we can set everything
            Model = model;
            EntityClrType = entityClrType;
            EntitySet = entitySet;
        }
Пример #41
0
        /// <summary>
        /// Constructs an instance of <see cref="ODataQueryContext"/> with EdmModel, Entity's CLR type and the name
        /// of EntitySet stored in the model.
        /// </summary>
        /// <param name="model">The EdmModel that includes the Entity and EntitySet information.</param>
        /// <param name="entityClrType">The entity's CLR type information.</param>
        /// <param name="entitySetName">The name of EntitySet stored in the model.</param>
        public ODataQueryContext(IEdmModel model, Type entityClrType, string entitySetName)
        {
            if (model == null)
            {
                throw Error.ArgumentNull("model");
            }

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

            if (String.IsNullOrEmpty(entitySetName))
            {
                throw Error.ArgumentNullOrEmpty("entitySetName");
            }

            // check if we can successfully retrieve an entitySet from the model with the given entitySetName
            IEnumerable<IEdmEntityContainer> containers = model.EntityContainers();
            foreach (IEdmEntityContainer container in containers)
            {
                EntitySet = container.FindEntitySet(entitySetName);

                if (EntitySet != null)
                {
                    break;
                }
            }

            if (EntitySet == null)
            {
                throw Error.Argument("entitySetName", SRResources.EntitySetNotFoundForName, entitySetName);
            }

            // Check if the model contains the entityClrType
            IEdmEntityType edmType = model.GetEdmType(entityClrType) as IEdmEntityType;
            if (edmType == null)
            {
                throw Error.Argument("entityClrType", SRResources.EntityClrTypeNotFound, entityClrType.FullName);
            }

            // Check if the entitySetName matches the entityClrType
            if (!edmType.IsEquivalentTo(EntitySet.ElementType))
            {
                throw Error.Argument("entityClrType", SRResources.EntityClrTypeNotMatchEntitySetName, entityClrType.FullName, entitySetName);
            }

            Model = model;
            EntityClrType = entityClrType;
        }
Пример #42
0
        /// <summary>
        /// Tries to get entity set.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="model">The model.</param>
        /// <param name="entitySet">The entity set.</param>
        /// <returns>
        /// True  if it gets and entitySet or false if it can't
        /// </returns>
        public static bool TryGetEntitySetAndEntityType(Uri uri, IEdmModel model, out IEdmEntitySet entitySet)
        {
            IEdmEntitySet currentEntitySet = null;

            entitySet = null;
            foreach (string segment in uri.Segments)
            {
                string segmentValue = segment.Replace("/", String.Empty);

                if (segmentValue.Length == 0)
                {
                    continue;
                }

                // lopping off key pieces as we don't care
                int i = segment.IndexOf('(');
                if (i > -1)
                {
                    segmentValue = segment.Remove(i);
                }

                IEdmEntityContainer container = model.EntityContainers().First();
                // If there is no entitySet we need to find out which one it is
                if (currentEntitySet == null)
                {
                    IEdmEntitySet foundEntitySet = container.FindEntitySet(segmentValue);
                    if (foundEntitySet != null)
                    {
                        currentEntitySet = foundEntitySet;
                    }
                    else
                    {
                        // check to see if there the current segment is a service operation
                        IEdmFunctionImport functionImport = container.FunctionImports().SingleOrDefault(fi => fi.Name == segmentValue);
                        if (functionImport != null)
                        {
                            IEdmEntitySet functionEntitySet = null;
                            if (functionImport.TryGetStaticEntitySet(out functionEntitySet))
                            {
                                currentEntitySet = functionEntitySet;
                            }
                        }
                    }
                }
                else
                {
                    IEdmNavigationProperty navigationProperty = currentEntitySet.ElementType.NavigationProperties().SingleOrDefault(np => np.Name == segmentValue);
                    if (navigationProperty != null)
                    {
                        currentEntitySet = currentEntitySet.FindNavigationTarget(navigationProperty);
                    }
                    else
                    {
                        // Need to update this a little so it works for Actions/Functions
                        IEdmFunctionImport functionImport = container.FunctionImports().SingleOrDefault(fi => fi.IsBindable == true && fi.Name == segmentValue);
                        if (functionImport != null)
                        {
                            IEdmEntitySet functionEntitySet = null;
                            if (functionImport.TryGetStaticEntitySet(out functionEntitySet))
                            {
                                currentEntitySet = functionEntitySet;
                            }
                        }
                    }
                }
            }

            if (currentEntitySet != null)
            {
                entitySet = currentEntitySet;
                return true;
            }

            entitySet = null;

            return false;
        }
 private static IEdmNavigationProperty GetNavigationProperty(IEdmModel model)
 {
     return
         model.EntityContainers().Single().EntitySets().First().NavigationPropertyBindings.Single().NavigationProperty;
 }
 private static ODataPath CreatePath(IEdmModel model, string actionName)
 {
     IEdmFunctionImport functionImport =
         model.EntityContainers().Single().FindFunctionImports(actionName).Single();
     return new ODataPath(new ActionPathSegment(functionImport));
 }