Ejemplo n.º 1
0
        public void TypeDefinitionUnitTest()
        {
            EdmTypeDefinition          typeDef = new EdmTypeDefinition("NS", "Length", EdmPrimitiveTypeKind.Int32);
            EdmTypeDefinitionReference typeRef = new EdmTypeDefinitionReference(typeDef, true);

            typeRef.TypeDefinition().Should().Be(typeDef);
        }
Ejemplo n.º 2
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");
        }
Ejemplo n.º 3
0
        public void TestModelWithTypeDefinition()
        {
            var model = new EdmModel();

            var addressType = new EdmTypeDefinition("MyNS", "Address", EdmPrimitiveTypeKind.String);

            model.AddElement(addressType);

            var weightType = new EdmTypeDefinition("MyNS", "Weight", EdmPrimitiveTypeKind.Decimal);

            model.AddElement(weightType);

            var personType = new EdmEntityType("MyNS", "Person");

            var addressTypeReference = new EdmTypeDefinitionReference(addressType, false);

            personType.AddStructuralProperty("Address", addressTypeReference);
            addressTypeReference.Definition.Should().Be(addressType);
            addressTypeReference.IsNullable.Should().BeFalse();

            var weightTypeReference = new EdmTypeDefinitionReference(weightType, true);

            personType.AddStructuralProperty("Weight", weightTypeReference);
            weightTypeReference.Definition.Should().Be(weightType);
            weightTypeReference.IsNullable.Should().BeTrue();

            var personId = personType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);

            personType.AddKeys(personId);
        }
Ejemplo n.º 4
0
        public void CreateCollectionWriterWithTypeDefinitionAsItemType()
        {
            var writer            = new ODataMessageWriter(new DummyRequestMessage());
            var entityElementType = new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "Test", EdmPrimitiveTypeKind.Int32), false);
            var collectionWriter  = writer.CreateODataCollectionWriter(entityElementType);

            Assert.True(collectionWriter != null, "CreateODataCollectionWriter with type definition item type failed.");
        }
Ejemplo n.º 5
0
        public void PassNullModelToGetPrimitiveValueConverterShouldFail()
        {
            EdmModel model         = null;
            var      typeReference = new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "Test", EdmPrimitiveTypeKind.Int32), true);
            Action   getConverter  = () => model.GetPrimitiveValueConverter(typeReference);

            getConverter.ShouldThrow <ArgumentNullException>();
        }
Ejemplo n.º 6
0
        public void PassNullConverterToSetPrimitiveValueConverterShouldFail()
        {
            var    model         = new EdmModel();
            var    typeReference = new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "Test", EdmPrimitiveTypeKind.Int32), true);
            Action setConverter  = () => model.SetPrimitiveValueConverter(typeReference, null);

            setConverter.ShouldThrow <ArgumentNullException>();
        }
Ejemplo n.º 7
0
        public void SetAndGetPrimitiveValueConverterShouldWork()
        {
            var model         = new EdmModel();
            var typeReference = new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "Test", EdmPrimitiveTypeKind.Int32), true);
            var converter     = new TestPrimitiveValueConverter();

            model.SetPrimitiveValueConverter(typeReference, converter);
            Assert.AreEqual(model.GetPrimitiveValueConverter(typeReference), converter);
        }
        private void VerifyUIntValuesRoundtripWithTypeInformation(IEnumerable clrValues, string edmTypeDefinitionName)
        {
            var typeReference = new EdmTypeDefinitionReference((IEdmTypeDefinition)this.model.FindType(edmTypeDefinitionName), true);

            foreach (object clrValue in clrValues)
            {
                this.VerifyPrimitiveValueRoundtrips(clrValue, typeReference, ODataVersion.V4, string.Format("JSON Light roundtrip value {0} of type {1}.", clrValue, edmTypeDefinitionName), isIeee754Compatible: true);
            }
        }
