예제 #1
0
        public void ConstructableTypeReferenceToStringTest()
        {
            IEdmEntityType  astonishing  = new EdmEntityType("AwesomeNamespace", "AstonishingEntity", null, false, false);
            IEdmComplexType breathTaking = new EdmComplexType("AwesomeNamespace", "BreathtakingComplex", null, false);

            IEdmEntityTypeReference          entity      = new EdmEntityTypeReference(astonishing, true);
            IEdmComplexTypeReference         complex     = new EdmComplexTypeReference(breathTaking, true);
            IEdmPrimitiveTypeReference       primitive   = EdmCoreModel.Instance.GetInt32(true);
            IEdmStringTypeReference          stringType  = EdmCoreModel.Instance.GetString(false, 128, false, true);
            IEdmBinaryTypeReference          binary      = EdmCoreModel.Instance.GetBinary(true, null, true);
            IEdmTemporalTypeReference        temporal    = EdmCoreModel.Instance.GetTemporal(EdmPrimitiveTypeKind.DateTimeOffset, 1, true);
            IEdmDecimalTypeReference         decimalType = EdmCoreModel.Instance.GetDecimal(3, 2, true);
            IEdmSpatialTypeReference         spatial     = EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.Geography, 1, true);
            IEdmEntityReferenceTypeReference entityRef   = new EdmEntityReferenceTypeReference(new EdmEntityReferenceType(astonishing), true);
            IEdmCollectionTypeReference      collection  = EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(true));
            IEdmTypeReference type = new EdmEntityTypeReference(astonishing, true);

            Assert.AreEqual("[AwesomeNamespace.AstonishingEntity Nullable=True]", entity.ToString(), "To string correct");
            Assert.AreEqual("[AwesomeNamespace.BreathtakingComplex Nullable=True]", complex.ToString(), "To string correct");
            Assert.AreEqual("[Edm.Int32 Nullable=True]", primitive.ToString(), "To string correct");
            Assert.AreEqual("[Edm.String Nullable=True MaxLength=128 Unicode=False]", stringType.ToString(), "To string correct");
            Assert.AreEqual("[Edm.Binary Nullable=True MaxLength=max]", binary.ToString(), "To string correct");
            Assert.AreEqual("[Edm.DateTimeOffset Nullable=True Precision=1]", temporal.ToString(), "To string correct");
            Assert.AreEqual("[Edm.Decimal Nullable=True Precision=3 Scale=2]", decimalType.ToString(), "To string correct");
            Assert.AreEqual("[Edm.Geography Nullable=True SRID=1]", spatial.ToString(), "To string correct");
            Assert.AreEqual("[Collection([Edm.Int32 Nullable=True]) Nullable=True]", collection.ToString(), "To string correct");
            Assert.AreEqual("[EntityReference(AwesomeNamespace.AstonishingEntity) Nullable=True]", entityRef.ToString(), "To string correct");
            Assert.AreEqual("[AwesomeNamespace.AstonishingEntity Nullable=True]", type.ToString(), "To string correct");
        }
