public void GetEdmModel_Works_ForOpenComplexTypeWithDerivedDynamicProperty() { // Arrange ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); builder.ComplexType <OpenComplexTypeWithDerivedDynamicProperty>(); // Act IEdmModel model = builder.GetEdmModel(); // Assert Assert.NotNull(model); IEdmComplexType complexType = Assert.Single(model.SchemaElements.OfType <IEdmComplexType>()); Assert.True(complexType.IsOpen); IEdmProperty edmProperty = Assert.Single(complexType.Properties()); Assert.Equal("StringProperty", edmProperty.Name); }
public void DataMemberAttributeEdmPropertyConvention_ConfiguresNonRequiredDataMembersAsOptional() { MockType type = new MockType("Entity") .Property(typeof(int), "ID", new DataMemberAttribute()) .Property(typeof(int), "Count", new DataMemberAttribute()); type.Setup(t => t.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())).Returns(new[] { new DataContractAttribute() }); ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); builder.AddEntityType(type); IEdmModel model = builder.GetEdmModel(); IEdmEntityType entity = model.AssertHasEntityType(type); entity.AssertHasKey(model, "ID", EdmPrimitiveTypeKind.Int32); entity.AssertHasPrimitiveProperty(model, "Count", EdmPrimitiveTypeKind.Int32, isNullable: true); }
private IEdmModel GetModel <T>() where T : class { Type key = typeof(T); IEdmModel value; if (!_modelCache.TryGetValue(key, out value)) { ODataModelBuilder model = ODataConventionModelBuilderFactory.Create(); model.EntitySet <T>("Products"); if (key == typeof(Product)) { model.EntityType <DerivedProduct>().DerivesFrom <Product>(); model.EntityType <DerivedCategory>().DerivesFrom <Category>(); } value = _modelCache[key] = model.GetEdmModel(); } return(value); }
public void Apply_ActionOnDeleteAttribute_Works() { // Arrange Type orderType = typeof(TestOrder); ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); PropertyInfo propertyInfo = orderType.GetProperty("Customer"); EntityTypeConfiguration entity = builder.AddEntityType(orderType); NavigationPropertyConfiguration navProperty = entity.AddNavigationProperty(propertyInfo, EdmMultiplicity.One); navProperty.AddedExplicitly = false; navProperty.HasConstraint(orderType.GetProperty("CustomerId"), typeof(TestCustomer).GetProperty("Id")); // Act new ActionOnDeleteAttributeConvention().Apply(navProperty, entity, builder); // Assert Assert.Equal(EdmOnDeleteAction.Cascade, navProperty.OnDeleteAction); }
public void MapODataServiceRoute_ConfigEnsureInitialized_DoesNotThrowForInvalidPathTemplateWithoutAttributeRouting() { // Arrange var builder = ODataConventionModelBuilderFactory.Create(); builder.EntitySet <Customer>("Customers").EntityType.Ignore(c => c.Name); IEdmModel model = builder.GetEdmModel(); var configuration = RoutingConfigurationFactory.CreateWithTypes(new[] { typeof(CustomersController) }); configuration.MapODataServiceRoute( "RouteName", "RoutePrefix", model, new DefaultODataPathHandler(), ODataRoutingConventions.CreateDefault()); // Act & Assert ExceptionAssert.DoesNotThrow(() => configuration.EnsureInitialized()); }
public void GetETag_Returns_ETagInHeader_ForInteger(byte byteValue, short shortValue, long longValue) { // Arrange Dictionary <string, object> properties = new Dictionary <string, object> { { "ByteVal", byteValue }, { "LongVal", longValue }, { "ShortVal", shortValue } }; EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties); var builder = ODataConventionModelBuilderFactory.Create(); builder.EntitySet <MyEtagOrder>("Orders"); IEdmModel model = builder.GetEdmModel(); IEdmEntitySet orders = model.FindDeclaredEntitySet("Orders"); ODataPath odataPath = new ODataPath(new EntitySetSegment(orders)); HttpRequestMessage request = new HttpRequestMessage(); request.EnableHttpDependencyInjectionSupport(model); request.ODataProperties().Path = odataPath; // Act ETag result = request.GetETag(etagHeaderValue); dynamic dynamicResult = result; // Assert byte actualByte = Assert.IsType <byte>(result["ByteVal"]); Assert.Equal(actualByte, dynamicResult.ByteVal); Assert.Equal(byteValue, actualByte); short actualShort = Assert.IsType <short>(result["ShortVal"]); Assert.Equal(actualShort, dynamicResult.ShortVal); Assert.Equal(shortValue, actualShort); long actualLong = Assert.IsType <long>(result["LongVal"]); Assert.Equal(actualLong, dynamicResult.LongVal); Assert.Equal(longValue, actualLong); }
public void RequiredAttributeEdmPropertyConvention_DoesnotOverwriteExistingConfigurationForNavigationProperties() { MockType anotherType = new MockType("RelatedEntity") .Property <int>("ID"); MockType type = new MockType("Entity") .Property(typeof(int), "ID") .Property(anotherType, "RelatedEntity", new RequiredAttribute()); ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); builder.AddEntityType(type).AddNavigationProperty(type.GetProperty("RelatedEntity"), EdmMultiplicity.ZeroOrOne); IEdmModel model = builder.GetEdmModel(); IEdmEntityType entity = model.AssertHasEntityType(type); entity.AssertHasNavigationProperty(model, "RelatedEntity", anotherType, isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne); }
public void RequiredAttributeEdmPropertyConvention_ConfiguresRequiredNavigationPropertyAsRequired() { MockType anotherType = new MockType("RelatedEntity") .Property <int>("ID"); MockType type = new MockType("Entity") .Property(typeof(int), "ID") .Property(anotherType, "RelatedEntity", new RequiredAttribute()); ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); builder.AddEntityType(type); IEdmModel model = builder.GetEdmModel(); IEdmEntityType entity = model.AssertHasEntityType(type); entity.AssertHasNavigationProperty(model, "RelatedEntity", anotherType, isNullable: false, multiplicity: EdmMultiplicity.One); }
public void Apply_SetsOperationLinkBuilder_OnlyIfFunctionIsBindable() { // Arrange ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); var function = builder.Function("MyFunction").Returns <int>(); ActionLinkGenerationConvention convention = new ActionLinkGenerationConvention(); // Act convention.Apply(function, builder); // Assert IEdmModel model = builder.GetEdmModel(); var edmFunction = model.EntityContainer.Elements.OfType <IEdmFunctionImport>().Single(); Assert.NotNull(edmFunction); OperationLinkBuilder linkBuilder = model.GetAnnotationValue <OperationLinkBuilder>(edmFunction); Assert.Null(linkBuilder); }
public void Apply_SetsOperationLinkBuilder_OnlyIfActionIsBindable() { // Arrange ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); builder.EntitySet <Customer>("Customers"); var paintAction = builder.Action("Paint"); ActionLinkGenerationConvention convention = new ActionLinkGenerationConvention(); // Act convention.Apply(paintAction, builder); // Assert IEdmModel model = builder.GetEdmModel(); var paintEdmAction = model.EntityContainer.Elements.OfType <IEdmActionImport>().Single(); OperationLinkBuilder actionLinkBuilder = model.GetAnnotationValue <OperationLinkBuilder>(paintEdmAction); Assert.Null(actionLinkBuilder); }
public static bool Apply <TPropertyConfiguration, TProperty>() where TPropertyConfiguration : PropertyConfiguration where TProperty : PropertyConfiguration { Func <Attribute, bool> matchAllFilter = a => true; // build the type Mock <EntityTypeConfiguration> structuralType = new Mock <EntityTypeConfiguration>(MockBehavior.Strict); ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); structuralType.Setup(s => s.ModelBuilder).Returns(builder); // build the property Mock <PropertyInfo> property = new Mock <PropertyInfo>(); property.Setup(p => p.Name).Returns("Property"); property.Setup(p => p.PropertyType).Returns(typeof(int)); Attribute attribute = new Mock <Attribute>().Object; property.Setup(p => p.GetCustomAttributes(It.IsAny <bool>())).Returns(new[] { attribute }); Mock <TProperty> propertyConfiguration; if (typeof(TProperty) == typeof(NavigationPropertyConfiguration)) { propertyConfiguration = new Mock <TProperty>(property.Object, EdmMultiplicity.ZeroOrOne, structuralType.Object); } else { propertyConfiguration = new Mock <TProperty>(property.Object, structuralType.Object); } // build the convention SpyAttributeEdmPropertyConvention <TPropertyConfiguration> spy = new SpyAttributeEdmPropertyConvention <TPropertyConfiguration>(matchAllFilter, allowMultiple: false); // Apply (spy as IEdmPropertyConvention).Apply(propertyConfiguration.Object, structuralType.Object, builder); return(spy.Called); }
public void DefaultValueAttributeEdmPropertyConvention_ConfiguresDefaultValuePropertyAsDefaultValue() { MockType type = new MockType("Entity") .Property(typeof(int), "ID") .Property(typeof(int), "Count", new DefaultValueAttribute(0)) .Property(typeof(TestEnum), "Kind", new DefaultValueAttribute(TestEnum.Member2)); ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); builder.AddEntityType(type); IEdmModel model = builder.GetEdmModel(); IEdmEntityType entity = model.AssertHasEntityType(type); IEdmStructuralProperty property = entity.AssertHasPrimitiveProperty(model, "Count", EdmPrimitiveTypeKind.Int32, isNullable: false); Assert.Equal("0", property.DefaultValueString); IEdmStructuralProperty enumProperty = entity.AssertHasProperty <IEdmStructuralProperty>(model, "Kind", typeof(TestEnum), isNullable: false); Assert.Equal("Member2", enumProperty.DefaultValueString); }
public void LowerCamelCaser_ProcessReflectedAndExplicitPropertyNames() { // Arrange var builder = ODataConventionModelBuilderFactory.Create().EnableLowerCamelCase( NameResolverOptions.ProcessReflectedPropertyNames | NameResolverOptions.ProcessExplicitPropertyNames); builder.EntitySet <LowerCamelCaserModelAliasEntity>("Entities"); // Act IEdmModel model = builder.GetEdmModel(); // Assert IEdmEntityType lowerCamelCaserEntity = Assert.Single(model.SchemaElements.OfType <IEdmEntityType>().Where(e => e.Name == "LowerCamelCaserModelAliasEntity")); Assert.Equal(4, lowerCamelCaserEntity.Properties().Count()); Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "ID")); Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "name")); Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "Something")); Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "color")); }
public void SelectAction_ReturnsNull_IfPostToNavigationPropertyBindingToNonCollectionValuedNavigationProperty(string path) { // Arrange ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); builder.EntitySet <Company>("Companies"); builder.Singleton <Company>("MyCompany"); builder.EntitySet <Employee>("Employees"); builder.Singleton <Employee>("Tony"); IEdmModel model = builder.GetEdmModel(); ODataPath odataPath = new DefaultODataPathHandler().Parse(model, "http://any/", path); var request = RequestFactory.Create(HttpMethod.Post, "http://localhost/"); var emptyActionMap = SelectActionHelper.CreateActionMap(); // Act string selectedAction = SelectActionHelper.SelectAction(new NavigationRoutingConvention(), odataPath, request, emptyActionMap); // Assert Assert.Null(selectedAction); }
public void SelfLinksGenerationConvention_Uses_GetByIdWithCast_IfDerivedTypeHasNavigationProperty() { ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); var vehicles = builder.EntitySet <Vehicle>("vehicles"); IEdmModel model = builder.GetEdmModel(); IEdmEntitySet vehiclesEdmEntitySet = model.EntityContainer.EntitySets().Single(); IEdmEntityType carType = model.AssertHasEntityType(typeof(Car)); var request = RequestFactory.CreateFromModel(model); NavigationSourceLinkBuilderAnnotation linkBuilder = model.GetNavigationSourceLinkBuilder(vehiclesEdmEntitySet); var serializerContext = ODataSerializerContextFactory.Create(model, vehiclesEdmEntitySet, request); var entityContext = new ResourceContext(serializerContext, carType.AsReference(), new Car { Model = 2009, Name = "Contoso" }); EntitySelfLinks selfLinks = linkBuilder.BuildEntitySelfLinks(entityContext, ODataMetadataLevel.FullMetadata); Assert.Equal("http://localhost/vehicles(Model=2009,Name='Contoso')", selfLinks.IdLink.ToString()); Assert.Equal("http://localhost/vehicles(Model=2009,Name='Contoso')/Microsoft.Test.AspNet.OData.Builder.TestModels.Car", selfLinks.EditLink.ToString()); }
public void AddDynamicDictionary_ThrowsException_IfMoreThanOneDynamicPropertyInOpenComplexType() { // Arrange ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); builder.ComplexType <BadOpenComplexType>(); // Act & Assert #if NETCOREAPP3_0 ExceptionAssert.ThrowsArgument(() => builder.GetEdmModel(), "propertyInfo", "Found more than one dynamic property container in type 'BadOpenComplexType'. " + "Each open type must have at most one dynamic property container. (Parameter 'propertyInfo')"); #else ExceptionAssert.ThrowsArgument(() => builder.GetEdmModel(), "propertyInfo", "Found more than one dynamic property container in type 'BadOpenComplexType'. " + "Each open type must have at most one dynamic property container.\r\n" + "Parameter name: propertyInfo"); #endif }
public void DataMemberAttributeEdmPropertyConvention_DerivedClassPropertyAliased_IfEnabled(string propertyAlias, bool modelAliasing) { // Arrange MockType baseType = new MockType("BaseMocktype") .Property <int>("ID"); baseType.Setup(t => t.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())) .Returns(new[] { new DataContractAttribute() }); MockType relatedType = new MockType("RelatedEntity") .Property <int>("ID"); MockType derivedType = new MockType("DerivedMockType") .Property(relatedType, "RelatedEntity", new DataMemberAttribute { Name = "AliasRelatedEntity" }) .BaseType(baseType); derivedType.Setup(t => t.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())) .Returns(new[] { new DataContractAttribute() }); // Act ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(b => b.ModelAliasingEnabled = modelAliasing); builder.AddEntityType(derivedType); IEdmModel model = builder.GetEdmModel(); // Assert IEdmEntityType entity = model.AssertHasEntityType(derivedType); entity.AssertHasKey(model, "ID", EdmPrimitiveTypeKind.Int32); entity.AssertHasNavigationProperty( model, propertyAlias, relatedType, isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne); }
public EnableNestedPathsTest() { _deserializerProvider = ODataDeserializerProviderFactory.Create(); _resourceSetDeserializer = new ODataResourceSetDeserializer(_deserializerProvider); _resourceDeserializer = new ODataResourceDeserializer(_deserializerProvider); _primitiveDeserializer = new ODataPrimitiveDeserializer(); ODataModelBuilder builder = ODataConventionModelBuilderFactory.Create(); builder.EntitySet <EnableNestedPathsCustomer>("EnableNestedPathsCustomers"); builder.EntitySet <EnableNestedPathsProduct>("EnableNestedPathsProducts"); builder.Singleton <EnableNestedPathsCustomer>("EnableNestedPathsTopCustomer"); builder.EntityType <EnableNestedPathsVipCustomer>(); builder.EntityType <EnableNestedPathsVipCustomer>() .Function("GetMostPurchasedProduct") .ReturnsFromEntitySet <EnableNestedPathsProduct>("EnableNestedPathsProduct"); builder.EntityType <EnableNestedPathsProduct>() .Collection .Action("SetDiscountRate"); _model = builder.GetEdmModel(); Type[] controllers = new Type[] { typeof(EnableNestedPathsCustomersController), typeof(EnableNestedPathsProductsController), typeof(EnableNestedPathsTopCustomerController) }; _server = TestServerFactory.Create(controllers, (config) => { config.MapODataServiceRoute("odata", "odata", _model); config.Count().OrderBy().Filter().Expand().MaxTop(null).Select(); }); _client = TestServerFactory.CreateClient(_server); _db = new EnableNestedPathsDatabase(); }
public void GetETag_Returns_ETagInHeader_ForDouble(double value, bool isEqual) { // Arrange Dictionary <string, object> properties = new Dictionary <string, object> { { "Version", value } }; EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties); var builder = ODataConventionModelBuilderFactory.Create(); builder.EntitySet <MyEtagCustomer>("Customers"); IEdmModel model = builder.GetEdmModel(); IEdmEntitySet customers = model.FindDeclaredEntitySet("Customers"); ODataPath odataPath = new ODataPath(new EntitySetSegment(customers)); HttpRequestMessage request = new HttpRequestMessage(); request.EnableHttpDependencyInjectionSupport(model); request.ODataProperties().Path = odataPath; // Act ETag result = request.GetETag(etagHeaderValue); dynamic dynamicResult = result; // Assert double actual = Assert.IsType <double>(result["Version"]); Assert.Equal(actual, dynamicResult.Version); if (isEqual) { Assert.Equal(value, actual); } else { Assert.NotEqual(value, actual); Assert.True(actual - value < 0.0000001); } }
public void Apply_IgnoresKey_NonEntityTypeConfiguration() { // Arrange ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); Mock <PropertyInfo> property = new Mock <PropertyInfo>(); property.Setup(p => p.Name).Returns("Property"); property.Setup(p => p.PropertyType).Returns(typeof(int)); property.Setup(p => p.GetCustomAttributes(It.IsAny <bool>())).Returns(new[] { new KeyAttribute() }); Mock <ComplexTypeConfiguration> complexType = new Mock <ComplexTypeConfiguration>(MockBehavior.Strict); Mock <PrimitivePropertyConfiguration> primitiveProperty = new Mock <PrimitivePropertyConfiguration>(property.Object, complexType.Object); // Act new KeyAttributeEdmPropertyConvention().Apply(primitiveProperty.Object, complexType.Object, builder); // Assert complexType.Verify(); }
private static System.Web.Http.HttpServer CreateServer(string customersEntitySet) #endif { // We need to do this to avoid controllers with incorrect attribute // routing configuration in this assembly that cause an exception to // be thrown at runtime. With this, we restrict the test to the following // set of controllers. Type[] controllers = new Type[] { typeof(OnlyFilterAllowedCustomersController), typeof(OnlyFilterAndEqualsAllowedCustomersController), typeof(FilterDisabledCustomersController), typeof(EverythingAllowedCustomersController), typeof(OtherLimitationsCustomersController), }; ODataModelBuilder builder = ODataConventionModelBuilderFactory.Create(); builder.EntitySet <EnableQueryCustomer>(customersEntitySet); builder.EntityType <PremiumEnableQueryCustomer>(); builder.EntitySet <EnableQueryCategory>("EnableQueryCategories"); builder.EntityType <PremiumEnableQueryCategory>(); builder.EntitySet <EnableQueryOrder>("EnableQueryOrders"); builder.EntityType <DiscountedEnableQueryOrder>(); builder.EntitySet <EnableQueryOrderLine>("EnableQueryOrderLines"); builder.ComplexType <EnableQueryAddress>(); IEdmModel model = builder.GetEdmModel(); return(TestServerFactory.Create(controllers, (config) => { config.MapODataServiceRoute("odata", "odata", model); config.Count().OrderBy().Filter().Expand().MaxTop(null).Select().SkipToken(); })); }
private static IEdmModel GetEdmModel() { var builder = ODataConventionModelBuilderFactory.Create(); builder.EntitySet <Account>("Accounts"); builder.EntitySet <PaymentInstrument>("Payments"); builder.EntityType <Account>().Collection.Action("Clear").Parameter <int>("p1"); builder.EntityType <Account>() .Collection.Function("MyCollectionFunction") .Returns <string>() .Parameter <int>("land"); builder.EntityType <PreminumAccount>().Collection.Function("MyCollectionFunction") .Returns <string>() .Parameter <int>("land"); builder.EntityType <Account>().Action("ClearSingle").Parameter <string>("pa"); builder.EntityType <Account>().Function("MyFunction").Returns <string>().Parameter <string>("p1"); return(builder.GetEdmModel()); }
public void Apply_SetOperationLinkBuilder_ForActionBoundToEntity() { // Arrange ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); var action = builder.EntityType <Customer>().Action("MyAction"); // Act Assert.Null(action.GetActionLink()); // Guard Assert.Null(action.GetFeedActionLink()); // Guard ActionLinkGenerationConvention convention = new ActionLinkGenerationConvention(); convention.Apply(action, builder); // Assert var actionLink = action.GetActionLink(); Assert.NotNull(actionLink); Assert.IsType <Func <ResourceContext, Uri> >(actionLink); Assert.Null(action.GetFeedActionLink()); }
public void Apply_Doesnot_Override_UserConfiguration() { // Arrange ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); var customers = builder.EntitySet <Customer>("Customers"); var paintAction = customers.EntityType.Action("Paint"); paintAction.HasActionLink(ctxt => new Uri("http://localhost/ActionTestWorks"), followsConventions: false); ActionLinkGenerationConvention convention = new ActionLinkGenerationConvention(); // Act convention.Apply(paintAction, builder); IEdmModel model = builder.GetEdmModel(); var edmCustomers = model.EntityContainer.FindEntitySet("Customers"); var edmCustomer = model.SchemaElements.OfType <IEdmEntityType>().First(c => c.Name == "Customer"); var edmAction = model.SchemaElements.OfType <IEdmAction>().First(a => a.Name == "Paint"); Assert.NotNull(edmAction); string routeName = "OData"; var configuration = RoutingConfigurationFactory.CreateWithRootContainer(routeName); configuration.MapODataServiceRoute(routeName, null, model); var request = RequestFactory.Create(HttpMethod.Get, "http://localhost", configuration, routeName); OperationLinkBuilder actionLinkBuilder = model.GetOperationLinkBuilder(edmAction); var serializerContext = ODataSerializerContextFactory.Create(model, edmCustomers, request); var entityContext = new ResourceContext(serializerContext, edmCustomer.AsReference(), new Customer { Id = 2009 }); // Assert Uri link = actionLinkBuilder.BuildLink(entityContext); Assert.Equal("http://localhost/ActionTestWorks", link.AbsoluteUri); }
public void NavigationLinksGenerationConvention_GeneratesLinksWithoutCast_ForBaseProperties() { ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); builder.EntitySet <SportBike>("vehicles"); builder.EntitySet <Manufacturer>("manufacturers"); IEdmModel model = builder.GetEdmModel(); IEdmEntitySet vehiclesEdmEntitySet = model.EntityContainer.FindEntitySet("vehicles"); IEdmEntityType sportbikeType = model.AssertHasEntityType(typeof(SportBike)); IEdmNavigationProperty motorcycleManufacturerProperty = sportbikeType.AssertHasNavigationProperty(model, "Manufacturer", typeof(MotorcycleManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne); var configuration = RoutingConfigurationFactory.Create(); string routeName = "Route"; configuration.MapODataServiceRoute(routeName, null, model); var request = RequestFactory.Create(HttpMethod.Get, "http://localhost", configuration, routeName); NavigationSourceLinkBuilderAnnotation linkBuilder = model.GetNavigationSourceLinkBuilder(vehiclesEdmEntitySet); linkBuilder.AddNavigationPropertyLinkBuilder(motorcycleManufacturerProperty, new NavigationLinkBuilder((context, property) => context.GenerateNavigationPropertyLink(property, includeCast: false), false)); var serializerContext = ODataSerializerContextFactory.Create(model, vehiclesEdmEntitySet, request); var entityContext = new ResourceContext(serializerContext, sportbikeType.AsReference(), new SportBike { Model = 2009, Name = "Ninja" }); // We might get one of these: // http://localhost/vehicles(Model=2009,Name='Ninja')/Manufacturer // http://localhost/vehicles(Name='Ninja',Model=2009)/Manufacturer Uri uri = linkBuilder.BuildNavigationLink(entityContext, motorcycleManufacturerProperty, ODataMetadataLevel.MinimalMetadata); string aboluteUri = uri.AbsoluteUri; Assert.Contains("http://localhost/vehicles(", aboluteUri); Assert.Contains("Model=2009", aboluteUri); Assert.Contains("Name='Ninja'", aboluteUri); Assert.Contains(")/Manufacturer", aboluteUri); }
public void ODataMetadataSerializer_Works_ForSingleton() { // Arrange ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); builder.Singleton <Customer>("Me"); builder.EntitySet <Order>("MyOrders"); IEdmModel model = builder.GetEdmModel(); ODataMetadataSerializer serializer = new ODataMetadataSerializer(); MemoryStream stream = new MemoryStream(); IODataResponseMessage message = new ODataMessageWrapper(stream); ODataMessageWriterSettings settings = new ODataMessageWriterSettings(); // Act serializer.WriteObject(model, typeof(IEdmModel), new ODataMessageWriter(message, settings, model), new ODataSerializerContext()); // Assert stream.Seek(0, SeekOrigin.Begin); string result = new StreamReader(stream).ReadToEnd(); Assert.Contains("<Singleton Name=\"Me\" Type=\"Microsoft.Test.AspNet.OData.Formatter.Serialization.Models.Customer\">", result); }
public void SelfLinksGenerationConvention_Uses_WithoutCast_IfDerivedTypeDoesnotHaveNavigationProperty_ForSingleton() { // Arrange ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); var myMotorcycle = builder.Singleton <Motorcycle>("MyMotor"); IEdmModel model = builder.GetEdmModel(); IEdmSingleton vehicleEdmSingleton = model.EntityContainer.FindSingleton("MyMotor"); IEdmEntityType sportbikeType = model.AssertHasEntityType(typeof(SportBike)); var request = RequestFactory.CreateFromModel(model); NavigationSourceLinkBuilderAnnotation linkBuilder = model.GetNavigationSourceLinkBuilder(vehicleEdmSingleton); var serializerContext = ODataSerializerContextFactory.Create(model, vehicleEdmSingleton, request); var entityContext = new ResourceContext(serializerContext, sportbikeType.AsReference(), new SportBike { Model = 2014, Name = "Ninja" }); // Act EntitySelfLinks selfLinks = linkBuilder.BuildEntitySelfLinks(entityContext, ODataMetadataLevel.FullMetadata); // Assert Assert.Equal("http://localhost/MyMotor", selfLinks.IdLink.ToString()); }
public void LowerCamelCaser_ProcessReflectedPropertyNames() { // Arrange var builder = ODataConventionModelBuilderFactory.Create().EnableLowerCamelCase(NameResolverOptions.ProcessReflectedPropertyNames); EntityTypeConfiguration <LowerCamelCaserModelAliasEntity> entity = builder.EntitySet <LowerCamelCaserModelAliasEntity>("Entities").EntityType; entity.HasKey(e => e.ID).Property(e => e.ID).Name = "IDExplicitly"; entity.Property(d => d.Price).Name = "Price"; // Act IEdmModel model = builder.GetEdmModel(); // Assert IEdmEntityType lowerCamelCaserModelAliasEntity = Assert.Single(model.SchemaElements.OfType <IEdmEntityType>().Where(e => e.Name == "LowerCamelCaserModelAliasEntity")); Assert.Equal(5, lowerCamelCaserModelAliasEntity.Properties().Count()); Assert.Single(lowerCamelCaserModelAliasEntity.Properties().Where(p => p.Name == "IDExplicitly")); Assert.Single(lowerCamelCaserModelAliasEntity.Properties().Where(p => p.Name == "name")); Assert.Single(lowerCamelCaserModelAliasEntity.Properties().Where(p => p.Name == "Something")); Assert.Single(lowerCamelCaserModelAliasEntity.Properties().Where(p => p.Name == "color")); Assert.Single(lowerCamelCaserModelAliasEntity.Properties().Where(p => p.Name == "Price")); }
public void WhenFunctionLinksNotManuallyConfigured_ConventionBasedBuilderUsesConventions() { // Arrange string uriTemplate = "http://server/Movies({0})/Default.Watch(param=@param)"; Uri expectedUri = new Uri(string.Format(uriTemplate, 1)); ODataModelBuilder builder = ODataConventionModelBuilderFactory.Create(); EntityTypeConfiguration <Movie> movie = builder.EntitySet <Movie>("Movies").EntityType; FunctionConfiguration watch = movie.Function("Watch").Returns <int>(); watch.Parameter <string>("param"); IEdmModel model = builder.GetEdmModel(); var configuration = RoutingConfigurationFactory.Create(); string routeName = "Route"; configuration.MapODataServiceRoute(routeName, null, model); var request = RequestFactory.Create(HttpMethod.Get, "http://server/Movies", configuration, routeName); // Act IEdmEntityType movieType = model.SchemaElements.OfType <IEdmEntityType>().SingleOrDefault(); IEdmEntityContainer container = model.SchemaElements.OfType <IEdmEntityContainer>().SingleOrDefault(); IEdmFunction watchFunction = Assert.Single(model.SchemaElements.OfType <IEdmFunction>()); // Guard IEdmEntitySet entitySet = container.EntitySets().SingleOrDefault(); ODataSerializerContext serializerContext = ODataSerializerContextFactory.Create(model, entitySet, request); ResourceContext context = new ResourceContext(serializerContext, movieType.AsReference(), new Movie { ID = 1, Name = "Avatar" }); OperationLinkBuilder functionLinkBuilder = model.GetAnnotationValue <OperationLinkBuilder>(watchFunction); //Assert Assert.Equal(expectedUri, watch.GetFunctionLink()(context)); Assert.NotNull(functionLinkBuilder); Assert.Equal(expectedUri, functionLinkBuilder.BuildLink(context)); }
public void Apply_WorksFor_ActionBoundToCollectionOfEntity() { // Arrange ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(); var action = builder.EntityType <Customer>().Collection.Action("MyFunction").Returns <int>(); action.Parameter <string>("param"); // Act Assert.Null(action.GetActionLink()); // Guard Assert.Null(action.GetFeedActionLink()); // Guard ActionLinkGenerationConvention convention = new ActionLinkGenerationConvention(); convention.Apply(action, builder); // Assert var actionLink = action.GetFeedActionLink(); Assert.NotNull(actionLink); Assert.IsType <Func <ResourceSetContext, Uri> >(actionLink); Assert.Null(action.GetActionLink()); }