Ejemplo n.º 9
0
        public void Convert_CheckTypeDefinitionPrimitives(object odataValue, EdmPrimitiveTypeKind edmTypeKind, Type clrType, object expectedResult)
        {
            var edmTypeDefinition   = new EdmTypeDefinition(clrType.Namespace, clrType.Name, edmTypeKind);
            var edmTypeDefReference = new EdmTypeDefinitionReference(edmTypeDefinition, false);

            var result = ODataModelBinderConverter.Convert(odataValue, edmTypeDefReference, clrType, "IsActive", null, null);

            Assert.NotNull(result);
            Assert.IsType(clrType, result);
            Assert.Equal(expectedResult, result);
        }
Ejemplo n.º 10
0
        private void VerifyUIntValuesRoundtripWithTypeInformation(IEnumerable clrValues, string edmTypeDefinitionName)
        {
            var typeReference = new EdmTypeDefinitionReference((IEdmTypeDefinition)this.model.FindType(edmTypeDefinitionName), true);

            foreach (ODataVersion version in new ODataVersion[] { ODataVersion.V4, ODataVersion.V401 })
            {
                foreach (object clrValue in clrValues)
                {
                    this.VerifyPrimitiveValueRoundtrips(clrValue, typeReference, version, isIeee754Compatible: true);
                }
            }
        }
Ejemplo n.º 11
0
        public static IEdmModel GetEdmModel()
        {
            var builder  = new ODataConventionModelBuilder();
            var customer = builder.EntitySet <Customer>("Customers").EntityType;

            var type = builder.AddEntityType(typeof(Customer));

            IList <PropertyInfo> removedProperties = new List <PropertyInfo>();

            foreach (var propertyInfo in typeof(Customer).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
            {
                if (propertyInfo.PropertyType == typeof(DateTime) ||
                    propertyInfo.PropertyType == typeof(DateTime?)) // add more codes to process collection
                {
                    type.RemoveProperty(propertyInfo);
                    removedProperties.Add(propertyInfo);
                }
            }
            // customer.Ignore(c => c.ReleaseDate);

            EdmModel model = builder.GetEdmModel() as EdmModel;

            EdmEntityType customerType  = model.SchemaElements.OfType <IEdmEntityType>().First(c => c.Name == "Customer") as EdmEntityType;
            var           localDateTime = model.FindType("Org.OData.Core.V1.LocalDateTime") as IEdmTypeDefinition;

            var localDateTimeNullableRef    = new EdmTypeDefinitionReference(localDateTime, true);
            var localDateTimenonNullableRef = new EdmTypeDefinitionReference(localDateTime, false);

            foreach (var propertyInfo in removedProperties)
            {
                EdmProperty edmProperty = null;
                if (propertyInfo.PropertyType == typeof(DateTime))
                {
                    edmProperty = customerType.AddStructuralProperty(propertyInfo.Name, localDateTimenonNullableRef);
                }
                else if (propertyInfo.PropertyType == typeof(DateTime?))
                {
                    edmProperty = customerType.AddStructuralProperty(propertyInfo.Name, localDateTimeNullableRef);
                }

                if (edmProperty != null)
                {
                    model.SetAnnotationValue(edmProperty, new ClrPropertyInfoAnnotation(propertyInfo));
                }
            }

            LocalDateTimeConverter converter = new LocalDateTimeConverter();

            model.SetPrimitiveValueConverter(localDateTimeNullableRef, converter);
            model.SetPrimitiveValueConverter(localDateTimenonNullableRef, converter);

            return(model);
        }
Ejemplo n.º 12
0
        public void GetClrTypeNameShouldReturnUnderlyingTypeForTypeDefinition(EdmPrimitiveTypeKind primitiveTypeKind, bool isReferenceType)
        {
            var underlyingType                  = new EdmPrimitiveType(primitiveTypeKind);
            var typeDefinition                  = new EdmTypeDefinition("namespace", "Field", underlyingType);
            var typeDefinitionReference         = new EdmTypeDefinitionReference(typeDefinition, false);
            var nullableTypeDefinitionReference = new EdmTypeDefinitionReference(typeDefinition, true);

            var underlyingTypeName = ODataT4CodeGenerator.Utils.GetClrTypeName(underlyingType, template);
            var nullableName       = isReferenceType ? underlyingTypeName : $"global::System.Nullable<{underlyingTypeName}>";

            ODataT4CodeGenerator.Utils.GetClrTypeName(typeDefinitionReference, false, template, context).Should().Be(underlyingTypeName);
            ODataT4CodeGenerator.Utils.GetClrTypeName(nullableTypeDefinitionReference, false, template, context).Should().Be(nullableName);
        }
        public void ParameterReaderShouldReadTypeDefinitionValueAndTypeDefinitionCollection()
        {
            var nameType = new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "NameType", EdmPrimitiveTypeKind.String), false);

            this.action.AddParameter("name", nameType);
            this.action.AddParameter("hobbies", EdmCoreModel.GetCollection(nameType));

            string payload = "{\"name\" : \"john\", \"hobbies\": [\"football\", \"basketball\"]}";

            var result = this.RunParameterReaderTest(payload);

            result.Values.Should().HaveCount(1);
            result.Collections.Should().HaveCount(1);
        }