예제 #2
0
        public void CreateEdmTypeSchemaReturnSchemaForComplexType(bool isNullable)
        {
            // Arrange
            IEdmModel       model   = EdmModelHelper.TripServiceModel;
            IEdmComplexType complex = model.SchemaElements.OfType <IEdmComplexType>().First(c => c.Name == "AirportLocation");

            Assert.NotNull(complex); // guard
            IEdmComplexTypeReference complexTypeReference = new EdmComplexTypeReference(complex, isNullable);
            ODataContext             context = new ODataContext(model);

            // Act
            var schema = context.CreateEdmTypeSchema(complexTypeReference);

            // & Assert
            Assert.NotNull(schema);

            if (isNullable)
            {
                Assert.Null(schema.Reference);
                Assert.NotNull(schema.AnyOf);
                Assert.NotEmpty(schema.AnyOf);
                var anyOf = Assert.Single(schema.AnyOf);
                Assert.NotNull(anyOf.Reference);
                Assert.Equal(ReferenceType.Schema, anyOf.Reference.Type);
                Assert.Equal(complex.FullTypeName(), anyOf.Reference.Id);
            }
            else
            {
                Assert.Null(schema.AnyOf);
                Assert.NotNull(schema.Reference);
                Assert.Equal(ReferenceType.Schema, schema.Reference.Type);
                Assert.Equal(complex.FullTypeName(), schema.Reference.Id);
            }
        }
        public void SerializeTopLevelPropertyOfComplexTypeShouldWork()
        {
            EdmModel model = new EdmModel();

            EdmComplexType complexType = new EdmComplexType("ns", "complex");

            complexType.AddProperty(new EdmStructuralProperty(complexType, "propertyName1", EdmCoreModel.Instance.GetInt32(isNullable: false)));
            complexType.AddProperty(new EdmStructuralProperty(complexType, "propertyName2", EdmCoreModel.Instance.GetString(isNullable: false)));
            model.AddElement(complexType);

            EdmComplexTypeReference complexReference = new EdmComplexTypeReference(complexType, isNullable: false);

            EdmEntityType entityType = new EdmEntityType("ns", "entityType", baseType: null, isAbstract: false, isOpen: false);

            entityType.AddStructuralProperty("complexPropertyName", complexReference);
            model.AddElement(entityType);

            ODataComplexValue complexValue = new ODataComplexValue {
                Properties = new[] { new ODataProperty {
                                         Name = "propertyName1", Value = 1
                                     }, new ODataProperty {
                                         Name = "propertyName2", Value = "stringValue"
                                     } }, TypeName = "ns.complex"
            };
            ODataProperty complexProperty = new ODataProperty {
                Name = "complexPropertyName", Value = complexValue
            };

            string val = SerializeProperty(model, complexProperty);

            val.Should().Be("<?xml version=\"1.0\" encoding=\"utf-8\"?><m:value xmlns:d=\"http://docs.oasis-open.org/odata/ns/data\" xmlns:georss=\"http://www.georss.org/georss\" xmlns:gml=\"http://www.opengis.net/gml\" m:context=\"http://odata.org/$metadata#ns.complex\" m:type=\"#ns.complex\" xmlns:m=\"http://docs.oasis-open.org/odata/ns/metadata\"><d:propertyName1 m:type=\"Int32\">1</d:propertyName1><d:propertyName2>stringValue</d:propertyName2></m:value>");
        }
예제 #4
0
        public void CreateODataCollectionValue_CanSerialize_IEdmObjects()
        {
            // Arrange
            Mock <IEdmComplexObject> edmComplexObject = new Mock <IEdmComplexObject>();

            IEdmComplexObject[]      collection        = new IEdmComplexObject[] { edmComplexObject.Object };
            ODataSerializerContext   serializerContext = new ODataSerializerContext();
            IEdmComplexTypeReference elementType       = new EdmComplexTypeReference(new EdmComplexType("NS", "ComplexType"), isNullable: true);

            edmComplexObject.Setup(s => s.GetEdmType()).Returns(elementType);
            IEdmCollectionTypeReference collectionType = new EdmCollectionTypeReference(new EdmCollectionType(elementType));

            Mock <ODataSerializerProvider>    serializerProvider = new Mock <ODataSerializerProvider>();
            Mock <ODataComplexTypeSerializer> elementSerializer  = new Mock <ODataComplexTypeSerializer>(MockBehavior.Strict, serializerProvider.Object);

            serializerProvider.Setup(s => s.GetEdmTypeSerializer(elementType)).Returns(elementSerializer.Object);
            elementSerializer.Setup(s => s.CreateODataComplexValue(collection[0], elementType, serializerContext)).Returns(new ODataComplexValue()).Verifiable();

            ODataCollectionSerializer serializer = new ODataCollectionSerializer(serializerProvider.Object);

            // Act
            var result = serializer.CreateODataCollectionValue(collection, elementType, serializerContext);

            // Assert
            elementSerializer.Verify();
        }
        public async Task WriteResourceValueAsync_WritesExpectedValueForOpenProperty()
        {
            var resourceValue = new ODataResourceValue
            {
                Properties = new List <ODataProperty>
                {
                    new ODataProperty {
                        Name = "LuckyNumber", Value = new ODataPrimitiveValue(13)
                    },
                    new ODataProperty {
                        Name = "FavoriteColor", Value = new ODataEnumValue("Black")
                    }
                },
                TypeName = "NS.Attributes"
            };

            var metadataTypeReference = new EdmComplexTypeReference(this.attributesComplexType, false);

            var result = await SetupJsonLightValueSerializerAndRunTestAsync(
                (jsonLightValueSerializer) =>
            {
                return(jsonLightValueSerializer.WriteResourceValueAsync(
                           resourceValue,
                           metadataTypeReference,
                           /* isOpenProperty */ true,
                           new NullDuplicatePropertyNameChecker()));
            });

            Assert.Equal("{\"@odata.type\":\"#NS.Attributes\",\"LuckyNumber\":13,\"FavoriteColor\":\"Black\"}", result);
        }
