public Task<IEdmModel> GetModelAsync(ModelContext context, CancellationToken cancellationToken) { var model = new EdmModel(); var dummyType = new EdmEntityType("NS", "Dummy"); model.AddElement(dummyType); var container = new EdmEntityContainer("NS", "DefaultContainer"); container.AddEntitySet("Test", dummyType); model.AddElement(container); return Task.FromResult((IEdmModel) model); }
protected override void VisitDeclaredKeyProperties( EdmEntityType entityType, IEnumerable<EdmProperty> properties) { if (properties.Count() > 0) { _schemaWriter.WriteDelaredKeyPropertiesElementHeader(); foreach (var keyProperty in properties) { _schemaWriter.WriteDelaredKeyPropertyRefElement(keyProperty); } _schemaWriter.WriteEndElement(); } }
internal void WriteEntityTypeElementHeader(EdmEntityType entityType) { _xmlWriter.WriteStartElement(CsdlConstants.Element_EntityType); _xmlWriter.WriteAttributeString(CsdlConstants.Attribute_Name, entityType.Name); if (entityType.Annotations.GetClrAttributes() != null) { foreach (var a in entityType.Annotations.GetClrAttributes()) { if (a.GetType().FullName.Equals(DataServicesHasStreamAttribute, StringComparison.Ordinal)) { _xmlWriter.WriteAttributeString(DataServicesPrefix, "HasStream", DataServicesNamespace, "true"); } else if (a.GetType().FullName.Equals(DataServicesMimeTypeAttribute, StringComparison.Ordinal)) { // Move down to the appropriate property var propertyName = a.GetType().GetProperty("MemberName").GetValue(a, null) as string; var property = entityType.Properties.SingleOrDefault( p => p.Name.Equals(propertyName, StringComparison.Ordinal)); AddAttributeAnnotation(property, a); } else if (a.GetType().FullName.Equals( DataServicesEntityPropertyMappingAttribute, StringComparison.Ordinal)) { // Move down to the appropriate property var sourcePath = a.GetType().GetProperty("SourcePath").GetValue(a, null) as string; var slashIndex = sourcePath.IndexOf("/", StringComparison.Ordinal); string propertyName; if (slashIndex == -1) { propertyName = sourcePath; } else { propertyName = sourcePath.Substring(0, slashIndex); } var property = entityType.Properties.SingleOrDefault( p => p.Name.Equals(propertyName, StringComparison.Ordinal)); AddAttributeAnnotation(property, a); } } } WritePolymorphicTypeAttributes(entityType); }
protected override void VisitEdmEntityType(EdmEntityType item) { _schemaWriter.WriteEntityTypeElementHeader(item); base.VisitEdmEntityType(item); _schemaWriter.WriteEndElement(); }
private string GetWriterOutputForContentTypeAndKnobValue(ODataEntry entry, EdmModel model, IEdmEntitySetBase entitySet, EdmEntityType entityType) { MemoryStream outputStream = new MemoryStream(); IODataResponseMessage message = new InMemoryMessage() { Stream = outputStream }; message.SetHeader("Content-Type", "application/json;odata.metadata=full"); ODataMessageWriterSettings settings = new ODataMessageWriterSettings() { AutoComputePayloadMetadataInJson = true, }; settings.SetServiceDocumentUri(new Uri("http://example.com")); string output; using (var messageWriter = new ODataMessageWriter(message, settings, model)) { ODataWriter writer = messageWriter.CreateODataEntryWriter(entitySet, entityType); writer.WriteStart(entry); writer.WriteEnd(); outputStream.Seek(0, SeekOrigin.Begin); output = new StreamReader(outputStream).ReadToEnd(); } return(output); }
private IEdmModel GetModel() { if (myModel == null) { myModel = new EdmModel(); EdmComplexType shippingAddress = new EdmComplexType("MyNS", "ShippingAddress"); shippingAddress.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String); shippingAddress.AddStructuralProperty("City", EdmPrimitiveTypeKind.String); shippingAddress.AddStructuralProperty("Region", EdmPrimitiveTypeKind.String); shippingAddress.AddStructuralProperty("PostalCode", EdmPrimitiveTypeKind.String); myModel.AddElement(shippingAddress); EdmComplexTypeReference shippingAddressReference = new EdmComplexTypeReference(shippingAddress, true); EdmEntityType orderType = new EdmEntityType("MyNS", "Order"); orderType.AddKeys(orderType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32)); orderType.AddStructuralProperty("ShippingAddress", shippingAddressReference); myModel.AddElement(orderType); EdmEntityType customer = new EdmEntityType("MyNS", "Customer"); customer.AddStructuralProperty("ContactName", EdmPrimitiveTypeKind.String); var customerId = customer.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32); customer.AddKeys(customerId); customer.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "Orders", Target = orderType, TargetMultiplicity = EdmMultiplicity.Many, }); myModel.AddElement(customer); var productType = new EdmEntityType("MyNS", "Product"); var productId = productType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32); productType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String); productType.AddKeys(productId); myModel.AddElement(productType); var physicalProductType = new EdmEntityType("MyNS", "PhysicalProduct", productType); physicalProductType.AddStructuralProperty("Material", EdmPrimitiveTypeKind.String); myModel.AddElement(physicalProductType); var productDetailType = new EdmEntityType("MyNS", "ProductDetail"); var productDetailId = productDetailType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32); productDetailType.AddStructuralProperty("Detail", EdmPrimitiveTypeKind.String); productDetailType.AddKeys(productDetailId); myModel.AddElement(productDetailType); var productDetailItemType = new EdmEntityType("MyNS", "ProductDetailItem"); var productDetailItemId = productDetailItemType.AddStructuralProperty("ItemId", EdmPrimitiveTypeKind.Int32); productDetailItemType.AddStructuralProperty("Description", EdmPrimitiveTypeKind.String); productDetailItemType.AddKeys(productDetailItemId); myModel.AddElement(productDetailItemType); productType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "Details", Target = productDetailType, TargetMultiplicity = EdmMultiplicity.Many, ContainsTarget = true, }); productDetailType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "Items", Target = productDetailItemType, TargetMultiplicity = EdmMultiplicity.Many, ContainsTarget = true, }); var favouriteProducts = customer.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "FavouriteProducts", Target = productType, TargetMultiplicity = EdmMultiplicity.Many, }); var productBeingViewed = customer.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "ProductBeingViewed", Target = productType, TargetMultiplicity = EdmMultiplicity.ZeroOrOne, }); EdmEntityContainer container = new EdmEntityContainer("MyNS", "Example30"); var products = container.AddEntitySet("Products", productType); var customers = container.AddEntitySet("Customers", customer); customers.AddNavigationTarget(favouriteProducts, products); customers.AddNavigationTarget(productBeingViewed, products); container.AddEntitySet("Orders", orderType); myModel.AddElement(container); } return(myModel); }
private void CreateEdmTypeHeader(IEdmTypeConfiguration config) { IEdmType edmType = GetEdmType(config.ClrType); if (edmType == null) { if (config.Kind == EdmTypeKind.Complex) { ComplexTypeConfiguration complex = (ComplexTypeConfiguration)config; IEdmComplexType baseType = null; if (complex.BaseType != null) { CreateEdmTypeHeader(complex.BaseType); baseType = GetEdmType(complex.BaseType.ClrType) as IEdmComplexType; Contract.Assert(baseType != null); } EdmComplexType complexType = new EdmComplexType(config.Namespace, config.Name, baseType, complex.IsAbstract ?? false, complex.IsOpen); _types.Add(config.ClrType, complexType); if (complex.IsOpen) { // add a mapping between the open complex type and its dynamic property dictionary. _openTypes.Add(complexType, complex.DynamicPropertyDictionary); } if (complex.SupportsInstanceAnnotations) { // add a mapping between the complex type and its instance annotation dictionary. _instanceAnnotableTypes.Add(complexType, complex.InstanceAnnotationsContainer); } edmType = complexType; } else if (config.Kind == EdmTypeKind.Entity) { EntityTypeConfiguration entity = config as EntityTypeConfiguration; Contract.Assert(entity != null); IEdmEntityType baseType = null; if (entity.BaseType != null) { CreateEdmTypeHeader(entity.BaseType); baseType = GetEdmType(entity.BaseType.ClrType) as IEdmEntityType; Contract.Assert(baseType != null); } EdmEntityType entityType = new EdmEntityType(config.Namespace, config.Name, baseType, entity.IsAbstract ?? false, entity.IsOpen, entity.HasStream); _types.Add(config.ClrType, entityType); if (entity.IsOpen) { // add a mapping between the open entity type and its dynamic property dictionary. _openTypes.Add(entityType, entity.DynamicPropertyDictionary); } if (entity.SupportsInstanceAnnotations) { // add a mapping between the entity type and its instance annotation dictionary. _instanceAnnotableTypes.Add(entityType, entity.InstanceAnnotationsContainer); } edmType = entityType; } else { EnumTypeConfiguration enumTypeConfiguration = config as EnumTypeConfiguration; // The config has to be enum. Contract.Assert(enumTypeConfiguration != null); _types.Add(enumTypeConfiguration.ClrType, new EdmEnumType(enumTypeConfiguration.Namespace, enumTypeConfiguration.Name, GetTypeKind(enumTypeConfiguration.UnderlyingType), enumTypeConfiguration.IsFlags)); } } IEdmStructuredType structuredType = edmType as IEdmStructuredType; StructuralTypeConfiguration structuralTypeConfiguration = config as StructuralTypeConfiguration; if (structuredType != null && structuralTypeConfiguration != null && !_structuredTypeQuerySettings.ContainsKey(structuredType)) { ModelBoundQuerySettings querySettings = structuralTypeConfiguration.QueryConfiguration.ModelBoundQuerySettings; if (querySettings != null) { _structuredTypeQuerySettings.Add(structuredType, structuralTypeConfiguration.QueryConfiguration.ModelBoundQuerySettings); } } }
/// <summary> /// Creates a test model shared among parameter reader/writer tests. /// </summary> /// <returns>Returns a model with function imports.</returns> public static IEdmModel BuildModelWithFunctionImport() { EdmCoreModel coreModel = EdmCoreModel.Instance; EdmModel model = new EdmModel(); const string defaultNamespaceName = "TestModel"; EdmEntityContainer container = new EdmEntityContainer(defaultNamespaceName, "TestContainer"); model.AddElement(container); EdmComplexType complexType = new EdmComplexType(defaultNamespaceName, "ComplexType"); complexType.AddProperty(new EdmStructuralProperty(complexType, "PrimitiveProperty", coreModel.GetString(false))); complexType.AddProperty(new EdmStructuralProperty(complexType, "ComplexProperty", complexType.ToTypeReference(false))); model.AddElement(complexType); EdmEnumType enumType = new EdmEnumType(defaultNamespaceName, "EnumType"); model.AddElement(enumType); EdmEntityType entityType = new EdmEntityType(defaultNamespaceName, "EntityType"); entityType.AddKeys(new IEdmStructuralProperty[] { new EdmStructuralProperty(entityType, "ID", coreModel.GetInt32(false)) }); entityType.AddProperty(new EdmStructuralProperty(entityType, "ComplexProperty", complexType.ToTypeReference())); container.AddActionAndActionImport(model, "FunctionImport_Primitive", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("primitive", coreModel.GetString(false)); container.AddActionAndActionImport(model, "FunctionImport_NullablePrimitive", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("nullablePrimitive", coreModel.GetString(true)); EdmCollectionType stringCollectionType = new EdmCollectionType(coreModel.GetString(true)); container.AddActionAndActionImport(model, "FunctionImport_PrimitiveCollection", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("primitiveCollection", stringCollectionType.ToTypeReference(false)); container.AddActionAndActionImport(model, "FunctionImport_Complex", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("complex", complexType.ToTypeReference(true)); EdmCollectionType complexCollectionType = new EdmCollectionType(complexType.ToTypeReference()); container.AddActionAndActionImport(model, "FunctionImport_ComplexCollection", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("complexCollection", complexCollectionType.ToTypeReference()); container.AddActionAndActionImport(model, "FunctionImport_Entry", null /*returnType*/, null /*entitySet*/, true /*bindable*/).Action.AsEdmAction().AddParameter("entry", entityType.ToTypeReference()); EdmCollectionType entityCollectionType = new EdmCollectionType(entityType.ToTypeReference()); container.AddActionAndActionImport(model, "FunctionImport_Feed", null /*returnType*/, null /*entitySet*/, true /*bindable*/).Action.AsEdmAction().AddParameter("feed", entityCollectionType.ToTypeReference()); container.AddActionAndActionImport(model, "FunctionImport_Stream", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("stream", coreModel.GetStream(false)); container.AddActionAndActionImport(model, "FunctionImport_Enum", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("enum", enumType.ToTypeReference()); var functionImport_PrimitiveTwoParameters = container.AddActionAndActionImport(model, "FunctionImport_PrimitiveTwoParameters", null /*returnType*/, null /*entitySet*/, false /*bindable*/); functionImport_PrimitiveTwoParameters.Action.AsEdmAction().AddParameter("p1", coreModel.GetInt32(false)); functionImport_PrimitiveTwoParameters.Action.AsEdmAction().AddParameter("p2", coreModel.GetString(false)); container.AddActionAndActionImport(model, "FunctionImport_Int", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("p1", coreModel.GetInt32(false)); container.AddActionAndActionImport(model, "FunctionImport_Double", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("p1", coreModel.GetDouble(false)); EdmCollectionType int32CollectionType = new EdmCollectionType(coreModel.GetInt32(false)); container.AddActionAndActionImport(model, "FunctionImport_NonNullablePrimitiveCollection", null /*returnType*/, null /*entitySet*/, false /*bindable*/).Action.AsEdmAction().AddParameter("p1", int32CollectionType.ToTypeReference(false)); EdmComplexType complexType2 = new EdmComplexType(defaultNamespaceName, "ComplexTypeWithNullableProperties"); complexType2.AddProperty(new EdmStructuralProperty(complexType2, "StringProperty", coreModel.GetString(true))); complexType2.AddProperty(new EdmStructuralProperty(complexType2, "IntegerProperty", coreModel.GetInt32(true))); model.AddElement(complexType2); var functionImport_MultipleNullableParameters = container.AddActionAndActionImport(model, "FunctionImport_MultipleNullableParameters", null /*returnType*/, null /*entitySet*/, false /*bindable*/); var function_MultipleNullableParameters = functionImport_MultipleNullableParameters.Action.AsEdmAction(); function_MultipleNullableParameters.AddParameter("p1", coreModel.GetBinary(true /*isNullable*/)); function_MultipleNullableParameters.AddParameter("p2", coreModel.GetBoolean(true /*isNullable*/)); function_MultipleNullableParameters.AddParameter("p3", coreModel.GetByte(true /*isNullable*/)); function_MultipleNullableParameters.AddParameter("p5", coreModel.GetDateTimeOffset(true /*isNullable*/)); function_MultipleNullableParameters.AddParameter("p6", coreModel.GetDecimal(true /*isNullable*/)); function_MultipleNullableParameters.AddParameter("p7", coreModel.GetDouble(true /*isNullable*/)); function_MultipleNullableParameters.AddParameter("p8", coreModel.GetGuid(true /*isNullable*/)); function_MultipleNullableParameters.AddParameter("p9", coreModel.GetInt16(true /*isNullable*/)); function_MultipleNullableParameters.AddParameter("p10", coreModel.GetInt32(true /*isNullable*/)); function_MultipleNullableParameters.AddParameter("p11", coreModel.GetInt64(true /*isNullable*/)); function_MultipleNullableParameters.AddParameter("p12", coreModel.GetSByte(true /*isNullable*/)); function_MultipleNullableParameters.AddParameter("p13", coreModel.GetSingle(true /*isNullable*/)); function_MultipleNullableParameters.AddParameter("p14", coreModel.GetSpatial(EdmPrimitiveTypeKind.GeographyPoint, true /*isNullable*/)); function_MultipleNullableParameters.AddParameter("p15", coreModel.GetString(true /*isNullable*/)); function_MultipleNullableParameters.AddParameter("p16", complexType2.ToTypeReference(true /*isNullable*/)); return(model); }
public void ReadingTypeDefinitionPayloadWithMultipleTypeDefinitionJsonLight() { EdmModel model = new EdmModel(); EdmEntityType entityType = new EdmEntityType("NS", "Person"); entityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32); EdmTypeDefinition weightType = new EdmTypeDefinition("NS", "Weight", EdmPrimitiveTypeKind.Double); EdmTypeDefinitionReference weightTypeRef = new EdmTypeDefinitionReference(weightType, false); entityType.AddStructuralProperty("Weight", weightTypeRef); EdmTypeDefinition heightType = new EdmTypeDefinition("NS", "Height", EdmPrimitiveTypeKind.Double); EdmComplexType complexType = new EdmComplexType("NS", "OpenAddress"); EdmComplexTypeReference complexTypeRef = new EdmComplexTypeReference(complexType, true); EdmTypeDefinition addressType = new EdmTypeDefinition("NS", "Address", EdmPrimitiveTypeKind.String); EdmTypeDefinitionReference addressTypeRef = new EdmTypeDefinitionReference(addressType, false); complexType.AddStructuralProperty("CountryRegion", addressTypeRef); EdmTypeDefinition cityType = new EdmTypeDefinition("NS", "City", EdmPrimitiveTypeKind.String); entityType.AddStructuralProperty("Address", complexTypeRef); model.AddElement(weightType); model.AddElement(heightType); model.AddElement(addressType); model.AddElement(cityType); model.AddElement(complexType); model.AddElement(entityType); EdmEntityContainer container = new EdmEntityContainer("EntityNs", "MyContainer"); EdmEntitySet entitySet = container.AddEntitySet("People", entityType); model.AddElement(container); const string payload = "{" + "\"@odata.context\":\"http://www.example.com/$metadata#EntityNs.MyContainer.People/$entity\"," + "\"@odata.id\":\"http://mytest\"," + "\"Id\":0," + "\"[email protected]\":\"#NS.Height\"," + "\"Weight\":60.5," + "\"Address\":{\"[email protected]\":\"#NS.City\",\"CountryRegion\":\"China\"}" + "}"; ODataEntry entry = null; this.ReadEntryPayload(model, payload, entitySet, entityType, reader => { entry = entry ?? reader.Item as ODataEntry; }); Assert.NotNull(entry); IList <ODataProperty> propertyList = entry.Properties.ToList(); propertyList[1].Name.Should().Be("Weight"); propertyList[1].Value.Should().Be(60.5); var address = propertyList[2].Value as ODataComplexValue; address.Properties.FirstOrDefault(s => string.Equals(s.Name, "CountryRegion", StringComparison.OrdinalIgnoreCase)).Value.Should().Be("China"); }
public void UnsignedIntAndTypeDefinitionRoundtripJsonLightIntegrationTest() { var model = new EdmModel(); var uint16 = new EdmTypeDefinition("MyNS", "UInt16", EdmPrimitiveTypeKind.Double); var uint16Ref = new EdmTypeDefinitionReference(uint16, false); model.AddElement(uint16); model.SetPrimitiveValueConverter(uint16Ref, UInt16ValueConverter.Instance); var uint64 = new EdmTypeDefinition("MyNS", "UInt64", EdmPrimitiveTypeKind.String); var uint64Ref = new EdmTypeDefinitionReference(uint64, false); model.AddElement(uint64); model.SetPrimitiveValueConverter(uint64Ref, UInt64ValueConverter.Instance); var guidType = new EdmTypeDefinition("MyNS", "Guid", EdmPrimitiveTypeKind.Int64); var guidRef = new EdmTypeDefinitionReference(guidType, true); model.AddElement(guidType); var personType = new EdmEntityType("MyNS", "Person"); personType.AddKeys(personType.AddStructuralProperty("ID", uint64Ref)); personType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String); personType.AddStructuralProperty("FavoriteNumber", uint16Ref); personType.AddStructuralProperty("Age", model.GetUInt32("MyNS", true)); personType.AddStructuralProperty("Guid", guidRef); personType.AddStructuralProperty("Weight", EdmPrimitiveTypeKind.Double); personType.AddStructuralProperty("Money", EdmPrimitiveTypeKind.Decimal); model.AddElement(personType); var container = new EdmEntityContainer("MyNS", "Container"); var peopleSet = container.AddEntitySet("People", personType); model.AddElement(container); var stream = new MemoryStream(); IODataResponseMessage message = new InMemoryMessage { Stream = stream }; message.StatusCode = 200; var writerSettings = new ODataMessageWriterSettings(); writerSettings.SetServiceDocumentUri(new Uri("http://host/service")); var messageWriter = new ODataMessageWriter(message, writerSettings, model); var entryWriter = messageWriter.CreateODataEntryWriter(peopleSet); var entry = new ODataEntry { TypeName = "MyNS.Person", Properties = new[] { new ODataProperty { Name = "ID", Value = UInt64.MaxValue }, new ODataProperty { Name = "Name", Value = "Foo" }, new ODataProperty { Name = "FavoriteNumber", Value = (UInt16)250 }, new ODataProperty { Name = "Age", Value = (UInt32)123 }, new ODataProperty { Name = "Guid", Value = Int64.MinValue }, new ODataProperty { Name = "Weight", Value = 123.45 }, new ODataProperty { Name = "Money", Value = Decimal.MaxValue } } }; entryWriter.WriteStart(entry); entryWriter.WriteEnd(); entryWriter.Flush(); stream.Position = 0; StreamReader reader = new StreamReader(stream); string payload = reader.ReadToEnd(); payload.Should().Be("{\"@odata.context\":\"http://host/service/$metadata#People/$entity\",\"ID\":\"18446744073709551615\",\"Name\":\"Foo\",\"FavoriteNumber\":250.0,\"Age\":123,\"Guid\":-9223372036854775808,\"Weight\":123.45,\"Money\":79228162514264337593543950335}"); stream = new MemoryStream(Encoding.Default.GetBytes(payload)); message = new InMemoryMessage { Stream = stream }; message.StatusCode = 200; var readerSettings = new ODataMessageReaderSettings(); var messageReader = new ODataMessageReader(message, readerSettings, model); var entryReader = messageReader.CreateODataEntryReader(peopleSet, personType); Assert.True(entryReader.Read()); var entryReaded = entryReader.Item as ODataEntry; var propertiesReaded = entryReaded.Properties.ToList(); var propertiesGiven = entry.Properties.ToList(); Assert.Equal(propertiesReaded.Count, propertiesGiven.Count); for (int i = 0; i < propertiesReaded.Count; ++i) { Assert.Equal(propertiesReaded[i].Name, propertiesGiven[i].Name); Assert.Equal(propertiesReaded[i].Value.GetType(), propertiesGiven[i].Value.GetType()); Assert.Equal(propertiesReaded[i].Value, propertiesGiven[i].Value); } }
public static IEdmModel SimpleCustomerOrderModel() { var model = new EdmModel(); var customerType = new EdmEntityType("Default", "Customer"); customerType.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32); customerType.AddStructuralProperty("FirstName", EdmPrimitiveTypeKind.String); customerType.AddStructuralProperty("LastName", EdmPrimitiveTypeKind.String); IEdmTypeReference primitiveTypeReference = EdmCoreModel.Instance.GetPrimitive( EdmPrimitiveTypeKind.String, isNullable: true); IEdmStructuralProperty city = customerType.AddStructuralProperty( "City", primitiveTypeReference, defaultValue: null); model.AddElement(customerType); var specialCustomerType = new EdmEntityType("Default", "SpecialCustomer", customerType); model.AddElement(specialCustomerType); var orderType = new EdmEntityType("Default", "Order"); orderType.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32); orderType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String); orderType.AddStructuralProperty("Shipment", EdmPrimitiveTypeKind.String); model.AddElement(orderType); var specialOrderType = new EdmEntityType("Default", "SpecialOrder", orderType); model.AddElement(specialOrderType); var addressType = new EdmComplexType("Default", "Address"); addressType.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String); addressType.AddStructuralProperty("City", EdmPrimitiveTypeKind.String); addressType.AddStructuralProperty("State", EdmPrimitiveTypeKind.String); addressType.AddStructuralProperty("CountryOrRegion", EdmPrimitiveTypeKind.String); addressType.AddStructuralProperty("ZipCode", EdmPrimitiveTypeKind.String); model.AddElement(addressType); // add a derived complex type "UsAddress" var usAddressType = new EdmComplexType("Default", "UsAddress", addressType); usAddressType.AddStructuralProperty("UsProp", EdmPrimitiveTypeKind.String); model.AddElement(usAddressType); // add a derived complex type "CnAddress" var cnAddressType = new EdmComplexType("Default", "CnAddress", addressType); cnAddressType.AddStructuralProperty("CnProp", EdmPrimitiveTypeKind.Guid); model.AddElement(cnAddressType); // add a complex type "Location" with complex type property var location = new EdmComplexType("Default", "Location"); location.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String); location.AddStructuralProperty("Address", new EdmComplexTypeReference(addressType, isNullable: true)); model.AddElement(location); // Add navigations customerType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo() { Name = "Orders", Target = orderType, TargetMultiplicity = EdmMultiplicity.Many }); orderType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo() { Name = "Customer", Target = customerType, TargetMultiplicity = EdmMultiplicity.One }); specialCustomerType.AddUnidirectionalNavigation( new EdmNavigationPropertyInfo { Name = "SpecialOrders", Target = specialOrderType, TargetMultiplicity = EdmMultiplicity.Many }); orderType.AddUnidirectionalNavigation( new EdmNavigationPropertyInfo { Name = "SpecialCustomer", Target = specialCustomerType, TargetMultiplicity = EdmMultiplicity.One }); // Add Entity set var container = new EdmEntityContainer("Default", "Container"); var customerSet = container.AddEntitySet("Customers", customerType); model.SetOptimisticConcurrencyAnnotation(customerSet, new[] { city }); var orderSet = container.AddEntitySet("Orders", orderType); customerSet.AddNavigationTarget(customerType.NavigationProperties().Single(np => np.Name == "Orders"), orderSet); customerSet.AddNavigationTarget( specialCustomerType.NavigationProperties().Single(np => np.Name == "SpecialOrders"), orderSet); orderSet.AddNavigationTarget(orderType.NavigationProperties().Single(np => np.Name == "Customer"), customerSet); orderSet.AddNavigationTarget( specialOrderType.NavigationProperties().Single(np => np.Name == "SpecialCustomer"), customerSet); NavigationSourceLinkBuilderAnnotation linkAnnotation = new MockNavigationSourceLinkBuilderAnnotation(); model.SetNavigationSourceLinkBuilder(customerSet, linkAnnotation); model.SetNavigationSourceLinkBuilder(orderSet, linkAnnotation); model.AddElement(container); return(model); }
protected virtual void VisitDeclaredProperties(EdmEntityType entityType, IEnumerable<EdmProperty> properties) { VisitCollection(properties, VisitEdmProperty); }
public static IEdmModel CreateTripPinServiceModel(string ns) { EdmModel model = new EdmModel(); var defaultContainer = new EdmEntityContainer(ns, "DefaultContainer"); model.AddElement(defaultContainer); var genderType = new EdmEnumType(ns, "PersonGender", isFlags: false); genderType.AddMember("Male", new EdmIntegerConstant(0)); genderType.AddMember("Female", new EdmIntegerConstant(1)); genderType.AddMember("Unknown", new EdmIntegerConstant(2)); model.AddElement(genderType); var cityType = new EdmComplexType(ns, "City"); cityType.AddProperty(new EdmStructuralProperty(cityType, "CountryRegion", EdmCoreModel.Instance.GetString(false))); cityType.AddProperty(new EdmStructuralProperty(cityType, "Name", EdmCoreModel.Instance.GetString(false))); cityType.AddProperty(new EdmStructuralProperty(cityType, "Region", EdmCoreModel.Instance.GetString(false))); model.AddElement(cityType); var locationType = new EdmComplexType(ns, "Location", null, false, true); locationType.AddProperty(new EdmStructuralProperty(locationType, "Address", EdmCoreModel.Instance.GetString(false))); locationType.AddProperty(new EdmStructuralProperty(locationType, "City", new EdmComplexTypeReference(cityType, false))); model.AddElement(locationType); var eventLocationType = new EdmComplexType(ns, "EventLocation", locationType, false, true); eventLocationType.AddProperty(new EdmStructuralProperty(eventLocationType, "BuildingInfo", EdmCoreModel.Instance.GetString(true))); model.AddElement(eventLocationType); var airportLocationType = new EdmComplexType(ns, "AirportLocation", locationType, false, true); airportLocationType.AddProperty(new EdmStructuralProperty(airportLocationType, "Loc", EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.GeographyPoint, false))); model.AddElement(airportLocationType); var photoType = new EdmEntityType(ns, "Photo", null, false, false, true); var photoIdProperty = new EdmStructuralProperty(photoType, "Id", EdmCoreModel.Instance.GetInt64(false)); photoType.AddProperty(photoIdProperty); photoType.AddKeys(photoIdProperty); photoType.AddProperty(new EdmStructuralProperty(photoType, "Name", EdmCoreModel.Instance.GetString(true))); model.AddElement(photoType); var photoSet = new EdmEntitySet(defaultContainer, "Photos", photoType); defaultContainer.AddElement(photoSet); var personType = new EdmEntityType(ns, "Person", null, false, /* isOpen */ true); var personIdProperty = new EdmStructuralProperty(personType, "UserName", EdmCoreModel.Instance.GetString(false)); personType.AddProperty(personIdProperty); personType.AddKeys(personIdProperty); personType.AddProperty(new EdmStructuralProperty(personType, "FirstName", EdmCoreModel.Instance.GetString(false))); personType.AddProperty(new EdmStructuralProperty(personType, "LastName", EdmCoreModel.Instance.GetString(false))); personType.AddProperty(new EdmStructuralProperty(personType, "Emails", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetString(true))))); personType.AddProperty(new EdmStructuralProperty(personType, "AddressInfo", new EdmCollectionTypeReference(new EdmCollectionType(new EdmComplexTypeReference(locationType, true))))); personType.AddProperty(new EdmStructuralProperty(personType, "Gender", new EdmEnumTypeReference(genderType, true))); personType.AddProperty(new EdmStructuralProperty(personType, "Concurrency", EdmCoreModel.Instance.GetInt64(false))); model.AddElement(personType); var personSet = new EdmEntitySet(defaultContainer, "People", personType); defaultContainer.AddElement(personSet); var airlineType = new EdmEntityType(ns, "Airline"); var airlineCodeProp = new EdmStructuralProperty(airlineType, "AirlineCode", EdmCoreModel.Instance.GetString(false)); airlineType.AddKeys(airlineCodeProp); airlineType.AddProperty(airlineCodeProp); airlineType.AddProperty(new EdmStructuralProperty(airlineType, "Name", EdmCoreModel.Instance.GetString(false))); model.AddElement(airlineType); var airlineSet = new EdmEntitySet(defaultContainer, "Airlines", airlineType); defaultContainer.AddElement(airlineSet); var airportType = new EdmEntityType(ns, "Airport"); var airportIdType = new EdmStructuralProperty(airportType, "IcaoCode", EdmCoreModel.Instance.GetString(false)); airportType.AddProperty(airportIdType); airportType.AddKeys(airportIdType); airportType.AddProperty(new EdmStructuralProperty(airportType, "Name", EdmCoreModel.Instance.GetString(false))); airportType.AddProperty(new EdmStructuralProperty(airportType, "IataCode", EdmCoreModel.Instance.GetString(false))); airportType.AddProperty(new EdmStructuralProperty(airportType, "Location", new EdmComplexTypeReference(airportLocationType, false))); model.AddElement(airportType); var airportSet = new EdmEntitySet(defaultContainer, "Airports", airportType); defaultContainer.AddElement(airportSet); var planItemType = new EdmEntityType(ns, "PlanItem"); var planItemIdType = new EdmStructuralProperty(planItemType, "PlanItemId", EdmCoreModel.Instance.GetInt32(false)); planItemType.AddProperty(planItemIdType); planItemType.AddKeys(planItemIdType); planItemType.AddProperty(new EdmStructuralProperty(planItemType, "ConfirmationCode", EdmCoreModel.Instance.GetString(true))); planItemType.AddProperty(new EdmStructuralProperty(planItemType, "StartsAt", EdmCoreModel.Instance.GetDateTimeOffset(true))); planItemType.AddProperty(new EdmStructuralProperty(planItemType, "EndsAt", EdmCoreModel.Instance.GetDateTimeOffset(true))); planItemType.AddProperty(new EdmStructuralProperty(planItemType, "Duration", EdmCoreModel.Instance.GetDuration(true))); model.AddElement(planItemType); var publicTransportationType = new EdmEntityType(ns, "PublicTransportation", planItemType); publicTransportationType.AddProperty(new EdmStructuralProperty(publicTransportationType, "SeatNumber", EdmCoreModel.Instance.GetString(true))); model.AddElement(publicTransportationType); var flightType = new EdmEntityType(ns, "Flight", publicTransportationType); var flightNumberType = new EdmStructuralProperty(flightType, "FlightNumber", EdmCoreModel.Instance.GetString(false)); flightType.AddProperty(flightNumberType); model.AddElement(flightType); var eventType = new EdmEntityType(ns, "Event", planItemType, false, true); eventType.AddProperty(new EdmStructuralProperty(eventType, "Description", EdmCoreModel.Instance.GetString(true))); eventType.AddProperty(new EdmStructuralProperty(eventType, "OccursAt", new EdmComplexTypeReference(eventLocationType, false))); model.AddElement(eventType); var tripType = new EdmEntityType(ns, "Trip"); var tripIdType = new EdmStructuralProperty(tripType, "TripId", EdmCoreModel.Instance.GetInt32(false)); tripType.AddProperty(tripIdType); tripType.AddKeys(tripIdType); tripType.AddProperty(new EdmStructuralProperty(tripType, "ShareId", EdmCoreModel.Instance.GetGuid(true))); tripType.AddProperty(new EdmStructuralProperty(tripType, "Description", EdmCoreModel.Instance.GetString(true))); tripType.AddProperty(new EdmStructuralProperty(tripType, "Name", EdmCoreModel.Instance.GetString(false))); tripType.AddProperty(new EdmStructuralProperty(tripType, "Budget", EdmCoreModel.Instance.GetSingle(false))); tripType.AddProperty(new EdmStructuralProperty(tripType, "StartsAt", EdmCoreModel.Instance.GetDateTimeOffset(false))); tripType.AddProperty(new EdmStructuralProperty(tripType, "EndsAt", EdmCoreModel.Instance.GetDateTimeOffset(false))); tripType.AddProperty(new EdmStructuralProperty(tripType, "Tags", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetString(false))))); model.AddElement(tripType); var friendsnNavigation = personType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo() { Name = "Friends", Target = personType, TargetMultiplicity = EdmMultiplicity.Many }); var personTripNavigation = personType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo() { Name = "Trips", Target = tripType, TargetMultiplicity = EdmMultiplicity.Many, ContainsTarget = true }); var personPhotoNavigation = personType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo() { Name = "Photo", Target = photoType, TargetMultiplicity = EdmMultiplicity.ZeroOrOne, }); var tripPhotosNavigation = tripType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo() { Name = "Photos", Target = photoType, TargetMultiplicity = EdmMultiplicity.Many, }); var tripItemNavigation = tripType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo() { Name = "PlanItems", Target = planItemType, ContainsTarget = true, TargetMultiplicity = EdmMultiplicity.Many }); var flightFromAirportNavigation = flightType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo() { Name = "From", Target = airportType, TargetMultiplicity = EdmMultiplicity.One }); var flightToAirportNavigation = flightType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo() { Name = "To", Target = airportType, TargetMultiplicity = EdmMultiplicity.One }); var flightAirlineNavigation = flightType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo() { Name = "Airline", Target = airlineType, TargetMultiplicity = EdmMultiplicity.One }); var me = new EdmSingleton(defaultContainer, "Me", personType); defaultContainer.AddElement(me); personSet.AddNavigationTarget(friendsnNavigation, personSet); me.AddNavigationTarget(friendsnNavigation, personSet); personSet.AddNavigationTarget(flightAirlineNavigation, airlineSet); me.AddNavigationTarget(flightAirlineNavigation, airlineSet); personSet.AddNavigationTarget(flightFromAirportNavigation, airportSet); me.AddNavigationTarget(flightFromAirportNavigation, airportSet); personSet.AddNavigationTarget(flightToAirportNavigation, airportSet); me.AddNavigationTarget(flightToAirportNavigation, airportSet); personSet.AddNavigationTarget(personPhotoNavigation, photoSet); me.AddNavigationTarget(personPhotoNavigation, photoSet); personSet.AddNavigationTarget(tripPhotosNavigation, photoSet); me.AddNavigationTarget(tripPhotosNavigation, photoSet); var getFavoriteAirlineFunction = new EdmFunction(ns, "GetFavoriteAirline", new EdmEntityTypeReference(airlineType, false), true, new EdmPathExpression("person/Trips/PlanItems/Microsoft.OData.SampleService.Models.TripPin.Flight/Airline"), true); getFavoriteAirlineFunction.AddParameter("person", new EdmEntityTypeReference(personType, false)); model.AddElement(getFavoriteAirlineFunction); var getInvolvedPeopleFunction = new EdmFunction(ns, "GetInvolvedPeople", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(personType, false))), true, null, true); getInvolvedPeopleFunction.AddParameter("trip", new EdmEntityTypeReference(tripType, false)); model.AddElement(getInvolvedPeopleFunction); var getFriendsTripsFunction = new EdmFunction(ns, "GetFriendsTrips", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(tripType, false))), true, new EdmPathExpression("person/Friends/Trips"), true); getFriendsTripsFunction.AddParameter("person", new EdmEntityTypeReference(personType, false)); getFriendsTripsFunction.AddParameter("userName", EdmCoreModel.Instance.GetString(false)); model.AddElement(getFriendsTripsFunction); var getNearestAirport = new EdmFunction(ns, "GetNearestAirport", new EdmEntityTypeReference(airportType, false), false, null, true); getNearestAirport.AddParameter("lat", EdmCoreModel.Instance.GetDouble(false)); getNearestAirport.AddParameter("lon", EdmCoreModel.Instance.GetDouble(false)); model.AddElement(getNearestAirport); var getNearestAirportFunctionImport = (IEdmFunctionImport)defaultContainer.AddFunctionImport("GetNearestAirport", getNearestAirport, new EdmEntitySetReferenceExpression(airportSet), true); var resetDataSourceAction = new EdmAction(ns, "ResetDataSource", null, false, null); model.AddElement(resetDataSourceAction); defaultContainer.AddActionImport(resetDataSourceAction); var shareTripAction = new EdmAction(ns, "ShareTrip", null, true, null); shareTripAction.AddParameter("person", new EdmEntityTypeReference(personType, false)); shareTripAction.AddParameter("userName", EdmCoreModel.Instance.GetString(false)); shareTripAction.AddParameter("tripId", EdmCoreModel.Instance.GetInt32(false)); model.AddElement(shareTripAction); model.SetDescriptionAnnotation(defaultContainer, "TripPin service is a sample service for OData V4."); model.SetOptimisticConcurrencyAnnotation(personSet, personType.StructuralProperties().Where(p => p.Name == "Concurrency")); // TODO: currently singleton does not support ETag feature // model.SetOptimisticConcurrencyAnnotation(me, personType.StructuralProperties().Where(p => p.Name == "Concurrency")); model.SetResourcePathCoreAnnotation(personSet, "People"); model.SetResourcePathCoreAnnotation(me, "Me"); model.SetResourcePathCoreAnnotation(airlineSet, "Airlines"); model.SetResourcePathCoreAnnotation(airportSet, "Airports"); model.SetResourcePathCoreAnnotation(photoSet, "Photos"); model.SetResourcePathCoreAnnotation(getNearestAirportFunctionImport, "Microsoft.OData.SampleService.Models.TripPin.GetNearestAirport"); model.SetDereferenceableIDsCoreAnnotation(defaultContainer, true); model.SetConventionalIDsCoreAnnotation(defaultContainer, true); model.SetPermissionsCoreAnnotation(personType.FindProperty("UserName"), CorePermission.Read); model.SetPermissionsCoreAnnotation(airlineType.FindProperty("AirlineCode"), CorePermission.Read); model.SetPermissionsCoreAnnotation(airportType.FindProperty("IcaoCode"), CorePermission.Read); model.SetPermissionsCoreAnnotation(planItemType.FindProperty("PlanItemId"), CorePermission.Read); model.SetPermissionsCoreAnnotation(tripType.FindProperty("TripId"), CorePermission.Read); model.SetPermissionsCoreAnnotation(photoType.FindProperty("Id"), CorePermission.Read); model.SetImmutableCoreAnnotation(airportType.FindProperty("IataCode"), true); model.SetComputedCoreAnnotation(personType.FindProperty("Concurrency"), true); model.SetAcceptableMediaTypesCoreAnnotation(photoType, new[] { "image/jpeg" }); model.SetConformanceLevelCapabilitiesAnnotation(defaultContainer, CapabilitiesConformanceLevelType.Advanced); model.SetSupportedFormatsCapabilitiesAnnotation(defaultContainer, new[] { "application/json;odata.metadata=full;IEEE754Compatible=false;odata.streaming=true", "application/json;odata.metadata=minimal;IEEE754Compatible=false;odata.streaming=true", "application/json;odata.metadata=none;IEEE754Compatible=false;odata.streaming=true" }); model.SetAsynchronousRequestsSupportedCapabilitiesAnnotation(defaultContainer, true); model.SetBatchContinueOnErrorSupportedCapabilitiesAnnotation(defaultContainer, false); model.SetNavigationRestrictionsCapabilitiesAnnotation(personSet, CapabilitiesNavigationType.None, new[] { new Tuple <IEdmNavigationProperty, CapabilitiesNavigationType>(friendsnNavigation, CapabilitiesNavigationType.Recursive) }); model.SetFilterFunctionsCapabilitiesAnnotation(defaultContainer, new[] { "contains", "endswith", "startswith", "length", "indexof", "substring", "tolower", "toupper", "trim", "concat", "year", "month", "day", "hour", "minute", "second", "round", "floor", "ceiling", "cast", "isof" }); model.SetSearchRestrictionsCapabilitiesAnnotation(personSet, true, CapabilitiesSearchExpressions.None); model.SetSearchRestrictionsCapabilitiesAnnotation(airlineSet, true, CapabilitiesSearchExpressions.None); model.SetSearchRestrictionsCapabilitiesAnnotation(airportSet, true, CapabilitiesSearchExpressions.None); model.SetSearchRestrictionsCapabilitiesAnnotation(photoSet, true, CapabilitiesSearchExpressions.None); model.SetInsertRestrictionsCapabilitiesAnnotation(personSet, true, new[] { personTripNavigation, friendsnNavigation }); model.SetInsertRestrictionsCapabilitiesAnnotation(airlineSet, true, null); model.SetInsertRestrictionsCapabilitiesAnnotation(airportSet, false, null); model.SetInsertRestrictionsCapabilitiesAnnotation(photoSet, true, null); // TODO: model.SetUpdateRestrictionsCapabilitiesAnnotation(); model.SetDeleteRestrictionsCapabilitiesAnnotation(airportSet, false, null); model.SetISOCurrencyMeasuresAnnotation(tripType.FindProperty("Budget"), "USD"); model.SetScaleMeasuresAnnotation(tripType.FindProperty("Budget"), 2); return(model); }
private static void BuildProperty(EdmEntityType entityType, PropertyInfo propertyInfo) { entityType.AddStructuralProperty(propertyInfo.Name, GetEdmPrimitiveKind(propertyInfo.PropertyType)); // if () }
public NodeToExpressionTranslatorTests() { this.functionExpressionBinder = new FunctionExpressionBinder(t => { throw new Exception(); }); this.customerResourceType = new ResourceType(typeof(Customer), ResourceTypeKind.EntityType, null, "Fake", "Customer", false) { IsOpenType = true }; var derivedCustomerResourceType = new ResourceType(typeof(DerivedCustomer), ResourceTypeKind.EntityType, this.customerResourceType, "Fake", "DerivedCustomer", false); this.weaklyBackedDerivedType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, derivedCustomerResourceType, "Fake", "WeaklyBackedCustomer", false) { CanReflectOnInstanceType = false }; var nameResourceProperty = new ResourceProperty("Name", ResourcePropertyKind.Key | ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(string))); this.customerResourceType.AddProperty(nameResourceProperty); var addressResourceType = new ResourceType(typeof(Address), ResourceTypeKind.ComplexType, null, "Fake", "Address", false); var addressResourceProperty = new ResourceProperty("Address", ResourcePropertyKind.ComplexType, addressResourceType); this.customerResourceType.AddProperty(addressResourceProperty); var namesResourceProperty = new ResourceProperty("Names", ResourcePropertyKind.Collection, ResourceType.GetCollectionResourceType(ResourceType.GetPrimitiveResourceType(typeof(string)))); this.customerResourceType.AddProperty(namesResourceProperty); var addressesResourceProperty = new ResourceProperty("Addresses", ResourcePropertyKind.Collection, ResourceType.GetCollectionResourceType(addressResourceType)); this.customerResourceType.AddProperty(addressesResourceProperty); var bestFriendResourceProperty = new ResourceProperty("BestFriend", ResourcePropertyKind.ResourceReference, this.customerResourceType); this.customerResourceType.AddProperty(bestFriendResourceProperty); var otherFriendsResourceProperty = new ResourceProperty("OtherFriends", ResourcePropertyKind.ResourceSetReference, this.customerResourceType); this.customerResourceType.AddProperty(otherFriendsResourceProperty); this.weaklyBackedResourceProperty = new ResourceProperty("WeaklyBacked", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(string))) { CanReflectOnInstanceTypeProperty = false }; var guid1ResourceProperty = new ResourceProperty("Guid1", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(Guid))); var guid2ResourceProperty = new ResourceProperty("Guid2", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(Guid))); var nullableGuid1ResourceProperty = new ResourceProperty("NullableGuid1", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(Guid?))); var nullableGuid2ResourceProperty = new ResourceProperty("NullableGuid2", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(Guid?))); this.customerResourceType.AddProperty(guid1ResourceProperty); this.customerResourceType.AddProperty(guid2ResourceProperty); this.customerResourceType.AddProperty(nullableGuid1ResourceProperty); this.customerResourceType.AddProperty(nullableGuid2ResourceProperty); var resourceSet = new ResourceSet("Customers", this.customerResourceType); resourceSet.SetReadOnly(); var resourceSetWrapper = ResourceSetWrapper.CreateForTests(resourceSet, EntitySetRights.All); this.model = new EdmModel(); this.customerEdmType = new MetadataProviderEdmEntityType("Fake", this.customerResourceType, null, false, true, false, t => {}); this.model.AddElement(this.customerEdmType); this.derivedCustomerEdmType = new MetadataProviderEdmEntityType("Fake", derivedCustomerResourceType, this.customerEdmType, false, false, false, t => { }); this.model.AddElement(this.derivedCustomerEdmType); this.weaklyBackedCustomerEdmType = new MetadataProviderEdmEntityType("Fake", weaklyBackedDerivedType, this.derivedCustomerEdmType, false, false, false, t => { }); this.model.AddElement(this.weaklyBackedCustomerEdmType); this.nameProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, nameResourceProperty, EdmCoreModel.Instance.GetString(true), null); this.customerEdmType.AddProperty(this.nameProperty); var addressEdmType = new MetadataProviderEdmComplexType("Fake", addressResourceType, null, false, false, t => {}); this.model.AddElement(addressEdmType); this.addressProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, addressResourceProperty, new EdmComplexTypeReference(addressEdmType, true), null); this.customerEdmType.AddProperty(this.addressProperty); this.namesProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, namesResourceProperty, new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetString(false))), null); this.customerEdmType.AddProperty(this.namesProperty); this.addressesProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, addressesResourceProperty, new EdmCollectionTypeReference(new EdmCollectionType(new EdmComplexTypeReference(addressEdmType, false))), null); this.customerEdmType.AddProperty(this.addressesProperty); this.bestFriendNavigation = new MetadataProviderEdmNavigationProperty(this.customerEdmType, bestFriendResourceProperty, new EdmEntityTypeReference(this.customerEdmType, true)); this.customerEdmType.AddProperty(this.bestFriendNavigation); this.otherFriendsNavigation = new MetadataProviderEdmNavigationProperty(this.customerEdmType, otherFriendsResourceProperty, new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(this.customerEdmType, true)))); this.customerEdmType.AddProperty(this.otherFriendsNavigation); this.weaklyBackedProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, this.weaklyBackedResourceProperty, EdmCoreModel.Instance.GetString(true), null); this.customerEdmType.AddProperty(this.weaklyBackedProperty); var guid1EdmProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, guid1ResourceProperty, EdmCoreModel.Instance.GetGuid(false), null); this.customerEdmType.AddProperty(guid1EdmProperty); var guid2EdmProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, guid2ResourceProperty, EdmCoreModel.Instance.GetGuid(false), null); this.customerEdmType.AddProperty(guid2EdmProperty); var nullableGuid1EdmProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, nullableGuid1ResourceProperty, EdmCoreModel.Instance.GetGuid(true), null); this.customerEdmType.AddProperty(nullableGuid1EdmProperty); var nullableGuid2EdmProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, nullableGuid2ResourceProperty, EdmCoreModel.Instance.GetGuid(true), null); this.customerEdmType.AddProperty(nullableGuid2EdmProperty); this.entitySet = new EdmEntitySetWithResourceSet(new EdmEntityContainer("Fake", "Container"), resourceSetWrapper, this.customerEdmType); ((EdmEntitySet)this.entitySet).AddNavigationTarget(this.bestFriendNavigation, this.entitySet); ((EdmEntitySet)this.entitySet).AddNavigationTarget(this.otherFriendsNavigation, this.entitySet); this.model.SetAnnotationValue(this.customerEdmType, this.customerResourceType); this.model.SetAnnotationValue(this.derivedCustomerEdmType, derivedCustomerResourceType); this.model.SetAnnotationValue(this.weaklyBackedCustomerEdmType, this.weaklyBackedDerivedType); this.model.SetAnnotationValue(this.nameProperty, nameResourceProperty); this.model.SetAnnotationValue(addressEdmType, addressResourceType); this.model.SetAnnotationValue(this.addressProperty, addressResourceProperty); this.model.SetAnnotationValue(this.namesProperty, namesResourceProperty); this.model.SetAnnotationValue(this.addressesProperty, addressesResourceProperty); this.model.SetAnnotationValue(this.bestFriendNavigation, bestFriendResourceProperty); this.model.SetAnnotationValue(this.otherFriendsNavigation, otherFriendsResourceProperty); this.model.SetAnnotationValue(this.weaklyBackedProperty, this.weaklyBackedResourceProperty); this.model.SetAnnotationValue(this.entitySet, resourceSetWrapper); this.model.SetAnnotationValue(guid1EdmProperty, guid1ResourceProperty); this.model.SetAnnotationValue(guid2EdmProperty, guid2ResourceProperty); this.model.SetAnnotationValue(nullableGuid1EdmProperty, nullableGuid1ResourceProperty); this.model.SetAnnotationValue(nullableGuid2EdmProperty, nullableGuid2ResourceProperty); this.testSubject = this.CreateTestSubject(); }
public void ValidateWriteMethodGroup() { // setup model var model = new EdmModel(); var complexType = new EdmComplexType("NS", "ComplexType"); complexType.AddStructuralProperty("PrimitiveProperty1", EdmPrimitiveTypeKind.Int64); complexType.AddStructuralProperty("PrimitiveProperty2", EdmPrimitiveTypeKind.Int64); var entityType = new EdmEntityType("NS", "EntityType", null, false, true); entityType.AddKeys( entityType.AddStructuralProperty("PrimitiveProperty", EdmPrimitiveTypeKind.Int64)); var container = new EdmEntityContainer("NS", "Container"); var entitySet = container.AddEntitySet("EntitySet", entityType); model.AddElements(new IEdmSchemaElement[] { complexType, entityType, container }); // write payload using new API string str1; { // setup var stream = new MemoryStream(); var message = new InMemoryMessage { Stream = stream }; message.SetHeader("Content-Type", "application/json;odata.metadata=full"); var settings = new ODataMessageWriterSettings { ODataUri = new ODataUri { ServiceRoot = new Uri("http://svc/") }, }; var writer = new ODataMessageWriter((IODataResponseMessage)message, settings, model); var entitySetWriter = writer.CreateODataResourceSetWriter(entitySet); entitySetWriter.Write(new ODataResourceSet(), () => entitySetWriter .Write(new ODataResource { Properties = new[] { new ODataProperty { Name = "PrimitiveProperty", Value = 1L } } }) .Write(new ODataResource { Properties = new[] { new ODataProperty { Name = "PrimitiveProperty", Value = 2L } } }, () => entitySetWriter .Write(new ODataNestedResourceInfo { Name = "DynamicNavProperty" }) .Write(new ODataNestedResourceInfo { Name = "DynamicCollectionProperty", IsCollection = true }, () => entitySetWriter .Write(new ODataResourceSet { TypeName = "Collection(NS.ComplexType)" }))) ); str1 = Encoding.UTF8.GetString(stream.ToArray()); } // write payload using old API string str2; { // setup var stream = new MemoryStream(); var message = new InMemoryMessage { Stream = stream }; message.SetHeader("Content-Type", "application/json;odata.metadata=full"); var settings = new ODataMessageWriterSettings { ODataUri = new ODataUri { ServiceRoot = new Uri("http://svc/") }, }; var writer = new ODataMessageWriter((IODataResponseMessage)message, settings, model); var entitySetWriter = writer.CreateODataResourceSetWriter(entitySet); entitySetWriter.WriteStart(new ODataResourceSet()); entitySetWriter.WriteStart(new ODataResource { Properties = new[] { new ODataProperty { Name = "PrimitiveProperty", Value = 1L } } }); entitySetWriter.WriteEnd(); entitySetWriter.WriteStart(new ODataResource { Properties = new[] { new ODataProperty { Name = "PrimitiveProperty", Value = 2L } } }); entitySetWriter.WriteStart(new ODataNestedResourceInfo { Name = "DynamicNavProperty" }); entitySetWriter.WriteEnd(); entitySetWriter.WriteStart(new ODataNestedResourceInfo { Name = "DynamicCollectionProperty", IsCollection = true }); entitySetWriter.WriteStart(new ODataResourceSet { TypeName = "Collection(NS.ComplexType)" }); entitySetWriter.WriteEnd(); entitySetWriter.WriteEnd(); entitySetWriter.WriteEnd(); entitySetWriter.WriteEnd(); str2 = Encoding.UTF8.GetString(stream.ToArray()); } str1.Should().Be(str2); }
private static IEdmModel GetEdmModel() { EdmModel model = new EdmModel(); IEdmTypeReference returnType = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Boolean, isNullable: false); IEdmTypeReference stringType = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.String, isNullable: false); IEdmTypeReference intType = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Int32, isNullable: false); // Entity EdmEntityType entity = new EdmEntityType("NS", "Entity", null, true, false); model.AddElement(entity); // Customer EdmEntityType customer = new EdmEntityType("NS", "Customer", entity); customer.AddKeys(customer.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32)); model.AddElement(customer); // VipCustomer EdmEntityType vipCustomer = new EdmEntityType("NS", "VipCustomer", customer); model.AddElement(vipCustomer); // functions bound to single EdmFunction isBaseUpgraded = new EdmFunction("NS", "IsBaseUpgraded", returnType, true, entitySetPathExpression: null, isComposable: false); isBaseUpgraded.AddParameter("entity", new EdmEntityTypeReference(entity, false)); model.AddElement(isBaseUpgraded); EdmFunction isUpgraded = new EdmFunction("NS", "IsUpgraded", returnType, true, entitySetPathExpression: null, isComposable: false); isUpgraded.AddParameter("entity", new EdmEntityTypeReference(customer, false)); model.AddElement(isUpgraded); EdmFunction isVipUpgraded = new EdmFunction("NS", "IsVipUpgraded", returnType, true, entitySetPathExpression: null, isComposable: false); isVipUpgraded.AddParameter("entity", new EdmEntityTypeReference(vipCustomer, false)); isVipUpgraded.AddParameter("param", stringType); model.AddElement(isVipUpgraded); // functions bound to collection EdmFunction isBaseAllUpgraded = new EdmFunction("NS", "IsBaseAllUpgraded", returnType, true, entitySetPathExpression: null, isComposable: false); isBaseAllUpgraded.AddParameter("entityset", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(entity, false)))); isBaseAllUpgraded.AddParameter("param", intType); model.AddElement(isBaseAllUpgraded); EdmFunction isAllUpgraded = new EdmFunction("NS", "IsAllCustomersUpgraded", returnType, true, entitySetPathExpression: null, isComposable: false); isAllUpgraded.AddParameter("entityset", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(customer, false)))); isAllUpgraded.AddParameter("param", intType); model.AddElement(isAllUpgraded); EdmFunction isVipAllUpgraded = new EdmFunction("NS", "IsVipAllUpgraded", returnType, true, entitySetPathExpression: null, isComposable: false); isVipAllUpgraded.AddParameter("entityset", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(vipCustomer, false)))); isVipAllUpgraded.AddParameter("param", intType); model.AddElement(isVipAllUpgraded); // overloads EdmFunction upgradeAll1 = new EdmFunction("NS", "UpgradedAll", returnType, true, entitySetPathExpression: null, isComposable: false); upgradeAll1.AddParameter("entityset", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(customer, false)))); upgradeAll1.AddParameter("age", intType); upgradeAll1.AddParameter("name", stringType); model.AddElement(upgradeAll1); EdmFunction upgradeAll2 = new EdmFunction("NS", "UpgradedAll", returnType, true, entitySetPathExpression: null, isComposable: false); upgradeAll2.AddParameter("entityset", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(customer, false)))); upgradeAll2.AddParameter("age", intType); upgradeAll2.AddParameter("name", stringType); upgradeAll2.AddParameter("gender", stringType); model.AddElement(upgradeAll2); EdmFunction upgradeAll3 = new EdmFunction("NS", "UpgradedAll", returnType, true, entitySetPathExpression: null, isComposable: false); upgradeAll3.AddParameter("entityset", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(vipCustomer, false)))); upgradeAll3.AddParameter("age", intType); upgradeAll3.AddParameter("name", stringType); model.AddElement(upgradeAll3); // function with optional parameters EdmFunction getSalaray = new EdmFunction("NS", "GetWholeSalary", intType, isBound: true, entitySetPathExpression: null, isComposable: false); getSalaray.AddParameter("entityset", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(customer, false)))); getSalaray.AddParameter("minSalary", intType); getSalaray.AddOptionalParameter("maxSalary", intType); getSalaray.AddOptionalParameter("aveSalary", intType, "129"); model.AddElement(getSalaray); EdmEntityContainer container = new EdmEntityContainer("NS", "Default"); container.AddEntitySet("Customers", customer); container.AddSingleton("Me", customer); model.AddElement(container); return(model); }
public async Task<IEdmModel> GetModelAsync(ModelContext context, CancellationToken cancellationToken) { IEdmModel innerModel = null; if (this.InnerHandler != null) { innerModel = await this.InnerHandler.GetModelAsync(context, cancellationToken); } var entityType = new EdmEntityType( "TestNamespace", "TestName" + _index); var model = innerModel as EdmModel; Assert.NotNull(model); model.AddElement(entityType); (model.EntityContainer as EdmEntityContainer) .AddEntitySet("TestEntitySet" + _index, entityType); return model; }
public void WriteContainedFeed() { EdmEntityType entityType = new EdmEntityType("NS", "Entity"); entityType.AddProperty(new EdmStructuralProperty(entityType, "Id", EdmCoreModel.Instance.GetInt32(false))); EdmEntityType expandEntityType = new EdmEntityType("NS", "ExpandEntity"); expandEntityType.AddProperty(new EdmStructuralProperty(expandEntityType, "Id", EdmCoreModel.Instance.GetInt32(false))); expandEntityType.AddProperty(new EdmStructuralProperty(expandEntityType, "Name", EdmCoreModel.Instance.GetString(false))); entityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo() { ContainsTarget = true, Name = "Property1", Target = expandEntityType, TargetMultiplicity = EdmMultiplicity.Many }); EdmOperation operation = new EdmFunction("NS", "Foo", EdmCoreModel.Instance.GetInt16(true)); operation.AddParameter("entry", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(entityType, false)))); Action <ODataJsonLightOutputContext> test = outputContext => { var entry1 = new ODataEntry(); entry1.Properties = new List <ODataProperty>() { new ODataProperty() { Name = "ID", Value = 1 }, }; var entry2 = new ODataEntry(); entry2.Properties = new List <ODataProperty>() { new ODataProperty() { Name = "ID", Value = 1 }, new ODataProperty() { Name = "Name", Value = "TestName" } }; var parameterWriter = new ODataJsonLightParameterWriter(outputContext, operation: null); parameterWriter.WriteStart(); var entryWriter = parameterWriter.CreateFeedWriter("feed"); entryWriter.WriteStart(new ODataFeed()); entryWriter.WriteStart(entry1); entryWriter.WriteStart(new ODataNavigationLink() { Name = "Property1", IsCollection = true }); entryWriter.WriteStart(new ODataFeed()); entryWriter.WriteStart(entry2); entryWriter.WriteEnd(); entryWriter.WriteEnd(); entryWriter.WriteEnd(); entryWriter.WriteEnd(); entryWriter.WriteEnd(); parameterWriter.WriteEnd(); parameterWriter.Flush(); }; WriteAndValidate(test, "{\"feed\":[{\"ID\":1,\"Property1\":[{\"ID\":1,\"Name\":\"TestName\"}]}]}", writingResponse: false); }
/// <summary> /// Adds a navigation property to the <paramref name="entityType"/>. This method creates an association type /// in order to add the navigation property. /// Returns the modified entity type for composability. /// </summary> /// <param name="entityType">The <see cref="EntityType"/> to add the navigation property to.</param> /// <param name="propertyName">The name of the property to add.</param> /// <param name="otherEndType">The type of the other end of the navigation property.</param> /// <returns>The <paramref name="entityType"/> instance after adding the navigation property to it.</returns> public static EdmEntityType NavigationProperty(this EdmEntityType entityType, string propertyName, EdmEntityType otherEndType) { ExceptionUtilities.CheckArgumentNotNull(entityType, "entityType"); ExceptionUtilities.CheckArgumentNotNull(propertyName, "propertyName"); // Create a navigation property representing one side of an association. // The partner representing the other side exists only inside this property and is not added to the target entity type, // so it should not cause any name collisions. EdmNavigationProperty navProperty = EdmNavigationProperty.CreateNavigationPropertyWithPartner( propertyName, otherEndType.ToTypeReference(), /*dependentProperties*/ null, /*principalProperties*/ null, /*containsTarget*/ false, EdmOnDeleteAction.None, "Partner", entityType.ToTypeReference(true), /*partnerDependentProperties*/ null, /*partnerPrincipalProperties*/ null, /*partnerContainsTarget*/ false, EdmOnDeleteAction.None); entityType.AddProperty(navProperty); return(entityType); }
private void CreateEntityTypeBody(EdmEntityType type, EntityTypeConfiguration config) { CreateStructuralTypeBody(type, config); IEdmStructuralProperty[] keys = config.Keys.Select(p => type.DeclaredProperties.OfType <IEdmStructuralProperty>().First(dp => dp.Name == p.PropertyInfo.Name)).ToArray(); type.AddKeys(keys); }
private void CreateNavigationProperty(StructuralTypeConfiguration config) { Contract.Assert(config != null); EdmStructuredType type = (EdmStructuredType)(GetEdmType(config.ClrType)); foreach (NavigationPropertyConfiguration navProp in config.NavigationProperties) { Func <NavigationPropertyConfiguration, EdmNavigationPropertyInfo> getInfo = nav => { EdmNavigationPropertyInfo info = new EdmNavigationPropertyInfo { Name = nav.Name, TargetMultiplicity = nav.Multiplicity, Target = GetEdmType(nav.RelatedClrType) as IEdmEntityType, ContainsTarget = nav.ContainsTarget, OnDelete = nav.OnDeleteAction }; // Principal properties if (nav.PrincipalProperties.Any()) { info.PrincipalProperties = GetDeclaringPropertyInfo(nav.PrincipalProperties); } // Dependent properties if (nav.DependentProperties.Any()) { info.DependentProperties = GetDeclaringPropertyInfo(nav.DependentProperties); } return(info); }; var navInfo = getInfo(navProp); var props = new Dictionary <IEdmProperty, NavigationPropertyConfiguration>(); EdmEntityType entityType = type as EdmEntityType; if (entityType != null && navProp.Partner != null) { var edmProperty = entityType.AddBidirectionalNavigation(navInfo, getInfo(navProp.Partner)); var partnerEdmProperty = (navInfo.Target as EdmEntityType).Properties().Single(p => p.Name == navProp.Partner.Name); props.Add(edmProperty, navProp); props.Add(partnerEdmProperty, navProp.Partner); } else { // Do not add this if we have have a partner relationship configured, as this // property will be added automatically through the AddBidirectionalNavigation var targetConfig = config.ModelBuilder.GetTypeConfigurationOrNull(navProp.RelatedClrType) as StructuralTypeConfiguration; if (!targetConfig.NavigationProperties.Any(p => p.Partner != null && p.Partner.Name == navInfo.Name)) { var edmProperty = type.AddUnidirectionalNavigation(navInfo); props.Add(edmProperty, navProp); } } foreach (var item in props) { var edmProperty = item.Key; var prop = item.Value; if (prop.PropertyInfo != null) { _properties[prop.PropertyInfo] = edmProperty; } if (prop.IsRestricted) { _propertiesRestrictions[edmProperty] = new QueryableRestrictions(prop); } if (prop.QueryConfiguration.ModelBoundQuerySettings != null) { _propertiesQuerySettings.Add(edmProperty, prop.QueryConfiguration.ModelBoundQuerySettings); } _propertyConfigurations[edmProperty] = prop; } } }
public ODataJsonLightWriterComplexIntegrationTests() { // Initialize open EntityType: EntityType. EdmModel edmModel = new EdmModel(); EdmEntityType edmEntityType = new EdmEntityType("TestNamespace", "EntityType", baseType: null, isAbstract: false, isOpen: true); edmEntityType.AddStructuralProperty("DeclaredProperty", EdmPrimitiveTypeKind.Guid); edmEntityType.AddStructuralProperty("DeclaredGeometryProperty", EdmPrimitiveTypeKind.Geometry); edmEntityType.AddStructuralProperty("DeclaredSingleProperty", EdmPrimitiveTypeKind.Single); edmEntityType.AddStructuralProperty("DeclaredDoubleProperty", EdmPrimitiveTypeKind.Double); edmEntityType.AddStructuralProperty("TimeOfDayProperty", EdmPrimitiveTypeKind.TimeOfDay); edmEntityType.AddStructuralProperty("DateProperty", EdmPrimitiveTypeKind.Date); edmModel.AddElement(edmEntityType); this.model = TestUtils.WrapReferencedModelsToMainModel(edmModel); this.entityType = edmEntityType; // Initialize derived ComplexType: Address and HomeAddress this.addressType = new EdmComplexType("TestNamespace", "Address", baseType: null, isAbstract: false, isOpen: false); this.addressType.AddStructuralProperty("City", EdmPrimitiveTypeKind.String); this.derivedAddressType = new EdmComplexType("TestNamespace", "HomeAddress", baseType: this.addressType, isAbstract: false, isOpen: false); this.derivedAddressType.AddStructuralProperty("FamilyName", EdmPrimitiveTypeKind.String); // Initialize open ComplexType: OpenAddress. this.openAddressType = new EdmComplexType("TestNamespace", "OpenAddress", baseType: null, isAbstract: false, isOpen: true); this.openAddressType.AddStructuralProperty("CountryRegion", EdmPrimitiveTypeKind.String); edmModel.AddElement(this.addressType); edmModel.AddElement(this.derivedAddressType); edmModel.AddElement(this.openAddressType); this.address = new ODataResource() { TypeName = "TestNamespace.Address", Properties = new ODataProperty[] { new ODataProperty { Name = "City", Value = "Shanghai" } } }; this.homeAddress = new ODataResource { TypeName = "TestNamespace.HomeAddress", Properties = new ODataProperty[] { new ODataProperty { Name = "FamilyName", Value = "Green" }, new ODataProperty { Name = "City", Value = "Shanghai" } } }; this.addressWithInstanceAnnotation = new ODataResource() { TypeName = "TestNamespace.Address", Properties = new ODataProperty[] { new ODataProperty { Name = "City", Value = "Shanghai" } }, InstanceAnnotations = new Collection <ODataInstanceAnnotation> { new ODataInstanceAnnotation("Is.ReadOnly", new ODataPrimitiveValue(true)) } }; this.homeAddressWithInstanceAnnotations = new ODataResource() { TypeName = "TestNamespace.HomeAddress", Properties = new ODataProperty[] { new ODataProperty { Name = "FamilyName", Value = "Green", InstanceAnnotations = new Collection <ODataInstanceAnnotation> { new ODataInstanceAnnotation("FamilyName.annotation", new ODataPrimitiveValue(true)) } }, new ODataProperty { Name = "City", Value = "Shanghai", InstanceAnnotations = new Collection <ODataInstanceAnnotation> { new ODataInstanceAnnotation("City.annotation1", new ODataPrimitiveValue(true)), new ODataInstanceAnnotation("City.annotation2", new ODataPrimitiveValue(123)) } } }, InstanceAnnotations = new Collection <ODataInstanceAnnotation> { new ODataInstanceAnnotation("Is.AutoComputable", new ODataPrimitiveValue(true)), new ODataInstanceAnnotation("Is.ReadOnly", new ODataPrimitiveValue(false)) } }; }
public void WriteEntityReferenceLinkAfterFeedJsonLightErrorTest() { EdmModel model = new EdmModel(); var container = new EdmEntityContainer("TestModel", "DefaultContainer"); model.AddElement(container); var customerType = new EdmEntityType("TestModel", "Customer"); var orderType = new EdmEntityType("TestModel", "Order"); var orderNavProp = customerType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "Orders", Target = orderType, TargetMultiplicity = EdmMultiplicity.Many }); var bestFriendNavProp = customerType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "BestFriend", Target = customerType, TargetMultiplicity = EdmMultiplicity.One }); var customerSet = container.AddEntitySet("Customers", customerType); var orderSet = container.AddEntitySet("Order", orderType); customerSet.AddNavigationTarget(orderNavProp, orderSet); customerSet.AddNavigationTarget(bestFriendNavProp, customerSet); model.AddElement(customerType); model.AddElement(orderType); ODataResource expandedOrderInstance = ObjectModelUtils.CreateDefaultEntryWithAtomMetadata(); expandedOrderInstance.TypeName = "TestModel.Order"; var testCases = new WriterNavigationLinkTests.NavigationLinkTestCase[] { // Entity reference link after empty feed in collection navigation link new WriterNavigationLinkTests.NavigationLinkTestCase { Items = new ODataItem[] { new ODataNestedResourceInfo() { IsCollection = true, Name = "Orders", Url = new Uri("http://odata.org/nav") }, ObjectModelUtils.CreateDefaultFeedWithAtomMetadata(), null, new ODataEntityReferenceLink() { Url = new Uri("http://odata.org/singleton") }, }, ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightWriter_EntityReferenceLinkAfterResourceSetInRequest") }, // Entity reference link after non-empty feed in collection navigation link new WriterNavigationLinkTests.NavigationLinkTestCase { Items = new ODataItem[] { new ODataNestedResourceInfo() { IsCollection = true, Name = "Orders", Url = new Uri("http://odata.org/nav") }, ObjectModelUtils.CreateDefaultFeedWithAtomMetadata(), expandedOrderInstance, null, null, new ODataEntityReferenceLink() { Url = new Uri("http://odata.org/singleton") }, }, ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightWriter_EntityReferenceLinkAfterResourceSetInRequest") }, // Entity reference link before and after empty feed in collection navigation link new WriterNavigationLinkTests.NavigationLinkTestCase { Items = new ODataItem[] { new ODataNestedResourceInfo() { IsCollection = true, Name = "Orders", Url = new Uri("http://odata.org/nav") }, new ODataEntityReferenceLink() { Url = new Uri("http://odata.org/singleton") }, ObjectModelUtils.CreateDefaultFeedWithAtomMetadata(), null, new ODataEntityReferenceLink() { Url = new Uri("http://odata.org/singleton") }, }, ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightWriter_EntityReferenceLinkAfterResourceSetInRequest") }, // Entity reference link after two empty feeds in collection navigation link new WriterNavigationLinkTests.NavigationLinkTestCase { Items = new ODataItem[] { new ODataNestedResourceInfo() { IsCollection = true, Name = "Orders", Url = new Uri("http://odata.org/nav") }, new ODataEntityReferenceLink() { Url = new Uri("http://odata.org/singleton") }, ObjectModelUtils.CreateDefaultFeedWithAtomMetadata(), null, ObjectModelUtils.CreateDefaultFeedWithAtomMetadata(), null, new ODataEntityReferenceLink() { Url = new Uri("http://odata.org/singleton") }, }, ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightWriter_EntityReferenceLinkAfterResourceSetInRequest") }, }; IEnumerable <PayloadWriterTestDescriptor <ODataItem> > testDescriptors = testCases.Select(testCase => testCase.ToEdmTestDescriptor(this.Settings, model, customerSet, customerType)); this.CombinatorialEngineProvider.RunCombinations( testDescriptors, this.WriterTestConfigurationProvider.JsonLightFormatConfigurations.Where(tc => tc.IsRequest), (testDescriptor, testConfiguration) => { TestWriterUtils.WriteAndVerifyODataEdmPayload(testDescriptor, testConfiguration, this.Assert, this.Logger); }); }
private IEdmModel GetModel() { if (_model != null) { return(_model); } var model = new EdmModel(); // EntityContainer: Service var container = new EdmEntityContainer("ns", "Service"); model.AddElement(container); // EntityType: Address var address = new EdmEntityType("ns", "Address"); var addressId = address.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32); address.AddKeys(addressId); model.AddElement(address); // EntitySet: Addresses var addresses = container.AddEntitySet("Addresses", address); // EntityType: PaymentInstrument var paymentInstrument = new EdmEntityType("ns", "PaymentInstrument"); var paymentInstrumentId = paymentInstrument.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32); paymentInstrument.AddKeys(paymentInstrumentId); var billingAddresses = paymentInstrument.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "BillingAddresses", Target = address, TargetMultiplicity = EdmMultiplicity.Many }); paymentInstrument.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "ContainedBillingAddresses", Target = address, TargetMultiplicity = EdmMultiplicity.Many, ContainsTarget = true }); model.AddElement(paymentInstrument); // EntityType: Account var account = new EdmEntityType("ns", "Account"); var accountId = account.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32); account.AddKeys(accountId); var myPaymentInstruments = account.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "MyPaymentInstruments", Target = paymentInstrument, TargetMultiplicity = EdmMultiplicity.Many, ContainsTarget = true }); model.AddElement(account); // EntitySet: Accounts var accounts = container.AddEntitySet("Accounts", account); var paymentInstruments = accounts.FindNavigationTarget(myPaymentInstruments) as EdmNavigationSource; Assert.NotNull(paymentInstruments); paymentInstruments.AddNavigationTarget(billingAddresses, addresses); // EntityType: Person var person = new EdmEntityType("ns", "Person"); var personId = person.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32); person.AddKeys(personId); var myAccounts = person.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "MyAccounts", Target = account, TargetMultiplicity = EdmMultiplicity.Many }); var myPermanentAccount = person.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "MyPermanentAccount", Target = account, TargetMultiplicity = EdmMultiplicity.One }); var myLatestAccount = person.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "MyLatestAccount", Target = account, TargetMultiplicity = EdmMultiplicity.One }); person.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "MyAddresses", Target = address, TargetMultiplicity = EdmMultiplicity.Many, ContainsTarget = true }); model.AddElement(person); // EntityType: Benefit var benefit = new EdmEntityType("ns", "Benefit"); var benefitId = benefit.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32); benefit.AddKeys(benefitId); model.AddElement(benefit); // EntityType: SpecialPerson var specialPerson = new EdmEntityType("ns", "SpecialPerson", person); specialPerson.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "Benefits", Target = benefit, TargetMultiplicity = EdmMultiplicity.Many, ContainsTarget = true }); model.AddElement(specialPerson); // EntityType: VIP var vip = new EdmEntityType("ns", "VIP", specialPerson); vip.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "MyBenefits", Target = benefit, TargetMultiplicity = EdmMultiplicity.Many, ContainsTarget = true }); model.AddElement(vip); // EntitySet: People var people = container.AddEntitySet("People", person); people.AddNavigationTarget(myAccounts, accounts); people.AddNavigationTarget(myLatestAccount, accounts); // EntityType: Club var club = new EdmEntityType("ns", "Club"); var clubId = club.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32); club.AddKeys(clubId); var members = club.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "Members", Target = person, TargetMultiplicity = EdmMultiplicity.Many, ContainsTarget = true }); // EntityType: SeniorClub var seniorClub = new EdmEntityType("ns", "SeniorClub", club); model.AddElement(seniorClub); // EntitySet: Clubs var clubs = container.AddEntitySet("Clubs", club); var membersInClub = clubs.FindNavigationTarget(members) as EdmNavigationSource; membersInClub.AddNavigationTarget(myAccounts, accounts); // Singleton: PermanentAccount var permanentAccount = container.AddSingleton("PermanentAccount", account); people.AddNavigationTarget(myPermanentAccount, permanentAccount); _model = model; return(_model); }
public void AutoComputeETagWithOptimisticConcurrencyControlAnnotationForDerivedType() { const string expected = "{" + "\"@odata.context\":\"http://example.com/$metadata#Managers/$entity\"," + "\"@odata.id\":\"Managers(123)\"," + "\"@odata.etag\":\"W/\\\"'lucy',10\\\"\"," + "\"@odata.editLink\":\"Managers(123)\"," + "\"@odata.mediaEditLink\":\"Managers(123)/$value\"," + "\"ID\":123," + "\"Name\":\"lucy\"," + "\"Class\":12306," + "\"Alias\":\"lily\"," + "\"TeamSize\":10}"; EdmModel model = new EdmModel(); EdmEntityType personType = new EdmEntityType("MyNs", "Person", null, false, false, true); personType.AddKeys(personType.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32)); var nameProperty = personType.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(isNullable: true)); personType.AddStructuralProperty("Class", EdmPrimitiveTypeKind.Int32); personType.AddStructuralProperty("Alias", EdmCoreModel.Instance.GetString(isNullable: true), null, EdmConcurrencyMode.Fixed); EdmEntityType managerType = new EdmEntityType("MyNs", "Manager", personType, false, false, true); var tsProperty = managerType.AddStructuralProperty("TeamSize", EdmPrimitiveTypeKind.Int32); var container = new EdmEntityContainer("MyNs", "Container"); model.AddElement(personType); model.AddElement(managerType); container.AddEntitySet("Managers", managerType); model.AddElement(container); IEdmEntitySet managerSet = model.FindDeclaredEntitySet("Managers"); model.SetOptimisticConcurrencyControlAnnotation(managerSet, new[] { nameProperty, tsProperty }); ODataEntry entry = new ODataEntry { Properties = new[] { new ODataProperty { Name = "ID", Value = 123 }, new ODataProperty { Name = "Name", Value = "lucy" }, new ODataProperty { Name = "Class", Value = 12306 }, new ODataProperty { Name = "Alias", Value = "lily" }, new ODataProperty { Name = "TeamSize", Value = 10 }, } }; string actual = GetWriterOutputForContentTypeAndKnobValue(entry, model, managerSet, managerType); Assert.Equal(expected, actual); }
public void ReadAvroAsParameter() { EdmEntityType personType = new EdmEntityType("TestNS", "Person"); personType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32); personType.AddStructuralProperty("Title", EdmPrimitiveTypeKind.String); var operation = new EdmAction("NS", "op1", null); operation.AddParameter("p1", EdmCoreModel.Instance.GetString(false)); operation.AddParameter("p2", new EdmEntityTypeReference(personType, false)); const string Schema = @"{ ""type"":""record"", ""name"":""NS.op1Parameter"", ""fields"": [ { ""name"":""p1"", ""type"":""string"" }, { ""name"":""p2"", ""type"": {""type"":""record"", ""name"":""TestNS.Person"", ""fields"": [ { ""name"":""Id"", ""type"":""int"" }, { ""name"":""Title"", ""type"":""string"" }, ] } } ] }"; var stream = new MemoryStream(); using (var writer = AvroContainer.CreateGenericWriter(Schema, stream, /*leave open*/ true, Codec.Null)) using (var seqWriter = new SequentialWriter <object>(writer, 24)) { RecordSchema parameterSchema = (RecordSchema)AvroSerializer.CreateGeneric(Schema).WriterSchema; AvroRecord ar = new AvroRecord(parameterSchema); ar["p1"] = "dat"; var personSchema = parameterSchema.GetField("p2").TypeSchema; AvroRecord person = new AvroRecord(personSchema); person["Id"] = 5; person["Title"] = "per1"; ar["p2"] = person; seqWriter.Write(ar); seqWriter.Flush(); } stream.Flush(); stream.Seek(0, SeekOrigin.Begin); var reader = new ODataAvroParameterReader(this.CreateODataInputContext(stream), operation); Assert.AreEqual(ODataParameterReaderState.Start, reader.State); Assert.IsTrue(reader.Read()); Assert.AreEqual(ODataParameterReaderState.Value, reader.State); Assert.AreEqual("p1", reader.Name); Assert.AreEqual("dat", reader.Value); Assert.IsTrue(reader.Read()); Assert.AreEqual(ODataParameterReaderState.Resource, reader.State); Assert.AreEqual("p2", reader.Name); var ew = reader.CreateResourceReader(); Assert.AreEqual(ODataReaderState.Start, ew.State); Assert.IsTrue(ew.Read()); Assert.AreEqual(ODataReaderState.ResourceStart, ew.State); Assert.IsTrue(ew.Read()); Assert.AreEqual(ODataReaderState.ResourceEnd, ew.State); var entry = ew.Item as ODataResource; Assert.IsFalse(ew.Read()); Assert.AreEqual(ODataReaderState.Completed, ew.State); Assert.IsNotNull(entry); var properties = entry.Properties.ToList(); Assert.AreEqual(2, properties.Count); Assert.AreEqual("Id", properties[0].Name); Assert.AreEqual(5, properties[0].Value); Assert.AreEqual("Title", properties[1].Name); Assert.AreEqual("per1", properties[1].Value); Assert.IsFalse(reader.Read()); Assert.AreEqual(ODataParameterReaderState.Completed, reader.State); }
public ODataWriterDerivedTypeConstraintTests() { // Create the basic model edmModel = new EdmModel(); // Entity Type edmCustomerType = new EdmEntityType("NS", "Customer"); edmCustomerType.AddKeys(edmCustomerType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32)); edmVipCustomerType = new EdmEntityType("NS", "VipCustomer", edmCustomerType); edmVipCustomerType.AddStructuralProperty("Vip", EdmPrimitiveTypeKind.String); edmNormalCustomerType = new EdmEntityType("NS", "NormalCustomer", edmCustomerType); edmNormalCustomerType.AddStructuralProperty("Email", EdmPrimitiveTypeKind.String); edmModel.AddElements(new[] { edmCustomerType, edmVipCustomerType, edmNormalCustomerType }); // Complex type edmAddressType = new EdmComplexType("NS", "Address"); edmAddressType.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String); edmUsAddressType = new EdmComplexType("NS", "UsAddress", edmAddressType); edmUsAddressType.AddStructuralProperty("ZipCode", EdmPrimitiveTypeKind.Int32); edmCnAddressType = new EdmComplexType("NS", "CnAddress", edmAddressType); edmCnAddressType.AddStructuralProperty("PostCode", EdmPrimitiveTypeKind.String); edmModel.AddElements(new[] { edmAddressType, edmUsAddressType, edmCnAddressType }); // EntityContainer EdmEntityContainer container = new EdmEntityContainer("NS", "Default"); edmMe = container.AddSingleton("Me", edmCustomerType); edmCustomers = container.AddEntitySet("Customers", edmCustomerType); edmModel.AddElement(container); // resource odataCustomerResource = new ODataResource { TypeName = "NS.Customer", Properties = new[] { new ODataProperty { Name = "Id", Value = 7 } } }; odataVipResource = new ODataResource { TypeName = "NS.VipCustomer", Properties = new[] { new ODataProperty { Name = "Id", Value = 8 }, new ODataProperty { Name = "Vip", Value = "Boss" } } }; odataNormalResource = new ODataResource { TypeName = "NS.NormalCustomer", Properties = new[] { new ODataProperty { Name = "Id", Value = 9 }, new ODataProperty { Name = "Email", Value = "*****@*****.**" } } }; odataAddressResource = new ODataResource { TypeName = "NS.Address", Properties = new[] { new ODataProperty { Name = "Street", Value = "Way" } } }; odataUsAddressResource = new ODataResource { TypeName = "NS.UsAddress", Properties = new[] { new ODataProperty { Name = "Street", Value = "RedWay" }, new ODataProperty { Name = "ZipCode", Value = 98052 } } }; odataCnAddressResource = new ODataResource { TypeName = "NS.CnAddress", Properties = new[] { new ODataProperty { Name = "Street", Value = "ShaWay" }, new ODataProperty { Name = "PostCode", Value = "201100" } } }; }
public void EntityTypeTypeReferenceFullNameTest() { var entityType = new EdmEntityType("n", "type"); entityType.FullTypeName().Should().Be("n.type"); }
public EntityTypeInfo(OeEdmModelMetadataProvider metadataProvider, Type clrType, EdmEntityType edmType, bool isRefModel, bool isDbQuery) { _metadataProvider = metadataProvider; ClrType = clrType; EdmType = edmType; IsRefModel = isRefModel; _isDbQuery = isDbQuery; _keyProperties = new List <KeyValuePair <PropertyInfo, EdmStructuralProperty> >(1); _navigationClrProperties = new List <FKeyInfo>(); }
public void TopLevelPropertyTest() { var injectedProperties = new[] { new { InjectedJSON = string.Empty, ExpectedException = (ExpectedException)null }, new { InjectedJSON = "\"@custom.annotation\": null", ExpectedException = (ExpectedException)null }, new { InjectedJSON = "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataAnnotationNamespacePrefix + "unknown\": { }", ExpectedException = (ExpectedException)null }, new { InjectedJSON = "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\": { }", ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_UnexpectedAnnotationProperties", JsonLightConstants.ODataContextAnnotationName) }, new { InjectedJSON = "\"@custom.annotation\": null, \"@custom.annotation\": 42", ExpectedException = (ExpectedException)null }, }; var payloads = new[] { new { Json = "{{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " + "\"value\": null" + "{1}{0}" + "}}", }, new { Json = "{{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " + "{0}{1}" + "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" + "}}", }, new { Json = "{{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " + "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" + "{1}{0}" + "}}", }, }; EdmModel model = new EdmModel(); var container = new EdmEntityContainer("TestModel", "DefaultContainer"); model.AddElement(container); var owningType = new EdmEntityType("TestModel", "OwningType"); owningType.AddKeys(owningType.AddStructuralProperty("ID", EdmCoreModel.Instance.GetInt32(false))); owningType.AddStructuralProperty("TopLevelProperty", EdmCoreModel.Instance.GetInt32(true)); owningType.AddStructuralProperty("TopLevelSpatialProperty", EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.GeographyPoint, false)); owningType.AddStructuralProperty("TopLevelCollectionProperty", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false))); model.AddElement(owningType); IEdmEntityType edmOwningType = (IEdmEntityType)model.FindDeclaredType("TestModel.OwningType"); IEdmStructuralProperty edmTopLevelProperty = (IEdmStructuralProperty)edmOwningType.FindProperty("TopLevelProperty"); IEdmStructuralProperty edmTopLevelSpatialProperty = (IEdmStructuralProperty)edmOwningType.FindProperty("TopLevelSpatialProperty"); IEdmStructuralProperty edmTopLevelCollectionProperty = (IEdmStructuralProperty)edmOwningType.FindProperty("TopLevelCollectionProperty"); PayloadReaderTestDescriptor.ReaderMetadata readerMetadata = new PayloadReaderTestDescriptor.ReaderMetadata(edmTopLevelProperty); PayloadReaderTestDescriptor.ReaderMetadata spatialReaderMetadata = new PayloadReaderTestDescriptor.ReaderMetadata(edmTopLevelSpatialProperty); PayloadReaderTestDescriptor.ReaderMetadata collectionReaderMetadata = new PayloadReaderTestDescriptor.ReaderMetadata(edmTopLevelCollectionProperty); var testDescriptors = payloads.SelectMany(payload => injectedProperties.Select(injectedProperty => { return(new NativeInputReaderTestDescriptor() { PayloadKind = ODataPayloadKind.Property, InputCreator = (tc) => { string input = string.Format(payload.Json, injectedProperty.InjectedJSON, string.IsNullOrEmpty(injectedProperty.InjectedJSON) ? string.Empty : ","); return input; }, PayloadEdmModel = model, // We use payload expected result just as a convenient way to run the reader for the Property payload kind. // We validate whether the reading succeeds or fails, but not the actual read values (at least not here). ExpectedResultCallback = (tc) => new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings) { ReaderMetadata = readerMetadata, ExpectedException = injectedProperty.ExpectedException, } }); })); var explicitPayloads = new[] { new { Description = "Custom property annotation - should be ignored.", Json = "{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " + "\"" + JsonLightUtils.GetPropertyAnnotationName("value", "custom.annotation") + "\": null," + "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" + "}", ReaderMetadata = readerMetadata, ExpectedException = (ExpectedException)null }, new { Description = "Duplicate custom property annotation - should not fail.", Json = "{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " + "\"" + JsonLightUtils.GetPropertyAnnotationName("value", "custom.annotation") + "\": null," + "\"" + JsonLightUtils.GetPropertyAnnotationName("value", "custom.annotation") + "\": 42," + "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" + "}", ReaderMetadata = readerMetadata, ExpectedException = (ExpectedException)null }, new { Description = "Unrecognized odata property annotation - should be ignored.", Json = "{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " + "\"" + JsonLightUtils.GetPropertyAnnotationName("value", JsonLightConstants.ODataAnnotationNamespacePrefix + "unknown") + "\": null," + "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" + "}", ReaderMetadata = readerMetadata, ExpectedException = (ExpectedException)null }, new { Description = "Custom property annotation after the property - should fail.", Json = "{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " + "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42," + "\"" + JsonLightUtils.GetPropertyAnnotationName("value", "custom.annotation") + "\": null" + "}", ReaderMetadata = readerMetadata, ExpectedException = ODataExpectedExceptions.ODataException("PropertyAnnotationAfterTheProperty", "custom.annotation", "value") }, new { Description = "OData property annotation.", Json = "{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Edm.Int32\"," + "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" + "}", ReaderMetadata = readerMetadata, ExpectedException = (ExpectedException)null }, new { Description = "Duplicate odata.type property should fail.", Json = "{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Edm.Int32\"," + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Edm.String\"," + "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" + "}", ReaderMetadata = readerMetadata, ExpectedException = ODataExpectedExceptions.ODataException("DuplicateAnnotationNotAllowed", JsonLightConstants.ODataTypeAnnotationName) }, new { Description = "Type information for top-level property - correct.", Json = "{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Edm.Int32\"," + "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" + "}", ReaderMetadata = readerMetadata, ExpectedException = (ExpectedException)null }, new { Description = "Type information for top-level property - different kind - should fail.", Json = "{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Collection(Edm.Int32)\"," + "\"" + JsonLightConstants.ODataValuePropertyName + "\": 42" + "}", ReaderMetadata = readerMetadata, ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectTypeKind", "Collection(Edm.Int32)", "Primitive", "Collection") }, new { Description = "Unknown type information for top-level null - should fail.", Json = "{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Unknown\"," + "\"" + JsonLightConstants.ODataValuePropertyName + "\": null" + "}", ReaderMetadata = readerMetadata, ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectTypeKind", "Unknown", "Primitive", "Complex") }, new { Description = "Invalid type information for top-level null - we don't allow null collections - should fail.", Json = "{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Collection(Edm.Int32)\", " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Collection(Edm.Int32)\"," + "\"" + JsonLightConstants.ODataValuePropertyName + "\": null" + "}", ReaderMetadata = collectionReaderMetadata, ExpectedException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullNamedValueForNonNullableType", "value", "Collection(Edm.Int32)") }, new { Description = "Type information for top-level spatial - should work.", Json = "{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.GeographyPoint\", " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"Edm.GeographyPoint\"," + "\"" + JsonLightConstants.ODataValuePropertyName + "\":" + SpatialUtils.GetSpatialStringValue(ODataFormat.Json, GeographyFactory.Point(33.1, -110.0).Build()) + "}", ReaderMetadata = spatialReaderMetadata, ExpectedException = (ExpectedException)null }, }; testDescriptors = testDescriptors.Concat(explicitPayloads.Select(payload => { return(new NativeInputReaderTestDescriptor() { PayloadKind = ODataPayloadKind.Property, InputCreator = (tc) => { return payload.Json; }, PayloadEdmModel = model, // We use payload expected result just as a convenient way to run the reader for the Property payload kind // since the reading should always fail, we don't need anything to compare the results to. ExpectedResultCallback = (tc) => new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings) { ReaderMetadata = payload.ReaderMetadata, ExpectedException = payload.ExpectedException, }, DebugDescription = payload.Description }); })); // Add a test descriptor to verify that we ignore odata.context in requests testDescriptors = testDescriptors.Concat( new NativeInputReaderTestDescriptor[] { new NativeInputReaderTestDescriptor() { DebugDescription = "Top-level property with invalid name.", PayloadKind = ODataPayloadKind.Property, InputCreator = tc => { return("{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\", " + "\"TopLevelProperty\": 42" + "}"); }, PayloadEdmModel = model, ExpectedResultCallback = tc => new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings) { ReaderMetadata = readerMetadata, ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_InvalidTopLevelPropertyName", "TopLevelProperty", "value") }, SkipTestConfiguration = tc => !tc.IsRequest } }); this.CombinatorialEngineProvider.RunCombinations( testDescriptors, this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations, (testDescriptor, testConfiguration) => { testDescriptor.RunTest(testConfiguration); }); }
public void SpatialPropertyErrorTest() { EdmModel model = new EdmModel(); var container = new EdmEntityContainer("TestModel", "DefaultContainer"); model.AddElement(container); var owningType = new EdmEntityType("TestModel", "OwningType"); owningType.AddKeys(owningType.AddStructuralProperty("ID", EdmCoreModel.Instance.GetInt32(false))); owningType.AddStructuralProperty("TopLevelProperty", EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.GeographyPoint, true)); model.AddElement(owningType); IEdmEntityType edmOwningType = (IEdmEntityType)model.FindDeclaredType("TestModel.OwningType"); IEdmStructuralProperty edmTopLevelProperty = (IEdmStructuralProperty)edmOwningType.FindProperty("TopLevelProperty"); PayloadReaderTestDescriptor.ReaderMetadata readerMetadata = new PayloadReaderTestDescriptor.ReaderMetadata(edmTopLevelProperty); string pointValue = SpatialUtils.GetSpatialStringValue(ODataFormat.Json, GeographyFactory.Point(33.1, -110.0).Build(), "Edm.GeographyPoint"); var explicitPayloads = new[] { new { Description = "Spatial value with type information and odata.type annotation - should fail.", Json = "{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.GeographyPoint\", " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"Edm.GeographyPoint\"," + "\"" + JsonLightConstants.ODataValuePropertyName + "\":" + pointValue + "}", ReaderMetadata = readerMetadata, ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_ODataTypeAnnotationInPrimitiveValue", JsonLightConstants.ODataTypeAnnotationName) }, new { Description = "Spatial value with odata.type annotation - should fail.", Json = "{ " + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.GeographyPoint\", " + "\"" + JsonLightConstants.ODataValuePropertyName + "\":" + pointValue + "}", ReaderMetadata = readerMetadata, ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_ODataTypeAnnotationInPrimitiveValue", JsonLightConstants.ODataTypeAnnotationName) }, }; var testDescriptors = explicitPayloads.Select(payload => { return(new NativeInputReaderTestDescriptor() { DebugDescription = payload.Description, PayloadKind = ODataPayloadKind.Property, InputCreator = (tc) => { return payload.Json; }, PayloadEdmModel = model, // We use payload expected result just as a convenient way to run the reader for the Property payload kind // since the reading should always fail, we don't need anything to compare the results to. ExpectedResultCallback = (tc) => new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings) { ReaderMetadata = payload.ReaderMetadata, ExpectedException = payload.ExpectedException, }, }); }); this.CombinatorialEngineProvider.RunCombinations( testDescriptors, this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations, (testDescriptor, testConfiguration) => { testDescriptor.RunTest(testConfiguration); }); }
public void WritingPayloadInt64SingleDoubleDecimalWithoutSuffix() { EdmModel model = new EdmModel(); EdmEntityType entityType = new EdmEntityType("NS", "MyTestEntity"); EdmStructuralProperty key = entityType.AddStructuralProperty("LongId", EdmPrimitiveTypeKind.Int64, false); entityType.AddKeys(key); entityType.AddStructuralProperty("FloatId", EdmPrimitiveTypeKind.Single, false); entityType.AddStructuralProperty("DoubleId", EdmPrimitiveTypeKind.Double, false); entityType.AddStructuralProperty("DecimalId", EdmPrimitiveTypeKind.Decimal, false); entityType.AddStructuralProperty("BoolValue1", EdmPrimitiveTypeKind.Boolean, false); entityType.AddStructuralProperty("BoolValue2", EdmPrimitiveTypeKind.Boolean, false); EdmComplexType complexType = new EdmComplexType("NS", "MyTestComplexType"); complexType.AddStructuralProperty("CLongId", EdmPrimitiveTypeKind.Int64, false); complexType.AddStructuralProperty("CFloatId", EdmPrimitiveTypeKind.Single, false); complexType.AddStructuralProperty("CDoubleId", EdmPrimitiveTypeKind.Double, false); complexType.AddStructuralProperty("CDecimalId", EdmPrimitiveTypeKind.Decimal, false); model.AddElement(complexType); EdmComplexTypeReference complexTypeRef = new EdmComplexTypeReference(complexType, true); entityType.AddStructuralProperty("ComplexProperty", complexTypeRef); entityType.AddStructuralProperty("LongNumbers", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetInt64(false)))); entityType.AddStructuralProperty("FloatNumbers", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetSingle(false)))); entityType.AddStructuralProperty("DoubleNumbers", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetDouble(false)))); entityType.AddStructuralProperty("DecimalNumbers", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetDecimal(false)))); entityType.AddStructuralProperty( "IntNumbers", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetInt32(false)))); entityType.AddStructuralProperty( "NullableIntNumbers", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetInt32(true)))); model.AddElement(entityType); ODataEntry entry = new ODataEntry() { Id = new Uri("http://test/Id"), TypeName = "NS.MyTestEntity", Properties = new[] { new ODataProperty { Name = "LongId", Value = 12L }, new ODataProperty { Name = "FloatId", Value = 34.98f }, new ODataProperty { Name = "DoubleId", Value = 56.010 }, new ODataProperty { Name = "DecimalId", Value = 78.62m }, new ODataProperty { Name = "BoolValue1", Value = true }, new ODataProperty { Name = "BoolValue2", Value = false }, new ODataProperty { Name = "LongNumbers", Value = new ODataCollectionValue { Items = new[] { 0L, long.MinValue, long.MaxValue }, TypeName = "Collection(Int64)" } }, new ODataProperty { Name = "FloatNumbers", Value = new ODataCollectionValue { Items = new[] { 1F, float.MinValue, float.MaxValue, float.PositiveInfinity, float.NegativeInfinity, float.NaN }, TypeName = "Collection(Single)" } }, new ODataProperty { Name = "DoubleNumbers", Value = new ODataCollectionValue { Items = new[] { -1D, double.MinValue, double.MaxValue, double.PositiveInfinity, double.NegativeInfinity, double.NaN }, TypeName = "Collection(Double)" } }, new ODataProperty { Name = "DecimalNumbers", Value = new ODataCollectionValue { Items = new[] { 0M, decimal.MinValue, decimal.MaxValue }, TypeName = "Collection(Decimal)" } }, new ODataProperty { Name = "ComplexProperty", Value = new ODataComplexValue { Properties = new[] { new ODataProperty { Name = "CLongId", Value = 1L }, new ODataProperty { Name = "CFloatId", Value = -1.0F }, new ODataProperty { Name = "CDoubleId", Value = 1.0D }, new ODataProperty { Name = "CDecimalId", Value = 1.0M }, } } } }, SerializationInfo = MySerializationInfo }; string outputPayload = this.WriterEntry(model, entry, entityType); string expectedPayload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:d=\"http://docs.oasis-open.org/odata/ns/data\" " + "xmlns:m=\"http://docs.oasis-open.org/odata/ns/metadata\" xmlns:georss=\"http://www.georss.org/georss\" " + "xmlns:gml=\"http://www.opengis.net/gml\" " + "m:context=\"http://odata.org/$metadata#MyTestEntity/$entity\">" + "<id>http://test/Id</id>" + "<category term=\"#NS.MyTestEntity\" scheme=\"http://docs.oasis-open.org/odata/ns/scheme\" />" + "<title />" + // "<updated>2013-10-01T19:35:43Z</updated>" + "<author><name /></author>" + "<content type=\"application/xml\">" + "<m:properties>" + "<d:LongId m:type=\"Int64\">12</d:LongId>" + "<d:FloatId m:type=\"Single\">34.98</d:FloatId>" + "<d:DoubleId m:type=\"Double\">56.01</d:DoubleId>" + "<d:DecimalId m:type=\"Decimal\">78.62</d:DecimalId>" + "<d:BoolValue1 m:type=\"Boolean\">true</d:BoolValue1>" + "<d:BoolValue2 m:type=\"Boolean\">false</d:BoolValue2>" + "<d:LongNumbers m:type=\"#Collection(Int64)\">" + "<m:element>0</m:element>" + "<m:element>-9223372036854775808</m:element>" + "<m:element>9223372036854775807</m:element>" + "</d:LongNumbers>" + "<d:FloatNumbers m:type=\"#Collection(Single)\">" + "<m:element>1</m:element>" + "<m:element>-3.40282347E+38</m:element>" + "<m:element>3.40282347E+38</m:element>" + "<m:element>INF</m:element>" + "<m:element>-INF</m:element>" + "<m:element>NaN</m:element>" + "</d:FloatNumbers>" + "<d:DoubleNumbers m:type=\"#Collection(Double)\">" + "<m:element>-1</m:element>" + "<m:element>-1.7976931348623157E+308</m:element>" + "<m:element>1.7976931348623157E+308</m:element>" + "<m:element>INF</m:element>" + "<m:element>-INF</m:element>" + "<m:element>NaN</m:element>" + "</d:DoubleNumbers>" + "<d:DecimalNumbers m:type=\"#Collection(Decimal)\">" + "<m:element>0</m:element>" + "<m:element>-79228162514264337593543950335</m:element>" + "<m:element>79228162514264337593543950335</m:element>" + "</d:DecimalNumbers>" + "<d:ComplexProperty m:type=\"#NS.MyTestComplexType\">" + "<d:CLongId m:type=\"Int64\">1</d:CLongId>" + "<d:CFloatId m:type=\"Single\">-1</d:CFloatId>" + "<d:CDoubleId m:type=\"Double\">1</d:CDoubleId>" + "<d:CDecimalId m:type=\"Decimal\">1.0</d:CDecimalId>" + "</d:ComplexProperty>" + "</m:properties>" + "</content>" + "</entry>"; outputPayload = Regex.Replace(outputPayload, "<updated>[^<]*</updated>", ""); outputPayload.Should().Be(expectedPayload); }
protected virtual void VisitEdmEntityType(EdmEntityType item) { VisitEdmNamedMetadataItem(item); if (item != null) { if (item.HasDeclaredKeyProperties) { VisitDeclaredKeyProperties(item, item.DeclaredKeyProperties); } if (item.HasDeclaredProperties) { VisitDeclaredProperties(item, item.DeclaredProperties); } if (item.HasDeclaredNavigationProperties) { VisitDeclaredNavigationProperties(item, item.DeclaredNavigationProperties); } } }
public CustomersModelWithInheritance() { EdmModel model = new EdmModel(); // Enum type simpleEnum EdmEnumType simpleEnum = new EdmEnumType("NS", "SimpleEnum"); simpleEnum.AddMember(new EdmEnumMember(simpleEnum, "First", new EdmEnumMemberValue(0))); simpleEnum.AddMember(new EdmEnumMember(simpleEnum, "Second", new EdmEnumMemberValue(1))); simpleEnum.AddMember(new EdmEnumMember(simpleEnum, "Third", new EdmEnumMemberValue(2))); model.AddElement(simpleEnum); // complex type address EdmComplexType address = new EdmComplexType("NS", "Address"); address.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String); address.AddStructuralProperty("City", EdmPrimitiveTypeKind.String); address.AddStructuralProperty("State", EdmPrimitiveTypeKind.String); address.AddStructuralProperty("ZipCode", EdmPrimitiveTypeKind.String); address.AddStructuralProperty("CountryOrRegion", EdmPrimitiveTypeKind.String); model.AddElement(address); // open complex type "Account" EdmComplexType account = new EdmComplexType("NS", "Account", null, false, true); account.AddStructuralProperty("Bank", EdmPrimitiveTypeKind.String); account.AddStructuralProperty("CardNum", EdmPrimitiveTypeKind.Int64); account.AddStructuralProperty("BankAddress", new EdmComplexTypeReference(address, isNullable: true)); model.AddElement(account); EdmComplexType specialAccount = new EdmComplexType("NS", "SpecialAccount", account, false, true); specialAccount.AddStructuralProperty("SpecialCard", EdmPrimitiveTypeKind.String); model.AddElement(specialAccount); // entity type customer EdmEntityType customer = new EdmEntityType("NS", "Customer"); customer.AddKeys(customer.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32)); IEdmProperty customerName = customer.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String); customer.AddStructuralProperty("SimpleEnum", simpleEnum.ToEdmTypeReference(isNullable: false)); customer.AddStructuralProperty("Address", new EdmComplexTypeReference(address, isNullable: true)); customer.AddStructuralProperty("Account", new EdmComplexTypeReference(account, isNullable: true)); IEdmTypeReference primitiveTypeReference = EdmCoreModel.Instance.GetPrimitive( EdmPrimitiveTypeKind.String, isNullable: true); var city = customer.AddStructuralProperty( "City", primitiveTypeReference, defaultValue: null); model.AddElement(customer); // derived entity type special customer EdmEntityType specialCustomer = new EdmEntityType("NS", "SpecialCustomer", customer); specialCustomer.AddStructuralProperty("SpecialCustomerProperty", EdmPrimitiveTypeKind.Guid); specialCustomer.AddStructuralProperty("SpecialAddress", new EdmComplexTypeReference(address, isNullable: true)); model.AddElement(specialCustomer); // entity type order (open entity type) EdmEntityType order = new EdmEntityType("NS", "Order", null, false, true); // EdmEntityType order = new EdmEntityType("NS", "Order"); order.AddKeys(order.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32)); order.AddStructuralProperty("City", EdmPrimitiveTypeKind.String); order.AddStructuralProperty("Amount", EdmPrimitiveTypeKind.Int32); model.AddElement(order); // derived entity type special order EdmEntityType specialOrder = new EdmEntityType("NS", "SpecialOrder", order, false, true); specialOrder.AddStructuralProperty("SpecialOrderProperty", EdmPrimitiveTypeKind.Guid); model.AddElement(specialOrder); // test entity EdmEntityType testEntity = new EdmEntityType("Microsoft.Test.AspNet.OData.Query.Expressions", "TestEntity"); testEntity.AddStructuralProperty("SampleProperty", EdmPrimitiveTypeKind.Binary); model.AddElement(testEntity); // containment // my order EdmEntityType myOrder = new EdmEntityType("NS", "MyOrder"); myOrder.AddKeys(myOrder.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32)); myOrder.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String); model.AddElement(myOrder); // order line EdmEntityType orderLine = new EdmEntityType("NS", "OrderLine"); orderLine.AddKeys(orderLine.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32)); orderLine.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String); model.AddElement(orderLine); EdmNavigationProperty orderLinesNavProp = myOrder.AddUnidirectionalNavigation( new EdmNavigationPropertyInfo { Name = "OrderLines", TargetMultiplicity = EdmMultiplicity.Many, Target = orderLine, ContainsTarget = true, }); EdmNavigationProperty nonContainedOrderLinesNavProp = myOrder.AddUnidirectionalNavigation( new EdmNavigationPropertyInfo { Name = "NonContainedOrderLines", TargetMultiplicity = EdmMultiplicity.Many, Target = orderLine, ContainsTarget = false, }); EdmAction tag = new EdmAction("NS", "tag", returnType: null, isBound: true, entitySetPathExpression: null); tag.AddParameter("entity", new EdmEntityTypeReference(orderLine, false)); model.AddElement(tag); // entity sets EdmEntityContainer container = new EdmEntityContainer("NS", "ModelWithInheritance"); model.AddElement(container); EdmEntitySet customers = container.AddEntitySet("Customers", customer); EdmEntitySet orders = container.AddEntitySet("Orders", order); EdmEntitySet myOrders = container.AddEntitySet("MyOrders", myOrder); // singletons EdmSingleton vipCustomer = container.AddSingleton("VipCustomer", customer); EdmSingleton mary = container.AddSingleton("Mary", customer); EdmSingleton rootOrder = container.AddSingleton("RootOrder", order); // annotations model.SetOptimisticConcurrencyAnnotation(customers, new[] { city }); // containment IEdmContainedEntitySet orderLines = (IEdmContainedEntitySet)myOrders.FindNavigationTarget(orderLinesNavProp); // no-containment IEdmNavigationSource nonContainedOrderLines = myOrders.FindNavigationTarget(nonContainedOrderLinesNavProp); // actions EdmAction upgrade = new EdmAction("NS", "upgrade", returnType: null, isBound: true, entitySetPathExpression: null); upgrade.AddParameter("entity", new EdmEntityTypeReference(customer, false)); model.AddElement(upgrade); EdmAction specialUpgrade = new EdmAction("NS", "specialUpgrade", returnType: null, isBound: true, entitySetPathExpression: null); specialUpgrade.AddParameter("entity", new EdmEntityTypeReference(specialCustomer, false)); model.AddElement(specialUpgrade); // actions bound to collection EdmAction upgradeAll = new EdmAction("NS", "UpgradeAll", returnType: null, isBound: true, entitySetPathExpression: null); upgradeAll.AddParameter("entityset", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(customer, false)))); model.AddElement(upgradeAll); EdmAction upgradeSpecialAll = new EdmAction("NS", "UpgradeSpecialAll", returnType: null, isBound: true, entitySetPathExpression: null); upgradeSpecialAll.AddParameter("entityset", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(specialCustomer, false)))); model.AddElement(upgradeSpecialAll); // functions IEdmTypeReference returnType = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Boolean, isNullable: false); IEdmTypeReference stringType = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.String, isNullable: false); IEdmTypeReference intType = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Int32, isNullable: false); EdmFunction IsUpgraded = new EdmFunction( "NS", "IsUpgraded", returnType, isBound: true, entitySetPathExpression: null, isComposable: false); IsUpgraded.AddParameter("entity", new EdmEntityTypeReference(customer, false)); model.AddElement(IsUpgraded); EdmFunction orderByCityAndAmount = new EdmFunction( "NS", "OrderByCityAndAmount", stringType, isBound: true, entitySetPathExpression: null, isComposable: false); orderByCityAndAmount.AddParameter("entity", new EdmEntityTypeReference(customer, false)); orderByCityAndAmount.AddParameter("city", stringType); orderByCityAndAmount.AddParameter("amount", intType); model.AddElement(orderByCityAndAmount); EdmFunction getOrders = new EdmFunction( "NS", "GetOrders", EdmCoreModel.GetCollection(order.ToEdmTypeReference(false)), isBound: true, entitySetPathExpression: null, isComposable: true); getOrders.AddParameter("entity", new EdmEntityTypeReference(customer, false)); getOrders.AddParameter("parameter", intType); model.AddElement(getOrders); EdmFunction IsSpecialUpgraded = new EdmFunction( "NS", "IsSpecialUpgraded", returnType, isBound: true, entitySetPathExpression: null, isComposable: false); IsSpecialUpgraded.AddParameter("entity", new EdmEntityTypeReference(specialCustomer, false)); model.AddElement(IsSpecialUpgraded); EdmFunction getSalary = new EdmFunction( "NS", "GetSalary", stringType, isBound: true, entitySetPathExpression: null, isComposable: false); getSalary.AddParameter("entity", new EdmEntityTypeReference(customer, false)); model.AddElement(getSalary); getSalary = new EdmFunction( "NS", "GetSalary", stringType, isBound: true, entitySetPathExpression: null, isComposable: false); getSalary.AddParameter("entity", new EdmEntityTypeReference(specialCustomer, false)); model.AddElement(getSalary); EdmFunction IsAnyUpgraded = new EdmFunction( "NS", "IsAnyUpgraded", returnType, isBound: true, entitySetPathExpression: null, isComposable: false); EdmCollectionType edmCollectionType = new EdmCollectionType(new EdmEntityTypeReference(customer, false)); IsAnyUpgraded.AddParameter("entityset", new EdmCollectionTypeReference(edmCollectionType)); model.AddElement(IsAnyUpgraded); EdmFunction isCustomerUpgradedWithParam = new EdmFunction( "NS", "IsUpgradedWithParam", returnType, isBound: true, entitySetPathExpression: null, isComposable: false); isCustomerUpgradedWithParam.AddParameter("entity", new EdmEntityTypeReference(customer, false)); isCustomerUpgradedWithParam.AddParameter("city", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.String, isNullable: false)); model.AddElement(isCustomerUpgradedWithParam); EdmFunction isCustomerLocal = new EdmFunction( "NS", "IsLocal", returnType, isBound: true, entitySetPathExpression: null, isComposable: false); isCustomerLocal.AddParameter("entity", new EdmEntityTypeReference(customer, false)); model.AddElement(isCustomerLocal); EdmFunction entityFunction = new EdmFunction( "NS", "GetCustomer", returnType, isBound: true, entitySetPathExpression: null, isComposable: false); entityFunction.AddParameter("entity", new EdmEntityTypeReference(customer, false)); entityFunction.AddParameter("customer", new EdmEntityTypeReference(customer, false)); model.AddElement(entityFunction); EdmFunction getOrder = new EdmFunction( "NS", "GetOrder", order.ToEdmTypeReference(false), isBound: true, entitySetPathExpression: null, isComposable: true); // Composable getOrder.AddParameter("entity", new EdmEntityTypeReference(customer, false)); getOrder.AddParameter("orderId", intType); model.AddElement(getOrder); // functions bound to collection EdmFunction isAllUpgraded = new EdmFunction("NS", "IsAllUpgraded", returnType, isBound: true, entitySetPathExpression: null, isComposable: false); isAllUpgraded.AddParameter("entityset", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(customer, false)))); isAllUpgraded.AddParameter("param", intType); model.AddElement(isAllUpgraded); EdmFunction isSpecialAllUpgraded = new EdmFunction("NS", "IsSpecialAllUpgraded", returnType, isBound: true, entitySetPathExpression: null, isComposable: false); isSpecialAllUpgraded.AddParameter("entityset", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(specialCustomer, false)))); isSpecialAllUpgraded.AddParameter("param", intType); model.AddElement(isSpecialAllUpgraded); // navigation properties EdmNavigationProperty ordersNavProp = customer.AddUnidirectionalNavigation( new EdmNavigationPropertyInfo { Name = "Orders", TargetMultiplicity = EdmMultiplicity.Many, Target = order }); mary.AddNavigationTarget(ordersNavProp, orders); vipCustomer.AddNavigationTarget(ordersNavProp, orders); customers.AddNavigationTarget(ordersNavProp, orders); orders.AddNavigationTarget( order.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "Customer", TargetMultiplicity = EdmMultiplicity.ZeroOrOne, Target = customer }), customers); // navigation properties on derived types. EdmNavigationProperty specialOrdersNavProp = specialCustomer.AddUnidirectionalNavigation( new EdmNavigationPropertyInfo { Name = "SpecialOrders", TargetMultiplicity = EdmMultiplicity.Many, Target = order }); vipCustomer.AddNavigationTarget(specialOrdersNavProp, orders); customers.AddNavigationTarget(specialOrdersNavProp, orders); orders.AddNavigationTarget( specialOrder.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo { Name = "SpecialCustomer", TargetMultiplicity = EdmMultiplicity.ZeroOrOne, Target = customer }), customers); model.SetAnnotationValue <BindableOperationFinder>(model, new BindableOperationFinder(model)); // set properties Model = model; Container = container; Customer = customer; Order = order; Address = address; Account = account; SpecialCustomer = specialCustomer; SpecialOrder = specialOrder; Orders = orders; Customers = customers; VipCustomer = vipCustomer; Mary = mary; RootOrder = rootOrder; OrderLine = orderLine; OrderLines = orderLines; NonContainedOrderLines = nonContainedOrderLines; UpgradeCustomer = upgrade; UpgradeSpecialCustomer = specialUpgrade; CustomerName = customerName; IsCustomerUpgraded = isCustomerUpgradedWithParam; IsSpecialCustomerUpgraded = IsSpecialUpgraded; Tag = tag; }
protected virtual void VisitDeclaredNavigationProperties( EdmEntityType entityType, IEnumerable<EdmNavigationProperty> navigationProperties) { VisitCollection(navigationProperties, VisitEdmNavigationProperty); }
public ODataJsonLightReaderEnumIntegrationTests() { EdmModel tmpModel = new EdmModel(); // enum without flags var enumType = new EdmEnumType("NS", "Color"); var red = new EdmEnumMember(enumType, "Red", new EdmEnumMemberValue(1)); enumType.AddMember(red); enumType.AddMember("Green", new EdmEnumMemberValue(2)); enumType.AddMember("Blue", new EdmEnumMemberValue(3)); tmpModel.AddElement(enumType); // enum with flags var enumFlagsType = new EdmEnumType("NS", "ColorFlags", isFlags: true); enumFlagsType.AddMember("Red", new EdmEnumMemberValue(1)); enumFlagsType.AddMember("Green", new EdmEnumMemberValue(2)); enumFlagsType.AddMember("Blue", new EdmEnumMemberValue(4)); tmpModel.AddElement(enumFlagsType); this.entityType = new EdmEntityType("NS", "MyEntityType", isAbstract: false, isOpen: true, baseType: null); EdmStructuralProperty floatId = new EdmStructuralProperty(this.entityType, "FloatId", EdmCoreModel.Instance.GetSingle(false)); this.entityType.AddKeys(floatId); this.entityType.AddProperty(floatId); var enumTypeReference = new EdmEnumTypeReference(enumType, true); this.entityType.AddProperty(new EdmStructuralProperty(this.entityType, "Color", enumTypeReference)); var enumFlagsTypeReference = new EdmEnumTypeReference(enumFlagsType, false); this.entityType.AddProperty(new EdmStructuralProperty(this.entityType, "ColorFlags", enumFlagsTypeReference)); // enum in complex type EdmComplexType myComplexType = new EdmComplexType("NS", "MyComplexType"); myComplexType.AddProperty(new EdmStructuralProperty(myComplexType, "MyColorFlags", enumFlagsTypeReference)); myComplexType.AddProperty(new EdmStructuralProperty(myComplexType, "Height", EdmCoreModel.Instance.GetDouble(false))); tmpModel.AddElement(myComplexType); this.entityType.AddProperty(new EdmStructuralProperty(this.entityType, "MyComplexType", new EdmComplexTypeReference(myComplexType, true))); // enum in derived complex type EdmComplexType myDerivedComplexType = new EdmComplexType("NS", "MyDerivedComplexType", myComplexType, false); myDerivedComplexType.AddProperty(new EdmStructuralProperty(myDerivedComplexType, "MyDerivedColorFlags", new EdmEnumTypeReference(enumFlagsType, false))); tmpModel.AddElement(myDerivedComplexType); // enum in collection type EdmCollectionType myCollectionType = new EdmCollectionType(enumFlagsTypeReference); this.entityType.AddProperty(new EdmStructuralProperty(this.entityType, "MyCollectionType", new EdmCollectionTypeReference(myCollectionType))); tmpModel.AddElement(this.entityType); var defaultContainer = new EdmEntityContainer("NS", "DefaultContainer_sub"); this.entitySet = new EdmEntitySet(defaultContainer, "MySet", this.entityType); defaultContainer.AddEntitySet(this.entitySet.Name, this.entityType); tmpModel.AddElement(defaultContainer); this.userModel = TestUtils.WrapReferencedModelsToMainModel("NS", "DefaultContainer", tmpModel); }
public Task<IEdmModel> GetModelAsync(ModelContext context, CancellationToken cancellationToken) { var model = new EdmModel(); var entityType = new EdmEntityType( "TestNamespace", "TestName"); var entityContainer = new EdmEntityContainer( "TestNamespace", "Entities"); entityContainer.AddEntitySet("TestEntitySet", entityType); model.AddElement(entityType); model.AddElement(entityContainer); return Task.FromResult<IEdmModel>(model); }
public void ReadOpenCollectionPropertyValue() { EdmModel model = new EdmModel(); EdmEntityType entityType = new EdmEntityType("NS", "MyTestEntity", null, false, true); EdmStructuralProperty key = entityType.AddStructuralProperty("LongId", EdmPrimitiveTypeKind.Int64, false); entityType.AddKeys(key); EdmComplexType complexType = new EdmComplexType("NS", "MyTestComplexType"); complexType.AddStructuralProperty("CLongId", EdmPrimitiveTypeKind.Int64, false); model.AddElement(complexType); EdmEntityContainer container = new EdmEntityContainer("EntityNs", "MyContainer_sub"); EdmEntitySet entitySet = container.AddEntitySet("MyTestEntitySet", entityType); model.AddElement(container); const string payload = "{" + "\"@odata.context\":\"http://www.example.com/$metadata#EntityNs.MyContainer.MyTestEntitySet/$entity\"," + "\"@odata.id\":\"http://mytest\"," + "\"[email protected]\":\"Collection(Edm.Int32)\"," + "\"OpenPrimitiveCollection\":[0,1,2]," + "\"[email protected]\":\"Collection(NS.MyTestComplexType)\"," + "\"OpenComplexTypeCollection\":[{\"CLongId\":\"1\"},{\"CLongId\":\"1\"}]" + "}"; IEdmModel mainModel = TestUtils.WrapReferencedModelsToMainModel("EntityNs", "MyContainer", model); ODataEntry entry = null; this.ReadEntryPayload(mainModel, payload, entitySet, entityType, reader => { entry = entry ?? reader.Item as ODataEntry; }); Assert.NotNull(entry); var intCollection = entry.Properties.FirstOrDefault( s => string.Equals( s.Name, "OpenPrimitiveCollection", StringComparison.OrdinalIgnoreCase)).Value.As <ODataCollectionValue>(); var list = new List <int?>(); foreach (var val in intCollection.Items) { list.Add(val as int?); } Assert.Equal(0, list[0]); Assert.Equal(1, (int)list[1]); Assert.Equal(2, (int)list[2]); var complexCollection = entry.Properties.FirstOrDefault( s => string.Equals( s.Name, "OpenComplexTypeCollection", StringComparison.OrdinalIgnoreCase)).Value.As <ODataCollectionValue>(); foreach (var val in complexCollection.Items) { ((ODataComplexValue)val).Properties.FirstOrDefault(s => string.Equals(s.Name, "CLongId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(1L, "value should be in correct type."); } }