Ejemplo n.º 14
0
        public void UInt64RoundtripJsonLightTest()
        {
            var uint64    = new EdmTypeDefinition("NS", "UInt64", EdmPrimitiveTypeKind.String);
            var uint64Ref = new EdmTypeDefinitionReference(uint64, true);

            this.model.AddElement(uint64);
            this.model.SetPrimitiveValueConverter(uint64Ref, UInt64ValueConverter.Instance);
            var values = new[]
            {
                (UInt64)456,
                UInt64.MinValue,
                UInt64.MaxValue
            };

            this.VerifyUIntValuesRoundtripWithTypeInformation(values, "NS.UInt64");
        }
Ejemplo n.º 15
0
        public void UInt16RoundtripJsonLightTest()
        {
            var uint16    = new EdmTypeDefinition("NS", "UInt16", EdmPrimitiveTypeKind.Double);
            var uint16Ref = new EdmTypeDefinitionReference(uint16, true);

            this.model.AddElement(uint16);
            this.model.SetPrimitiveValueConverter(uint16Ref, UInt16ValueConverter.Instance);
            var values = new[]
            {
                (UInt16)123,
                UInt16.MinValue,
                UInt16.MaxValue
            };

            this.VerifyUIntValuesRoundtripWithTypeInformation(values, "NS.UInt16");
        }
        public void ReadingTypeDefinitionPayloadWithIncompatibleTypeDefinitionShouldFail()
        {
            EdmModel model = new EdmModel();

            EdmEntityType entityType = new EdmEntityType("NS", "Person");

            entityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);

            EdmTypeDefinition          weightType    = new EdmTypeDefinition("NS", "Weight", EdmPrimitiveTypeKind.Int32);
            EdmTypeDefinitionReference weightTypeRef = new EdmTypeDefinitionReference(weightType, false);

            entityType.AddStructuralProperty("Weight", weightTypeRef);

            EdmTypeDefinition heightType = new EdmTypeDefinition("NS", "Height", EdmPrimitiveTypeKind.Double);

            model.AddElement(weightType);
            model.AddElement(heightType);
            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," +
                "\"[email protected]\":\"#NS.Weight\"," +
                "\"Height\":180" +
                "}";

            Action read = () => this.ReadEntryPayload(model, payload, entitySet, entityType, reader => { });

            read.ShouldThrow <ODataException>().WithMessage(Strings.ValidationUtils_IncompatibleType("NS.Height", "NS.Weight"));
        }
        public void WriteTypeDefinitionPayloadWithIncompatibleTypeShouldFail()
        {
            EdmModel model = new EdmModel();

            EdmEntityType entityType = new EdmEntityType("NS", "Person");

            entityType.AddKeys(entityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));

            EdmTypeDefinition          weightType    = new EdmTypeDefinition("NS", "Weight", EdmPrimitiveTypeKind.Double);
            EdmTypeDefinitionReference weightTypeRef = new EdmTypeDefinitionReference(weightType, false);

            entityType.AddStructuralProperty("Weight", weightTypeRef);

            model.AddElement(weightType);
            model.AddElement(entityType);

            EdmEntityContainer container = new EdmEntityContainer("EntityNs", "MyContainer");
            EdmEntitySet       entitySet = container.AddEntitySet("People", entityType);

            model.AddElement(container);

            ODataResource entry = new ODataResource()
            {
                TypeName   = "NS.Person",
                Properties = new[]
                {
                    new ODataProperty {
                        Name = "Id", Value = 1
                    },
                    new ODataProperty {
                        Name = "Weight", Value = "abc"
                    },
                }
            };

            Action write = () => this.WriterEntry(model, entry, entitySet, entityType);

            write.Throws <ODataException>(Strings.ValidationUtils_IncompatiblePrimitiveItemType("Edm.String", "True", "NS.Weight", "False"));
        }