예제 #6
0
        public void GetClrType_Cached_OnlyOneInstance()
        {
            // Arrange
            ClrTypeCache    cache   = new ClrTypeCache();
            Type            clrType = typeof(CacheAddress);
            IEdmComplexType address = _model.SchemaElements.OfType <IEdmComplexType>().FirstOrDefault(c => c.Name == "Address");

            Action cacheCallAndVerify = () =>
            {
                IEdmComplexTypeReference addressTypeTrue = new EdmComplexTypeReference(address, true);
                Type actual = cache.GetClrType(addressTypeTrue, _model);
                Assert.Same(clrType, actual);

                IEdmComplexTypeReference addressTypeFalse = new EdmComplexTypeReference(address, false);
                actual = cache.GetClrType(addressTypeFalse, _model);
                Assert.Same(clrType, actual);

                Assert.Equal(2, cache.EdmToClrTypeCache.Count);
            };

            // Act & Assert
            cacheCallAndVerify();

            // 5 is a magic number, it doesn't matter, just want to call it mulitple times.
            for (int i = 0; i < 5; i++)
            {
                cacheCallAndVerify();
            }

            cacheCallAndVerify();
        }
예제 #7
0
        public void ReadingTypeDefinitionPayloadWithEdmTypeAnnotationJsonLight()
        {
            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);

            entityType.AddStructuralProperty("Address", complexTypeRef);

            model.AddElement(weightType);
            model.AddElement(heightType);
            model.AddElement(addressType);
            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]\":\"#Edm.Double\"," +
                "\"Weight\":60.5," +
                "\"Address\":{\"[email protected]\":\"#Edm.String\",\"CountryRegion\":\"China\"}" +
                "}";

            ODataEntry entry = null;

            this.ReadEntryPayload(model, payload, entitySet, entityType, reader => { entry = entry ?? reader.Item as ODataEntry; });
            Assert.IsNotNull(entry, "entry shouldn't be null");

            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");
        }