Ejemplo n.º 18
0
        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.CreateODataResourceWriter(peopleSet);

            var entry = new ODataResource
            {
                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();

            Assert.Equal("{\"@odata.context\":\"http://host/service/$metadata#People/$entity\",\"ID\":\"18446744073709551615\",\"Name\":\"Foo\",\"FavoriteNumber\":250.0,\"Age\":123,\"Guid\":-9223372036854775808,\"Weight\":123.45,\"Money\":79228162514264337593543950335}", payload);

#if NETCOREAPP1_1
            stream = new MemoryStream(Encoding.GetEncoding(0).GetBytes(payload));
#else
            stream = new MemoryStream(Encoding.Default.GetBytes(payload));
#endif
            message = new InMemoryMessage {
                Stream = stream
            };
            message.StatusCode = 200;

            var readerSettings = new ODataMessageReaderSettings();

            var messageReader = new ODataMessageReader(message, readerSettings, model);
            var entryReader   = messageReader.CreateODataResourceReader(peopleSet, personType);
            Assert.True(entryReader.Read());
            var entryReaded = entryReader.Item as ODataResource;

            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 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\"}" +
                "}";

            List <ODataResource>    entries        = new List <ODataResource>();
            ODataNestedResourceInfo navigationLink = null;

            this.ReadEntryPayload(model, payload, entitySet, entityType,
                                  reader =>
            {
                switch (reader.State)
                {
                case ODataReaderState.ResourceStart:
                    entries.Add(reader.Item as ODataResource);
                    break;

                case ODataReaderState.NestedResourceInfoStart:
                    navigationLink = (ODataNestedResourceInfo)reader.Item;
                    break;

                default:
                    break;
                }
            });

            Assert.Equal(2, entries.Count);

            IList <ODataProperty> propertyList = entries[0].Properties.ToList();

            propertyList[1].Name.Should().Be("Weight");
            propertyList[1].Value.Should().Be(60.5);

            navigationLink.Name.Should().Be("Address");
            var address = entries[1];

            address.Properties.FirstOrDefault(s => string.Equals(s.Name, "CountryRegion", StringComparison.OrdinalIgnoreCase)).Value.Should().Be("China");
        }
Ejemplo n.º 20
0
        public ODataJsonLightPropertySerializerTests()
        {
            // Initialize open EntityType: EntityType.
            EdmModel edmModel = new EdmModel();

            myInt32 = new EdmTypeDefinition("TestNamespace", "MyInt32", EdmPrimitiveTypeKind.Int32);
            EdmTypeDefinitionReference myInt32Reference = new EdmTypeDefinitionReference(myInt32, true);

            edmModel.AddElement(myInt32);

            myString = new EdmTypeDefinition("TestNamespace", "MyString", EdmPrimitiveTypeKind.String);
            EdmTypeDefinitionReference myStringReference = new EdmTypeDefinitionReference(myString, true);

            edmModel.AddElement(myString);

            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("MyInt32Property", myInt32Reference);
            edmEntityType.AddStructuralProperty("MyStringProperty", myStringReference);
            edmEntityType.AddStructuralProperty("TimeOfDayProperty", EdmPrimitiveTypeKind.TimeOfDay);
            edmEntityType.AddStructuralProperty("DateProperty", EdmPrimitiveTypeKind.Date);

            edmModel.AddElement(edmEntityType);

            // 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.openAddressType);

            this.model            = TestUtils.WrapReferencedModelsToMainModel(edmModel);
            this.entityType       = edmEntityType;
            this.declaredProperty = new ODataProperty {
                Name = "DeclaredProperty", Value = Guid.Empty
            };
            this.undeclaredProperty = new ODataProperty {
                Name = "UndeclaredProperty", Value = DateTimeOffset.MinValue
            };
            this.declaredGeometryProperty = new ODataProperty {
                Name = "DeclaredGeometryProperty", Value = GeometryPoint.Create(0.0, 0.0)
            };
            this.declaredPropertyTimeOfDay = new ODataProperty {
                Name = "TimeOfDayProperty", Value = new TimeOfDay(1, 30, 5, 123)
            };
            this.declaredPropertyDate = new ODataProperty {
                Name = "DateProperty", Value = new Date(2014, 9, 17)
            };

            this.declaredPropertyCountryRegion = new ODataProperty()
            {
                Name = "CountryRegion", Value = "China"
            };
            this.declaredPropertyCountryRegionWithInstanceAnnotation = new ODataProperty()
            {
                Name  = "CountryRegion",
                Value = "China",
                InstanceAnnotations = new Collection <ODataInstanceAnnotation>
                {
                    new ODataInstanceAnnotation("Is.ReadOnly", new ODataPrimitiveValue(true))
                }
            };
            this.undeclaredPropertyCity = new ODataProperty()
            {
                Name = "City", Value = "Shanghai"
            };

            this.declaredPropertyMyInt32 = new ODataProperty()
            {
                Name = "MyInt32Property", Value = 12345
            };
            this.declaredPropertyMyInt32WithInstanceAnnotations = new ODataProperty()
            {
                Name  = "MyInt32Property",
                Value = 12345,
                InstanceAnnotations = new Collection <ODataInstanceAnnotation>
                {
                    new ODataInstanceAnnotation("Is.AutoComputable", new ODataPrimitiveValue(true)),
                    new ODataInstanceAnnotation("Is.ReadOnly", new ODataPrimitiveValue(false))
                }
            };
            this.declaredPropertyMyString = new ODataProperty()
            {
                Name = "MyStringProperty", Value = "abcde"
            };
        }
        public void WriteTypeDefinitionPayloadShouldWork()
        {
            EdmModel model = new EdmModel();

            EdmEntityType entityType = new EdmEntityType("NS", "Person");

            entityType.AddKeys(entityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));

            EdmTypeDefinition          weightType    = new EdmTypeDefinition("NS", "Weight", EdmPrimitiveTypeKind.Double);
            EdmTypeDefinitionReference weightTypeRef = new EdmTypeDefinitionReference(weightType, false);

            entityType.AddStructuralProperty("Weight", weightTypeRef);

            EdmComplexType          complexType    = new EdmComplexType("NS", "Address");
            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(addressType);
            model.AddElement(complexType);
            model.AddElement(entityType);

            EdmEntityContainer container = new EdmEntityContainer("EntityNs", "MyContainer");
            EdmEntitySet       entitySet = container.AddEntitySet("People", entityType);

            model.AddElement(container);

            ODataEntry entry = new ODataEntry()
            {
                TypeName   = "NS.Person",
                Properties = new[]
                {
                    new ODataProperty {
                        Name = "Id", Value = 1
                    },
                    new ODataProperty {
                        Name = "Weight", Value = 60.5
                    },
                    new ODataProperty
                    {
                        Name  = "Address",
                        Value = new ODataComplexValue
                        {
                            Properties = new[]
                            {
                                new ODataProperty {
                                    Name = "CountryRegion", Value = "China"
                                }
                            }
                        }
                    }
                }
            };

            string outputPayload = this.WriterEntry(model, entry, entitySet, entityType);

            const string expectedMinimalPayload =
                "{" +
                "\"@odata.context\":\"http://www.example.com/$metadata#People/$entity\"," +
                "\"Id\":1," +
                "\"Weight\":60.5," +
                "\"Address\":{\"CountryRegion\":\"China\"}" +
                "}";

            outputPayload.Should().Be(expectedMinimalPayload);

            outputPayload = this.WriterEntry(model, entry, entitySet, entityType, true);

            const string expectedFullPayload =
                "{" +
                "\"@odata.context\":\"http://www.example.com/$metadata#People/$entity\"," +
                "\"@odata.type\":\"#NS.Person\"," +
                "\"@odata.id\":\"People(1)\"," +
                "\"@odata.editLink\":\"People(1)\"," +
                "\"Id\":1," +
                "\"Weight\":60.5," +
                "\"Address\":{\"CountryRegion\":\"China\"}" +
                "}";

            outputPayload.Should().Be(expectedFullPayload);
        }