예제 #8
0
            private IEdmTypeReference BuildTypeReference(EntityRelationElement relationElement)
            {
                var complexType = (IEdmComplexType)BuildSchemaType(relationElement.Target);

                IEdmTypeReference typeReference;

                switch (relationElement.Cardinality)
                {
                case EntityRelationCardinality.One:
                    typeReference = new EdmComplexTypeReference(complexType, false);
                    break;

                case EntityRelationCardinality.OptionalOne:
                    typeReference = new EdmComplexTypeReference(complexType, true);
                    break;

                case EntityRelationCardinality.Many:
                    typeReference = EdmCoreModel.GetCollection(new EdmComplexTypeReference(complexType, true));
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                return(typeReference);
            }
예제 #9
0
        public void WritingMultipleInstanceAnnotationInResourceValueShouldWrite(string filter, string expect)
        {
            var complexType = new EdmComplexType("NS", "Address");

            model.AddElement(complexType);
            settings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter(filter);
            var result = this.SetupSerializerAndRunTest(serializer =>
            {
                var resourceValue = new ODataResourceValue
                {
                    TypeName            = "NS.Address",
                    InstanceAnnotations = new Collection <ODataInstanceAnnotation>
                    {
                        new ODataInstanceAnnotation("Custom.Bool", new ODataPrimitiveValue(true)),
                        new ODataInstanceAnnotation("Custom.Int", new ODataPrimitiveValue(123)),
                        new ODataInstanceAnnotation("My.String", new ODataPrimitiveValue("annotation")),
                        new ODataInstanceAnnotation("My.Bool", new ODataPrimitiveValue(false))
                    }
                };

                var complexTypeRef = new EdmComplexTypeReference(complexType, false);
                serializer.WriteResourceValue(resourceValue, complexTypeRef, false, serializer.CreateDuplicatePropertyNameChecker());
            });

            Assert.Equal(expect, result);
        }
예제 #10
0
        public static IEdmModel Build()
        {
            var addressType = new EdmComplexType(Namespace, "address");

            addressType.AddStructuralProperty("street", EdmPrimitiveTypeKind.String);
            addressType.AddStructuralProperty("city", EdmPrimitiveTypeKind.String);

            var addressTypeRef   = new EdmComplexTypeReference(addressType, isNullable: false);
            var addressesTypeRef = EdmCoreModel.GetCollection(addressTypeRef);

            var nonNullableStringTypeRef = EdmCoreModel.Instance.GetString(isNullable: false);
            var tagsTypeRef = EdmCoreModel.GetCollection(nonNullableStringTypeRef);

            var docEntityType         = new EdmEntityType(Namespace, DocEntityTypeName);
            EdmStructuralProperty key = docEntityType.AddStructuralProperty("id", EdmPrimitiveTypeKind.String);

            docEntityType.AddKeys(key);
            docEntityType.AddStructuralProperty("addresses", addressesTypeRef);
            docEntityType.AddStructuralProperty("tags", tagsTypeRef);

            var docEntitySetType = EdmCoreModel.GetCollection(new EdmEntityTypeReference(docEntityType, isNullable: true));

            var container = new EdmEntityContainer("Default", "Container");

            container.AddEntitySet("Docs", docEntityType);

            var model = new EdmModel();

            model.AddElements(new IEdmSchemaElement[] { container, addressType, docEntityType });
            return(model);
        }
        public ODataJsonLightCollectionWriterTests()
        {
            collectionStartWithoutSerializationInfo = new ODataCollectionStart();

            collectionStartWithSerializationInfo = new ODataCollectionStart();
            collectionStartWithSerializationInfo.SetSerializationInfo(new ODataCollectionStartSerializationInfo {
                CollectionTypeName = "Collection(ns.Address)"
            });

            address = new ODataComplexValue {
                Properties = new[] { new ODataProperty {
                                         Name = "Street", Value = "1 Microsoft Way"
                                     }, new ODataProperty {
                                         Name = "Zipcode", Value = 98052
                                     }, new ODataProperty {
                                         Name = "State", Value = new ODataEnumValue("WA", "ns.StateEnum")
                                     } }
            };
            items = new[] { address };

            EdmComplexType addressType = new EdmComplexType("ns", "Address");

            addressType.AddProperty(new EdmStructuralProperty(addressType, "Street", EdmCoreModel.Instance.GetString(isNullable: true)));
            addressType.AddProperty(new EdmStructuralProperty(addressType, "Zipcode", EdmCoreModel.Instance.GetInt32(isNullable: true)));
            var stateEnumType = new EdmEnumType("ns", "StateEnum", isFlags: true);

            stateEnumType.AddMember("IL", new EdmIntegerConstant(1));
            stateEnumType.AddMember("WA", new EdmIntegerConstant(2));
            addressType.AddProperty(new EdmStructuralProperty(addressType, "State", new EdmEnumTypeReference(stateEnumType, true)));

            addressTypeReference = new EdmComplexTypeReference(addressType, isNullable: false);
        }
        public ODataJsonLightValueSerializerAsyncTests()
        {
            this.model = new EdmModel();

            this.colorEnumType = new EdmEnumType("NS", "Color");
            colorEnumType.AddMember(new EdmEnumMember(colorEnumType, "Black", new EdmEnumMemberValue(0)));
            colorEnumType.AddMember(new EdmEnumMember(colorEnumType, "White", new EdmEnumMemberValue(1)));
            this.model.AddElement(this.colorEnumType);

            attributesComplexType = new EdmComplexType("NS", "Attributes");
            attributesComplexType.AddStructuralProperty("LuckyNumber", EdmPrimitiveTypeKind.Int32);
            attributesComplexType.AddStructuralProperty("FavoriteColor", new EdmEnumTypeReference(colorEnumType, false));
            this.model.AddElement(this.attributesComplexType);

            EdmComplexTypeReference attributesComplexTypeRef = new EdmComplexTypeReference(attributesComplexType, true);

            this.entityType = new EdmEntityType("NS", "EntityType");
            entityType.AddKeys(entityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
            entityType.AddStructuralProperty("Attributes", new EdmCollectionTypeReference(new EdmCollectionType(attributesComplexTypeRef)));
            this.model.AddElement(this.entityType);

            this.stream   = new MemoryStream();
            this.settings = new ODataMessageWriterSettings {
                EnableMessageStreamDisposal = false, Version = ODataVersion.V4
            };
            this.settings.SetServiceDocumentUri(new Uri("http://tempuri.org"));
        }
예제 #13
0
        public void ApplyAnnotations_FailsWithUsefulErrorMessageOnUnknownProperty()
        {
            // Arrange
            const string HelpfulErrorMessage =
                "The property 'Unknown' does not exist on type 'namespace.name'. Make sure to only use property names " +
                "that are defined by the type.";

            var property = new ODataProperty {
                Name = "Unknown", Value = "Value"
            };
            var entityType = new EdmComplexType("namespace", "name");

            entityType.AddStructuralProperty("Known", EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(typeof(string)));

            var entityTypeReference = new EdmComplexTypeReference(entityType, isNullable: false);

            // Act
            var exception = Assert.Throws <ODataException>(() =>
                                                           DeserializationHelpers.ApplyProperty(
                                                               property,
                                                               entityTypeReference,
                                                               resource: null,
                                                               deserializerProvider: null,
                                                               readContext: null));

            // Assert
            Assert.Equal(HelpfulErrorMessage, exception.Message);
        }
예제 #14
0
        public void WritingMultipleInstanceAnnotationInComplexValueShouldWrite()
        {
            var complexType = new EdmComplexType("TestNamespace", "Address");

            model.AddElement(complexType);
            settings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");
            var result = this.SetupSerializerAndRunTest(serializer =>
            {
                var complexValue = new ODataComplexValue
                {
                    TypeName            = "TestNamespace.Address",
                    InstanceAnnotations = new Collection <ODataInstanceAnnotation>
                    {
                        new ODataInstanceAnnotation("Annotation.1", new ODataPrimitiveValue(true)),
                        new ODataInstanceAnnotation("Annotation.2", new ODataPrimitiveValue(123)),
                        new ODataInstanceAnnotation("Annotation.3", new ODataPrimitiveValue("annotation"))
                    }
                };

                var complexTypeRef = new EdmComplexTypeReference(complexType, false);
                serializer.WriteComplexValue(complexValue, complexTypeRef, false, false, new DuplicatePropertyNamesChecker(false, true));
            });

            result.Should().Contain("\"@Annotation.1\":true,\"@Annotation.2\":123,\"@Annotation.3\":\"annotation\"");
        }
예제 #15
0
        public void EqualsOnComplexTypesWithDifferentNullabilityIsSupported()
        {
            var notNullableType = new EdmComplexTypeReference(HardCodedTestModel.GetAddressType(), false);
            var nullableType    = new EdmComplexTypeReference(HardCodedTestModel.GetAddressType(), true);

            IEdmTypeReference left      = notNullableType;
            IEdmTypeReference right     = nullableType;
            SingleValueNode   leftNode  = new SingleValuePropertyAccessNode(new ConstantNode(null) /*parent*/, new EdmStructuralProperty(new EdmEntityType("MyNamespace", "MyEntityType"), "myPropertyName", left));
            SingleValueNode   rightNode = new SingleValuePropertyAccessNode(new ConstantNode(null) /*parent*/, new EdmStructuralProperty(new EdmEntityType("MyNamespace", "MyEntityType"), "myPropertyName", right));
            var result = TypePromotionUtils.PromoteOperandTypes(BinaryOperatorKind.Equal, leftNode, rightNode, out left, out right);

            result.Should().BeTrue();
            left.ShouldBeEquivalentTo(nullableType);
            right.ShouldBeEquivalentTo(nullableType);

            // Reverse order
            left      = nullableType;
            right     = notNullableType;
            leftNode  = new SingleValuePropertyAccessNode(new ConstantNode(null) /*parent*/, new EdmStructuralProperty(new EdmEntityType("MyNamespace", "MyEntityType"), "myPropertyName", left));
            rightNode = new SingleValuePropertyAccessNode(new ConstantNode(null) /*parent*/, new EdmStructuralProperty(new EdmEntityType("MyNamespace", "MyEntityType"), "myPropertyName", right));
            result    = TypePromotionUtils.PromoteOperandTypes(BinaryOperatorKind.Equal, leftNode, rightNode, out left, out right);

            result.Should().BeTrue();
            left.ShouldBeEquivalentTo(nullableType);
            right.ShouldBeEquivalentTo(nullableType);
        }
예제 #16
0
        private static object ConvertComplexValue(ODataComplexValue complexValue, ref IEdmTypeReference propertyType,
                                                  ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)
        {
            IEdmComplexTypeReference edmComplexType;

            if (propertyType == null)
            {
                // open complex property
                Contract.Assert(!String.IsNullOrEmpty(complexValue.TypeName),
                                "ODataLib should have verified that open complex value has a type name since we provided metadata.");
                IEdmModel model   = readContext.Model;
                IEdmType  edmType = model.FindType(complexValue.TypeName);
                Contract.Assert(edmType.TypeKind == EdmTypeKind.Complex, "ODataLib should have verified that complex value has a complex resource type.");
                edmComplexType = new EdmComplexTypeReference(edmType as IEdmComplexType, isNullable: true);
                propertyType   = edmComplexType;
            }
            else
            {
                edmComplexType = propertyType.AsComplex();
            }

            ODataEdmTypeDeserializer deserializer = deserializerProvider.GetEdmTypeDeserializer(edmComplexType);

            return(deserializer.ReadInline(complexValue, propertyType, readContext));
        }
예제 #17
0
        private static ODataValue GetComplexValue(InstanceAnnotation entryAnnotation, object annotation, IEdmModel model, ODataComplexTypeSerializer complexSerializer, ODataSerializerContext serializerContext)
        {
            Contract.Requires(entryAnnotation != null);
            Contract.Requires(annotation != null);
            Contract.Requires(model != null);
            Contract.Requires(complexSerializer != null);
            Contract.Requires(serializerContext != null);

            var complexType = (IEdmComplexType)model.FindDeclaredType(entryAnnotation.AnnotationTypeName);

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

            var typeRef = new EdmComplexTypeReference(complexType, entryAnnotation.IsNullable);

            if (!entryAnnotation.IsCollection)
            {
                return(complexSerializer.CreateODataComplexValue(annotation, typeRef, serializerContext));
            }

            var typeName = Invariant($"Collection({typeRef.FullName()})");
            var items    = GetComplexValues(annotation, complexSerializer, typeRef, serializerContext);

            return(new ODataCollectionValue()
            {
                Items = items, TypeName = typeName
            });
        }
예제 #18
0
        public LocalizedTextDataType(IODataObjectFactory oDataObjectFactory)
        {
            this.oDataObjectFactory                   = oDataObjectFactory;
            this.cultureValueTypeReference            = CreateCultureValueTypeReference();
            this.cultureValuesCollectionTypeReference = CreateCultureValuesCollectionTypeReference(this.cultureValueTypeReference);

            this.edmComplexType = CreateComplexType(this.cultureValuesCollectionTypeReference);
        }
        public void Initialize()
        {
            var addressEdmType = new EdmComplexType("Default", "Address");

            addressEdmType.AddStructuralProperty("ZipCode", EdmPrimitiveTypeKind.String);

            this.edmAddressComplexTypeRef = new EdmComplexTypeReference(addressEdmType, true);
        }
예제 #20
0
        private EdmStructuralProperty?BuildStructuralProperty(Dictionary <Type, EntityTypeInfo> entityTypes,
                                                              Dictionary <Type, EdmEnumType> enumTypes, Dictionary <Type, EdmComplexType> complexTypes, PropertyInfo clrProperty)
        {
            bool isNullable           = !_metadataProvider.IsRequired(clrProperty);
            IEdmTypeReference?typeRef = PrimitiveTypeHelper.GetPrimitiveTypeRef(clrProperty, isNullable);

            if (typeRef == null)
            {
                Type?underlyingType = null;
                if (clrProperty.PropertyType.IsEnum ||
                    (underlyingType = Nullable.GetUnderlyingType(clrProperty.PropertyType)) != null && underlyingType.IsEnum)
                {
                    Type clrPropertyType = underlyingType ?? clrProperty.PropertyType;
                    if (!enumTypes.TryGetValue(clrPropertyType, out EdmEnumType? edmEnumType))
                    {
                        edmEnumType = OeEdmModelBuilder.CreateEdmEnumType(clrPropertyType);
                        enumTypes.Add(clrPropertyType, edmEnumType);
                    }
                    typeRef = new EdmEnumTypeReference(edmEnumType, underlyingType != null);
                }
                else
                {
                    if (complexTypes.TryGetValue(clrProperty.PropertyType, out EdmComplexType? edmComplexType))
                    {
                        typeRef = new EdmComplexTypeReference(edmComplexType, clrProperty.PropertyType.IsClass);
                    }
                    else
                    {
                        FKeyInfo?fkeyInfo = FKeyInfo.Create(_metadataProvider, entityTypes, this, clrProperty);
                        if (fkeyInfo != null)
                        {
                            _navigationClrProperties.Add(fkeyInfo);
                        }
                        return(null);
                    }
                }
            }
            else
            {
                if (clrProperty.PropertyType == typeof(DateTime?) && enumTypes.ContainsKey(typeof(DateTime?)))
                {
                    var edmType = enumTypes[typeof(DateTime?)];
                    typeRef = new EdmEnumTypeReference(edmType, true);
                }
            }

            EdmStructuralProperty edmProperty = clrProperty is Infrastructure.OeShadowPropertyInfo ?
                                                new OeEdmStructuralShadowProperty(EdmType, clrProperty.Name, typeRef, clrProperty) :
                                                new EdmStructuralProperty(EdmType, clrProperty.Name, typeRef);

            EdmType.AddProperty(edmProperty);
            if (_metadataProvider.IsKey(clrProperty))
            {
                _keyProperties.Add(new KeyValuePair <PropertyInfo, EdmStructuralProperty>(clrProperty, edmProperty));
            }

            return(edmProperty);
        }
예제 #21
0
        public void GetEdmType_Returns_EdmTypeInitializedByCtor()
        {
            IEdmTypeReference           elementType    = new EdmComplexTypeReference(new EdmComplexType("NS", "Complex"), isNullable: false);
            IEdmCollectionTypeReference collectionType = new EdmCollectionTypeReference(new EdmCollectionType(elementType));

            var edmObject = new EdmComplexObjectCollection(collectionType);

            Assert.Same(collectionType, edmObject.GetEdmType());
        }
예제 #22
0
        private void VerifyComplexTypeRoundtrip(ODataComplexValue value, string typeName)
        {
            var          typeReference = new EdmComplexTypeReference((IEdmComplexType)model.FindType(typeName), true);
            MemoryStream stream        = new MemoryStream();

            using (ODataAtomOutputContext outputContext = new ODataAtomOutputContext(
                       ODataFormat.Atom,
                       new NonDisposingStream(stream),
                       Encoding.UTF8,
                       new ODataMessageWriterSettings()
            {
                Version = ODataVersion.V4
            },
                       /*writingResponse*/ true,
                       /*synchronous*/ true,
                       model,
                       /*urlResolver*/ null))
            {
                ODataAtomPropertyAndValueSerializer serializer = new ODataAtomPropertyAndValueSerializer(outputContext);
                serializer.XmlWriter.WriteStartElement("ValueElement");
                serializer.WriteComplexValue(
                    value,
                    typeReference,
                    /*isOpenPropertyType*/ false,
                    /*isWritingCollection*/ false,
                    /*beforeValueAction*/ null,
                    /*afterValueAction*/ null,
                    new DuplicatePropertyNamesChecker(false, false),
                    /*collectionValidator*/ null,
                    /*projectedProperties*/ null);
                serializer.XmlWriter.WriteEndElement();
            }

            stream.Position = 0;
            object actualValue;

            using (ODataAtomInputContext inputContext = new ODataAtomInputContext(
                       ODataFormat.Atom,
                       stream,
                       Encoding.UTF8,
                       new ODataMessageReaderSettings(),
                       /*readingResponse*/ true,
                       /*synchronous*/ true,
                       model,
                       /*urlResolver*/ null))
            {
                ODataAtomPropertyAndValueDeserializer deserializer = new ODataAtomPropertyAndValueDeserializer(inputContext);
                deserializer.XmlReader.MoveToContent();
                actualValue = deserializer.ReadNonEntityValue(
                    typeReference,
                    /*duplicatePropertyNamesChecker*/ null,
                    /*collectionValidator*/ null,
                    /*validateNullValue*/ true);
            }

            TestUtils.AssertODataValueAreEqual(actualValue as ODataValue, value);
        }
        public void CreateODataComplexValue_ReturnsNull_ForNullEdmComplexObject()
        {
            IEdmComplexTypeReference   edmType    = new EdmComplexTypeReference(_addressType, isNullable: true);
            ODataComplexTypeSerializer serializer = new ODataComplexTypeSerializer(new DefaultODataSerializerProvider());

            var result = serializer.CreateODataComplexValue(new NullEdmComplexObject(edmType), edmType, new ODataSerializerContext());

            Assert.Null(result);
        }
        public void TryGetValue_ThrowsInvalidOperation_EdmComplexObjectNullRef()
        {
            IEdmComplexTypeReference edmType           = new EdmComplexTypeReference(new EdmComplexType("NS", "ComplexType"), isNullable: true);
            NullEdmComplexObject     nullComplexObject = new NullEdmComplexObject(edmType);
            object propertyValue;

            ExceptionAssert.Throws <InvalidOperationException>(() => nullComplexObject.TryGetPropertyValue("property", out propertyValue),
                                                               "Cannot get property 'property' of a null EDM object of type '[NS.ComplexType Nullable=True]'.");
        }
        public void GetEdmType_Returns_CtorInitializedValue()
        {
            IEdmComplexTypeReference edmType           = new EdmComplexTypeReference(new EdmComplexType("NS", "ComplexType"), isNullable: true);
            NullEdmComplexObject     nullComplexObject = new NullEdmComplexObject(edmType);

            IEdmTypeReference result = nullComplexObject.GetEdmType();

            Assert.Same(edmType, result);
        }
        public void TryGetPropertyValue_ThrowsInvalidOperation()
        {
            // Arrange & Act & Assert
            EdmComplexType           complex = new EdmComplexType("NS", "Complex");
            IEdmComplexTypeReference typeRef = new EdmComplexTypeReference(complex, false);
            NullEdmComplexObject     obj     = new NullEdmComplexObject(typeRef);

            ExceptionAssert.Throws <InvalidOperationException>(() => obj.TryGetPropertyValue("name", out object value),
                                                               "Cannot get property 'name' of a null EDM object of type '[NS.Complex Nullable=False]'.");
        }
예제 #27
0
        public void TypeNameShouldBeWrittenForUndeclaredComplexProperty()
        {
            var typeFromValue = new EdmComplexTypeReference(new EdmComplexType("Test", "ComplexType"), false);

            this.typeNameOracle.GetResourceTypeNameForWriting(null,
                                                              new ODataResource {
                TypeName = "Test.ComplexType"
            },
                                                              /* isUndeclared*/ true).Should().Be("Test.ComplexType");
        }
예제 #28
0
        public void GetDefaultValue_NonNullableComplex()
        {
            IEdmTypeReference nonNullableComplexType = new EdmComplexTypeReference(new EdmComplexType("NS", "Complex"), isNullable: false);

            var result = EdmStructuredObject.GetDefaultValue(nonNullableComplexType);

            var complexObject = Assert.IsType <EdmComplexObject>(result);

            Assert.Equal(nonNullableComplexType, complexObject.GetEdmType(), new EdmTypeReferenceEqualityComparer());
        }
예제 #29
0
        private void BuildProperty(Dictionary <Type, EntityTypeInfo> entityTypes,
                                   Dictionary <Type, EdmEnumType> enumTypes, Dictionary <Type, EdmComplexType> complexTypes, PropertyDescriptor clrProperty)
        {
            IEdmTypeReference typeRef = PrimitiveTypeHelper.GetPrimitiveTypeRef(clrProperty);

            if (typeRef == null)
            {
                EdmEnumType edmEnumType;
                Type        underlyingType = null;
                if (clrProperty.PropertyType.GetTypeInfo().IsEnum ||
                    (underlyingType = Nullable.GetUnderlyingType(clrProperty.PropertyType)) != null && underlyingType.GetTypeInfo().IsEnum)
                {
                    Type clrPropertyType = underlyingType ?? clrProperty.PropertyType;
                    if (!enumTypes.TryGetValue(clrPropertyType, out edmEnumType))
                    {
                        edmEnumType = CreateEdmEnumType(clrPropertyType);
                        enumTypes.Add(clrPropertyType, edmEnumType);
                    }
                    typeRef = new EdmEnumTypeReference(edmEnumType, underlyingType != null);
                }
                else
                {
                    EdmComplexType edmComplexType;
                    if (complexTypes.TryGetValue(clrProperty.PropertyType, out edmComplexType))
                    {
                        typeRef = new EdmComplexTypeReference(edmComplexType, clrProperty.PropertyType.GetTypeInfo().IsClass);
                    }
                    else
                    {
                        FKeyInfo fkeyInfo = FKeyInfo.Create(_metadataProvider, entityTypes, this, clrProperty);
                        if (fkeyInfo != null)
                        {
                            _navigationClrProperties.Add(fkeyInfo);
                        }
                        return;
                    }
                }
            }
            else
            {
                if (clrProperty.PropertyType == typeof(DateTime?) && enumTypes.ContainsKey(typeof(DateTime?))) //zzz
                {
                    var edmType = enumTypes[typeof(DateTime?)];
                    typeRef = new EdmEnumTypeReference(edmType, true);
                }
            }

            var edmProperty = new EdmStructuralProperty(_edmType, clrProperty.Name, typeRef);

            _edmType.AddProperty(edmProperty);
            if (_metadataProvider.IsKey(clrProperty))
            {
                _keyProperties.Add(new KeyValuePair <PropertyDescriptor, EdmStructuralProperty>(clrProperty, edmProperty));
            }
        }
예제 #30
0
        public void GetDefaultValue_NonNullableComplexCollection()
        {
            IEdmTypeReference           elementType           = new EdmComplexTypeReference(new EdmComplexType("NS", "Complex"), isNullable: true);
            IEdmCollectionTypeReference complexCollectionType = new EdmCollectionTypeReference(new EdmCollectionType(elementType));

            var result = EdmStructuredObject.GetDefaultValue(complexCollectionType);

            var complexCollectionObject = Assert.IsType <EdmComplexObjectCollection>(result);

            Assert.Equal(complexCollectionType, complexCollectionObject.GetEdmType(), new EdmTypeReferenceEqualityComparer());
        }