Ejemplo n.º 22
0
        public ODataJsonLightPropertySerializerTests()
        {
            // Initialize open EntityType: EntityType.
            EdmModel edmModel = new EdmModel();

            myInt32 = new EdmTypeDefinition("TestNamespace", "MyInt32", EdmPrimitiveTypeKind.Int32);
            EdmTypeDefinitionReference myInt32Reference = new EdmTypeDefinitionReference(myInt32, true);

            edmModel.AddElement(myInt32);

            myString = new EdmTypeDefinition("TestNamespace", "MyString", EdmPrimitiveTypeKind.String);
            EdmTypeDefinitionReference myStringReference = new EdmTypeDefinitionReference(myString, true);

            edmModel.AddElement(myString);

            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("MyInt32Property", myInt32Reference);
            edmEntityType.AddStructuralProperty("MyStringProperty", myStringReference);
            edmEntityType.AddStructuralProperty("TimeOfDayProperty", EdmPrimitiveTypeKind.TimeOfDay);
            edmEntityType.AddStructuralProperty("DateProperty", EdmPrimitiveTypeKind.Date);
            edmEntityType.AddStructuralProperty("PrimitiveProperty", EdmPrimitiveTypeKind.PrimitiveType);

            // add derived type constraint property.
            var derivedTypeConstrictionProperty = edmEntityType.AddStructuralProperty("PrimitiveConstraintProperty", EdmPrimitiveTypeKind.PrimitiveType);
            var term = ValidationVocabularyModel.DerivedTypeConstraintTerm;
            IEdmStringConstantExpression stringConstant1 = new EdmStringConstant("Edm.Int32");
            IEdmStringConstantExpression stringConstant2 = new EdmStringConstant("Edm.Boolean");
            var collectionExpression = new EdmCollectionExpression(new[] { stringConstant1, stringConstant2 });
            EdmVocabularyAnnotation valueAnnotationOnProperty = new EdmVocabularyAnnotation(derivedTypeConstrictionProperty, term, collectionExpression);

            valueAnnotationOnProperty.SetSerializationLocation(edmModel, EdmVocabularyAnnotationSerializationLocation.Inline);
            edmModel.AddVocabularyAnnotation(valueAnnotationOnProperty);

            edmModel.AddElement(edmEntityType);

            // Initialize ComplexType: Address, HomeAddress, and OpenAddress
            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);

            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.model            = TestUtils.WrapReferencedModelsToMainModel(edmModel);
            this.entityType       = edmEntityType;
            this.declaredProperty = new ODataProperty {
                Name = "DeclaredProperty", Value = Guid.Empty
            };
            this.undeclaredProperty = new ODataProperty {
                Name = "UndeclaredProperty", Value = DateTimeOffset.MinValue
            };
            this.declaredGeometryProperty = new ODataProperty {
                Name = "DeclaredGeometryProperty", Value = GeometryPoint.Create(0.0, 0.0)
            };
            this.declaredPropertyTimeOfDay = new ODataProperty {
                Name = "TimeOfDayProperty", Value = new TimeOfDay(1, 30, 5, 123)
            };
            this.declaredPropertyDate = new ODataProperty {
                Name = "DateProperty", Value = new Date(2014, 9, 17)
            };

            this.declaredPropertyAddress = new ODataProperty()
            {
                Name  = "AddressProperty",
                Value = new ODataResourceValue
                {
                    TypeName   = "TestNamespace.Address",
                    Properties = new ODataProperty[] { new ODataProperty {
                                                           Name = "City", Value = "Shanghai"
                                                       } }
                }
            };
            this.declaredPropertyHomeAddress = new ODataProperty()
            {
                Name  = "HomeAddressProperty",
                Value = new ODataResourceValue
                {
                    TypeName   = "TestNamespace.HomeAddress",
                    Properties = new ODataProperty[]
                    {
                        new ODataProperty {
                            Name = "FamilyName", Value = "Green"
                        },
                        new ODataProperty {
                            Name = "City", Value = "Shanghai"
                        }
                    }
                }
            };
            this.declaredPropertyAddressWithInstanceAnnotation = new ODataProperty()
            {
                Name  = "AddressProperty",
                Value = new ODataResourceValue
                {
                    TypeName   = "TestNamespace.Address",
                    Properties = new ODataProperty[]
                    {
                        new ODataProperty {
                            Name = "City", Value = "Shanghai"
                        }
                    },
                    InstanceAnnotations = new Collection <ODataInstanceAnnotation>
                    {
                        new ODataInstanceAnnotation("Is.ReadOnly", new ODataPrimitiveValue(true))
                    }
                }
            };
            this.declaredPropertyHomeAddressWithInstanceAnnotations = new ODataProperty()
            {
                Name  = "HomeAddressProperty",
                Value = new ODataResourceValue
                {
                    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))
                    }
                }
            };

            this.declaredPropertyCountryRegion = new ODataProperty()
            {
                Name = "CountryRegion", Value = "China"
            };
            this.declaredPropertyCountryRegionWithInstanceAnnotation = new ODataProperty()
            {
                Name  = "CountryRegion",
                Value = "China",
                InstanceAnnotations = new Collection <ODataInstanceAnnotation>
                {
                    new ODataInstanceAnnotation("Is.ReadOnly", new ODataPrimitiveValue(true))
                }
            };
            this.undeclaredPropertyCity = new ODataProperty()
            {
                Name = "City", Value = "Shanghai"
            };

            this.declaredPropertyMyInt32 = new ODataProperty()
            {
                Name = "MyInt32Property", Value = 12345
            };
            this.declaredPropertyMyInt32WithInstanceAnnotations = new ODataProperty()
            {
                Name  = "MyInt32Property",
                Value = 12345,
                InstanceAnnotations = new Collection <ODataInstanceAnnotation>
                {
                    new ODataInstanceAnnotation("Is.AutoComputable", new ODataPrimitiveValue(true)),
                    new ODataInstanceAnnotation("Is.ReadOnly", new ODataPrimitiveValue(false))
                }
            };
            this.declaredPropertyMyString = new ODataProperty()
            {
                Name = "MyStringProperty", Value = "abcde"
            };
        }
        public void WriteTypeDefinitionAsKeyPayloadShouldWork()
        {
            EdmModel model = new EdmModel();

            EdmTypeDefinition          uint32Type      = new EdmTypeDefinition("NS", "UInt32", EdmPrimitiveTypeKind.String);
            EdmTypeDefinitionReference uint32Reference = new EdmTypeDefinitionReference(uint32Type, false);

            model.AddElement(uint32Type);

            EdmEntityType entityType = new EdmEntityType("NS", "Person");

            entityType.AddKeys(entityType.AddStructuralProperty("Id1", uint32Reference), entityType.AddStructuralProperty("Id2", EdmPrimitiveTypeKind.Int32));
            model.SetPrimitiveValueConverter(uint32Reference, new MyUInt32Converter());

            EdmTypeDefinition          weightType    = new EdmTypeDefinition("NS", "Weight", EdmPrimitiveTypeKind.Double);
            EdmTypeDefinitionReference weightTypeRef = new EdmTypeDefinitionReference(weightType, false);

            entityType.AddStructuralProperty("Weight", weightTypeRef);

            EdmComplexType          complexType    = new EdmComplexType("NS", "Address");
            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(addressType);
            model.AddElement(complexType);
            model.AddElement(entityType);

            EdmEntityContainer container = new EdmEntityContainer("EntityNs", "MyContainer");
            EdmEntitySet       entitySet = container.AddEntitySet("People", entityType);

            model.AddElement(container);

            ODataResource entry = new ODataResource()
            {
                TypeName   = "NS.Person",
                Properties = new[]
                {
                    new ODataProperty {
                        Name = "Id1", Value = (UInt32)1
                    },
                    new ODataProperty {
                        Name = "Id2", Value = 2
                    },
                    new ODataProperty {
                        Name = "Weight", Value = 60.5
                    },
                }
            };

            ODataNestedResourceInfo address = new ODataNestedResourceInfo()
            {
                Name         = "Address",
                IsCollection = false
            };

            ODataResource addressResource = new ODataResource
            {
                Properties = new[]
                {
                    new ODataProperty {
                        Name = "CountryRegion", Value = "China"
                    }
                }
            };

            string outputPayload = this.WriterEntry(model, entry, entitySet, entityType, false, (writer)
                                                    =>
            {
                writer.WriteStart(entry);
                writer.WriteStart(address);
                writer.WriteStart(addressResource);
                writer.WriteEnd();
                writer.WriteEnd();
                writer.WriteEnd();
            });

            const string expectedMinimalPayload =
                "{" +
                "\"@odata.context\":\"http://www.example.com/$metadata#People/$entity\"," +
                "\"Id1\":\"1\"," +
                "\"Id2\":2," +
                "\"Weight\":60.5," +
                "\"Address\":{\"CountryRegion\":\"China\"}" +
                "}";

            Assert.Equal(expectedMinimalPayload, outputPayload);

            outputPayload = this.WriterEntry(model, entry, entitySet, entityType, true, (writer)
                                             =>
            {
                writer.WriteStart(entry);
                writer.WriteStart(address);
                writer.WriteStart(addressResource);
                writer.WriteEnd();
                writer.WriteEnd();
                writer.WriteEnd();
            });

            const string expectedFullPayload =
                "{" +
                "\"@odata.context\":\"http://www.example.com/$metadata#People/$entity\"," +
                "\"@odata.type\":\"#NS.Person\"," +
                "\"@odata.id\":\"People(Id1='1',Id2=2)\"," +
                "\"@odata.editLink\":\"People(Id1='1',Id2=2)\"," +
                "\"Id1\":\"1\"," +
                "\"Id2\":2," +
                "\"Weight\":60.5," +
                "\"Address\":{\"CountryRegion\":\"China\"}" +
                "}";

            Assert.Equal(expectedFullPayload, outputPayload);
        }