Ejemplo n.º 1
0
        public void ReadingPayloadInt64SingleDoubleDecimalWithoutSuffix()
        {
            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);

            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))));
            model.AddElement(entityType);

            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://MyTestEntity\"," +
                "\"LongId\":\"12\"," +
                "\"FloatId\":34.98," +
                "\"DoubleId\":56.01," +
                "\"DecimalId\":\"78.62\"," +
                "\"LongNumbers\":[\"-1\",\"-9223372036854775808\",\"9223372036854775807\"]," +
                "\"FloatNumbers\":[-1,-3.40282347E+38,3.40282347E+38,\"INF\",\"-INF\",\"NaN\"]," +
                "\"DoubleNumbers\":[1.0,-1.7976931348623157E+308,1.7976931348623157E+308,\"INF\",\"-INF\",\"NaN\"]," +
                "\"DecimalNumbers\":[\"0\",\"-79228162514264337593543950335\",\"79228162514264337593543950335\"]," +
                "\"ComplexProperty\":{\"CLongId\":\"1\",\"CFloatId\":1,\"CDoubleId\":-1.0,\"CDecimalId\":\"0.0\"}" +
                "}";

            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);
            entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "LongId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(12L, "value should be in correct type.");
            entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "FloatId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(34.98f, "value should be in correct type.");
            entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "DoubleId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(56.01d, "value should be in correct type.");
            entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "DecimalId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(78.62m, "value should be in correct type.");

            var complextProperty = entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "ComplexProperty", StringComparison.OrdinalIgnoreCase)).Value as ODataComplexValue;

            complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CLongId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(1L, "value should be in correct type.");
            complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CFloatId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(1.0F, "value should be in correct type.");
            complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CDoubleId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(-1.0D, "value should be in correct type.");
            complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CDecimalId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(0.0M, "value should be in correct type.");

            var longCollection = entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "LongNumbers", StringComparison.OrdinalIgnoreCase)).Value.As <ODataCollectionValue>();

            longCollection.Items.Should().Contain(-1L).And.Contain(long.MinValue).And.Contain(long.MaxValue);
            var floatCollection = entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "FloatNumbers", StringComparison.OrdinalIgnoreCase)).Value.As <ODataCollectionValue>();

            floatCollection.Items.Should().Contain(-1F).And.Contain(float.MinValue).And.Contain(float.MaxValue).And.Contain(float.PositiveInfinity).And.Contain(float.NegativeInfinity).And.Contain(float.NaN);
            var doubleCollection = entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "DoubleNumbers", StringComparison.OrdinalIgnoreCase)).Value.As <ODataCollectionValue>();

            doubleCollection.Items.Should().Contain(1.0D).And.Contain(double.MinValue).And.Contain(double.MaxValue).And.Contain(double.PositiveInfinity).And.Contain(double.NegativeInfinity).And.Contain(double.NaN);
            var decimalCollection = entry.Properties.FirstOrDefault(s => string.Equals(s.Name, "DecimalNumbers", StringComparison.OrdinalIgnoreCase)).Value.As <ODataCollectionValue>();

            decimalCollection.Items.Should().Contain(0M).And.Contain(decimal.MinValue).And.Contain(decimal.MaxValue);
        }
        public void ComplexValueTest()
        {
            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 = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_DuplicateAnnotationNotAllowed", "custom.annotation")
                },
            };

            var payloads = new[]
            {
                new
                {
                    Json          = "{{{0}}}",
                    ExpectedValue = (ComplexInstance)PayloadBuilder.ComplexValue("TestModel.ComplexType")
                },
                new
                {
                    Json          = "{{{0}{1} \"Name\": \"Value\"}}",
                    ExpectedValue = (ComplexInstance)PayloadBuilder.ComplexValue("TestModel.ComplexType")
                                    .PrimitiveProperty("Name", "Value")
                },
                new
                {
                    Json          = "{{\"Name\": \"Value\"{1}{0}}}",
                    ExpectedValue = (ComplexInstance)PayloadBuilder.ComplexValue("TestModel.ComplexType")
                                    .PrimitiveProperty("Name", "Value")
                },
                new
                {
                    Json          = "{{\"Name\":\"Value\",{0}{1}\"City\":\"Redmond\"}}",
                    ExpectedValue = (ComplexInstance)PayloadBuilder.ComplexValue("TestModel.ComplexType")
                                    .PrimitiveProperty("Name", "Value")
                                    .PrimitiveProperty("City", "Redmond")
                },
            };

            EdmModel model = new EdmModel();

            var addressType = new EdmComplexType("TestModel", "Address");

            addressType.AddStructuralProperty("Street", EdmCoreModel.Instance.GetString(isNullable: false));

            var complexType = new EdmComplexType("TestModel", "ComplexType");

            complexType.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(isNullable: false));
            complexType.AddStructuralProperty("City", EdmCoreModel.Instance.GetString(isNullable: false));
            complexType.AddStructuralProperty("Address", new EdmComplexTypeReference(addressType, isNullable: false));
            complexType.AddStructuralProperty("Location", EdmPrimitiveTypeKind.GeographyPoint);

            var owningType = new EdmEntityType("TestModel", "OwningType");

            owningType.AddKeys(owningType.AddStructuralProperty("ID", EdmCoreModel.Instance.GetInt32(isNullable: false)));
            owningType.AddStructuralProperty("TopLevelProperty", new EdmComplexTypeReference(complexType, isNullable: true));
            model.AddElement(owningType);
            model.AddElement(addressType);
            model.AddElement(complexType);

            var container = new EdmEntityContainer("TestModel", "DefaultContainer");

            container.AddEntitySet("OwningType", owningType);
            model.AddElement(container);

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = payloads.SelectMany(payload => injectedProperties.Select(injectedProperty =>
            {
                return(new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Property("TopLevelProperty", payload.ExpectedValue.DeepCopy()
                                                             .JsonRepresentation(string.Format(payload.Json, injectedProperty.InjectedJSON, string.IsNullOrEmpty(injectedProperty.InjectedJSON) ? string.Empty : ","))
                                                             // JSON Light payloads don't store complex type names since the type can be inferred from the context URI and or API.
                                                             .SetAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    }))
                                     .ExpectedProperty(owningType, "TopLevelProperty"),
                    PayloadEdmModel = model,
                    ExpectedException = injectedProperty.ExpectedException,
                    ExpectedResultPayloadElement = tc => tc.IsRequest
                        ? PayloadBuilder.Property(string.Empty, payload.ExpectedValue.DeepCopy()
                                                  .SetAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    }))
                        : PayloadBuilder.Property("TopLevelProperty", payload.ExpectedValue.DeepCopy()
                                                  .SetAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    }))
                });
            }));

            var explicitPayloads = new[]
            {
                new
                {
                    Description       = "Primitive value as complex - should fail.",
                    Json              = "42",
                    ExpectedPayload   = PayloadBuilder.ComplexValue("TestModel.ComplexType"),
                    ExpectedException = ODataExpectedExceptions.ODataException("JsonReaderExtensions_UnexpectedNodeDetected", "StartObject", "PrimitiveValue")
                },
                new
                {
                    Description       = "Array value as complex - should fail.",
                    Json              = "[]",
                    ExpectedPayload   = PayloadBuilder.ComplexValue("TestModel.ComplexType"),
                    ExpectedException = ODataExpectedExceptions.ODataException("JsonReaderExtensions_UnexpectedNodeDetected", "StartObject", "StartArray")
                },
                new
                {
                    Description = "Type annotation preceded by custom annotation - should fail",
                    Json        = "{" +
                                  "\"@custom.annotation\": null," +
                                  "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\": \"TestModel.ComplexType\"," +
                                  "\"Name\": \"Value\"" +
                                  "}",
                    ExpectedPayload   = PayloadBuilder.ComplexValue("TestModel.ComplexType"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_ComplexTypeAnnotationNotFirst")
                },
                new
                {
                    Description = "Custom property annotation - should be ignored.",
                    Json        = "{" +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("Name", "custom.annotation") + "\": null," +
                                  "\"Name\": \"Value\"" +
                                  "}",
                    ExpectedPayload = PayloadBuilder.ComplexValue("TestModel.ComplexType")
                                      .PrimitiveProperty("Name", "Value"),
                    ExpectedException = (ExpectedException)null
                },
                new
                {
                    Description = "Duplicate custom property annotation - should fail.",
                    Json        = "{" +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("Name", "custom.annotation") + "\": null," +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("Name", "custom.annotation") + "\": 42," +
                                  "\"Name\": \"Value\"" +
                                  "}",
                    ExpectedPayload   = PayloadBuilder.ComplexValue("TestModel.ComplexType"),
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_DuplicateAnnotationForPropertyNotAllowed", "custom.annotation", "Name")
                },
                new
                {
                    Description = "Unrecognized odata property annotation - should fail.",
                    Json        = "{" +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("Name", JsonLightConstants.ODataAnnotationNamespacePrefix + "unknown") + "\": null," +
                                  "\"Name\": \"Value\"" +
                                  "}",
                    ExpectedPayload   = PayloadBuilder.ComplexValue("TestModel.ComplexType").PrimitiveProperty("Name", "Value"),
                    ExpectedException = (ExpectedException)null
                },
                new
                {
                    Description = "Custom property annotation after the property - should fail.",
                    Json        = "{" +
                                  "\"Name\": \"Value\"," +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("Name", "custom.annotation") + "\": null" +
                                  "}",
                    ExpectedPayload   = PayloadBuilder.ComplexValue("TestModel.ComplexType"),
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_PropertyAnnotationAfterTheProperty", "custom.annotation", "Name")
                },
                new
                {
                    Description = "OData property annotation.",
                    Json        = "{" +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("Name", JsonLightConstants.ODataTypeAnnotationName) + "\": \"Edm.String\"," +
                                  "\"Name\": \"Value\"" +
                                  "}",
                    ExpectedPayload = PayloadBuilder.ComplexValue("TestModel.ComplexType")
                                      .PrimitiveProperty("Name", "Value"),
                    ExpectedException = (ExpectedException)null
                },
                new
                {
                    Description = "Duplicate odata property annotation.",
                    Json        = "{" +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("Name", JsonLightConstants.ODataTypeAnnotationName) + "\": \"Edm.Int32\"," +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("Name", JsonLightConstants.ODataTypeAnnotationName) + "\": \"Edm.String\"," +
                                  "\"Name\": \"Value\"" +
                                  "}",
                    ExpectedPayload   = PayloadBuilder.ComplexValue("TestModel.ComplexType"),
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_DuplicateAnnotationForPropertyNotAllowed", JsonLightConstants.ODataTypeAnnotationName, "Name")
                },
                new
                {
                    Description = "Property with object value and type name annotation - should fail.",
                    Json        = "{" +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("Address", JsonLightConstants.ODataTypeAnnotationName) + "\":\"TestModel.Address\"," +
                                  "\"Address\":{}" +
                                  "}",
                    ExpectedPayload   = PayloadBuilder.ComplexValue("TestModel.ComplexType"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_ComplexValueWithPropertyTypeAnnotation", JsonLightConstants.ODataTypeAnnotationName)
                },
                new
                {
                    Description = "String property with type annotation after the property - should fail.",
                    Json        = "{" +
                                  "\"Name\":\"value\"," +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("Name", JsonLightConstants.ODataTypeAnnotationName) + "\":\"Edm.String\"" +
                                  "}",
                    ExpectedPayload   = PayloadBuilder.ComplexValue("TestModel.ComplexType"),
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_PropertyAnnotationAfterTheProperty", JsonLightConstants.ODataTypeAnnotationName, "Name")
                },
                new
                {
                    Description = "String property with null type annotation - should fail.",
                    Json        = "{" +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("Name", JsonLightConstants.ODataTypeAnnotationName) + "\":null," +
                                  "\"Name\":\"value\"" +
                                  "}",
                    ExpectedPayload   = PayloadBuilder.ComplexValue("TestModel.ComplexType"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_InvalidTypeName", string.Empty)
                },
                new
                {
                    Description = "null property with unknown type annotation - should fail.",
                    Json        = "{" +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("Name", JsonLightConstants.ODataTypeAnnotationName) + "\":\"Unknown\"," +
                                  "\"Name\":null" +
                                  "}",
                    ExpectedPayload   = PayloadBuilder.ComplexValue("TestModel.ComplexType"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectTypeKind", "Unknown", "Primitive", "Complex"),
                },
                new
                {
                    Description = "Spatial property with odata.type annotation inside the GeoJson object - should fail.",
                    Json        = "{" +
                                  "\"Location\":" + SpatialUtils.GetSpatialStringValue(ODataFormat.Json, GeographyFactory.Point(33.1, -110.0).Build(), "Edm.GeographyPoint") +
                                  "}",
                    ExpectedPayload   = PayloadBuilder.ComplexValue("TestModel.ComplexType"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_ODataTypeAnnotationInPrimitiveValue", JsonLightConstants.ODataTypeAnnotationName),
                },
                new
                {
                    Description = "Spatial property with odata.type annotation inside and outside the GeoJson object - should fail.",
                    Json        = "{" +
                                  "\"" + JsonLightUtils.GetPropertyAnnotationName("Location", JsonLightConstants.ODataTypeAnnotationName) + "\":\"Edm.GeographyPoint\"," +
                                  "\"Location\":" + SpatialUtils.GetSpatialStringValue(ODataFormat.Json, GeographyFactory.Point(33.1, -110.0).Build(), "Edm.GeographyPoint") +
                                  "}",
                    ExpectedPayload   = PayloadBuilder.ComplexValue("TestModel.ComplexType"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_ODataTypeAnnotationInPrimitiveValue", JsonLightConstants.ODataTypeAnnotationName),
                },
            };

            testDescriptors = testDescriptors.Concat(explicitPayloads.Select(payload =>
            {
                return(new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Property("TopLevelProperty", payload.ExpectedPayload.DeepCopy()
                                                             .JsonRepresentation(payload.Json)
                                                             // JSON Light payloads don't store complex type names since the type can be inferred from the context URI and or API.
                                                             .SetAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    }))
                                     // Don't reorder the properties on serialization
                                     .SetAnnotation(new JsonLightMaintainPropertyOrderAnnotation())
                                     .ExpectedProperty(owningType, "TopLevelProperty"),
                    PayloadEdmModel = model,
                    ExpectedException = payload.ExpectedException,
                    DebugDescription = payload.Description,
                    ExpectedResultPayloadElement = tc => tc.IsRequest
                        ? PayloadBuilder.Property(string.Empty, payload.ExpectedPayload.DeepCopy()
                                                  .SetAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    }))
                        : PayloadBuilder.Property("TopLevelProperty", payload.ExpectedPayload.DeepCopy()
                                                  .SetAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    }))
                });
            }));

            // Manual test descriptors
            testDescriptors = testDescriptors.Concat(new PayloadReaderTestDescriptor[]
            {
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "null complex value in request.",
                    PayloadElement   = PayloadBuilder.Property("TopLevelProperty", PayloadBuilder.ComplexValue("TestModel.ComplexType", true)
                                                               // JSON Light payloads don't store complex type names since the type can be inferred from the context URI and or API.
                                                               .SetAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    }))
                                       .JsonRepresentation("{\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataNullAnnotationName + "\":true}")
                                       .ExpectedProperty(owningType, "TopLevelProperty"),
                    //PayloadModel = model,
                    PayloadEdmModel = model,
                    ExpectedResultPayloadElement = tc => PayloadBuilder.Property(string.Empty, PayloadBuilder.ComplexValue("TestModel.ComplexType", true)
                                                                                 .SetAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    })),
                    SkipTestConfiguration = tc => !tc.IsRequest
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "null complex value in response.",
                    PayloadElement   = PayloadBuilder.Property("TopLevelProperty", PayloadBuilder.ComplexValue("TestModel.ComplexType", true)
                                                               // JSON Light payloads don't store complex type names since the type can be inferred from the context URI and or API.
                                                               .SetAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    }))
                                       .JsonRepresentation(
                        "{" +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#TestModel.ComplexType\"," +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataNullAnnotationName + "\":true" +
                        "}")
                                       .ExpectedProperty(owningType, "TopLevelProperty"),
                    //PayloadModel = model,
                    PayloadEdmModel = model,
                    ExpectedResultPayloadElement = tc => PayloadBuilder.Property("TopLevelProperty", PayloadBuilder.ComplexValue("TestModel.ComplexType", true)
                                                                                 .SetAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    })),
                    SkipTestConfiguration = tc => tc.IsRequest
                }
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                // These descriptors are already tailored specifically for Json Light and
                // do not require normalization.
                testDescriptor.TestDescriptorNormalizers.Clear();
                testDescriptor.RunTest(testConfiguration);
            });
        }
        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);
        }
        public static IEdmModel CreateEdm()
        {
            var model = new EdmModel();

            // Complex Type
            EdmComplexType address = new EdmComplexType(Namespace, "Address");

            address.AddStructuralProperty("Country", EdmPrimitiveTypeKind.String);
            address.AddStructuralProperty("City", EdmPrimitiveTypeKind.String);
            model.AddElement(address);

            EdmComplexType subAddress = new EdmComplexType(Namespace, "SubAddress", address);

            subAddress.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String);
            model.AddElement(subAddress);

            // Enum type
            EdmEnumType color = new EdmEnumType(Namespace, "Color");

            color.AddMember(new EdmEnumMember(color, "None", new EdmEnumMemberValue(0)));
            color.AddMember(new EdmEnumMember(color, "Red", new EdmEnumMemberValue(1)));
            color.AddMember(new EdmEnumMember(color, "Blue", new EdmEnumMemberValue(2)));
            color.AddMember(new EdmEnumMember(color, "Green", new EdmEnumMemberValue(3)));
            model.AddElement(color);

            // Entity type
            EdmEntityType customer = new EdmEntityType(Namespace, "Customer");

            customer.AddKeys(customer.AddStructuralProperty("CustomerId", EdmPrimitiveTypeKind.Int32));
            customer.AddStructuralProperty("Location", new EdmComplexTypeReference(address, isNullable: true));
            model.AddElement(customer);

            EdmEntityType vipCustomer = new EdmEntityType(Namespace, "VipCustomer", customer);

            vipCustomer.AddStructuralProperty("FavoriteColor", new EdmEnumTypeReference(color, isNullable: false));
            model.AddElement(vipCustomer);

            EdmEntityType order = new EdmEntityType(Namespace, "Order");

            order.AddKeys(order.AddStructuralProperty("OrderId", EdmPrimitiveTypeKind.Int32));
            order.AddStructuralProperty("Token", EdmPrimitiveTypeKind.Guid);
            model.AddElement(order);

            EdmEntityContainer container = new EdmEntityContainer(Namespace, "Container");
            EdmEntitySet       customers = container.AddEntitySet("Customers", customer);
            EdmEntitySet       orders    = container.AddEntitySet("Orders", order);

            model.AddElement(container);

            // EdmSingleton mary = container.AddSingleton("Mary", customer);

            // navigation properties
            EdmNavigationProperty ordersNavProp = customer.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo
            {
                Name = "Orders",
                TargetMultiplicity = EdmMultiplicity.Many,
                Target             = order
            });

            customers.AddNavigationTarget(ordersNavProp, orders);

            // function
            IEdmTypeReference stringType = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.String, isNullable: false);
            IEdmTypeReference intType    = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Int32, isNullable: false);

            EdmFunction getFirstName = new EdmFunction(Namespace, "GetFirstName", stringType, isBound: true, entitySetPathExpression: null, isComposable: false);

            getFirstName.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            model.AddElement(getFirstName);

            EdmFunction getNumber = new EdmFunction(Namespace, "GetOrderCount", intType, isBound: false, entitySetPathExpression: null, isComposable: false);

            model.AddElement(getNumber);
            container.AddFunctionImport("GetOrderCount", getNumber);

            // action
            EdmAction calculate = new EdmAction(Namespace, "CalculateOrderPrice", returnType: null, isBound: true, entitySetPathExpression: null);

            calculate.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            model.AddElement(calculate);

            EdmAction change = new EdmAction(Namespace, "ChangeCustomerById", returnType: null, isBound: false, entitySetPathExpression: null);

            change.AddParameter("Id", intType);
            model.AddElement(change);
            container.AddActionImport("ChangeCustomerById", change);


            return(model);
        }
Ejemplo n.º 5
0
        [Ignore] // Remove Atom
        // [TestMethod, Variation(Description = "Validates the payloads for various stream properties.")]
        public void WriterStreamPropertiesTests()
        {
            Uri baseUri             = new Uri("http://www.odata.org/", UriKind.Absolute);
            Uri relativeReadLinkUri = new Uri("readlink", UriKind.RelativeOrAbsolute);
            Uri relativeEditLinkUri = new Uri("editlink", UriKind.RelativeOrAbsolute);
            Uri absoluteReadLinkUri = new Uri(baseUri, relativeReadLinkUri.OriginalString);
            Uri absoluteEditLinkUri = new Uri(baseUri, relativeEditLinkUri.OriginalString);

            string contentType        = "application/binary";
            string etag               = "\"myetagvalue\"";
            string streamPropertyName = "stream1";

            var namedStreamProperties = new[]
            {
                // with only read link
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = relativeReadLinkUri
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = relativeReadLinkUri, ContentType = contentType
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = absoluteReadLinkUri
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = absoluteReadLinkUri, ContentType = contentType
                    }
                },
                // with only edit link
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        EditLink = relativeEditLinkUri
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        EditLink = relativeEditLinkUri, ContentType = contentType
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        EditLink = relativeEditLinkUri, ContentType = contentType, ETag = etag
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        EditLink = absoluteEditLinkUri
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        EditLink = absoluteEditLinkUri, ContentType = contentType
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        EditLink = absoluteEditLinkUri, ContentType = contentType, ETag = etag
                    }
                },
                // with both edit and read link
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = relativeReadLinkUri, EditLink = relativeEditLinkUri
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = relativeReadLinkUri, EditLink = relativeEditLinkUri, ContentType = contentType
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = relativeReadLinkUri, EditLink = relativeEditLinkUri, ContentType = contentType, ETag = etag
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = absoluteReadLinkUri, EditLink = relativeEditLinkUri
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = absoluteReadLinkUri, EditLink = relativeEditLinkUri, ContentType = contentType
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = absoluteReadLinkUri, EditLink = relativeEditLinkUri, ContentType = contentType, ETag = etag
                    }
                },
            };

            var testCases = namedStreamProperties.Select(property =>
            {
                var propertyName         = property.Name;
                var streamReferenceValue = (ODataStreamReferenceValue)property.Value;
                return(new StreamPropertyTestCase
                {
                    NamedStreamProperty = property,
                    GetExpectedAtomPayload = (testConfiguration) =>
                    {
                        return
                        (streamReferenceValue.ReadLink == null
                                    ? string.Empty
                                    : (
                             "<link rel=\"http://docs.oasis-open.org/odata/ns/mediaresource/" + property.Name + "\" " +
                             (streamReferenceValue.ContentType == null ? string.Empty : "type=\"" + streamReferenceValue.ContentType + "\" ") +
                             "title=\"" + property.Name + "\" " +
                             "href=\"" + (((ODataStreamReferenceValue)property.Value).ReadLink.IsAbsoluteUri ? absoluteReadLinkUri.OriginalString : relativeReadLinkUri.OriginalString) + "\" " +
                             "xmlns=\"" + TestAtomConstants.AtomNamespace + "\" />")) +

                        (streamReferenceValue.EditLink == null
                                    ? string.Empty
                                    : (
                             "<link rel=\"http://docs.oasis-open.org/odata/ns/edit-media/" + property.Name + "\" " +
                             (streamReferenceValue.ContentType == null ? string.Empty : "type=\"" + streamReferenceValue.ContentType + "\" ") +
                             "title=\"" + property.Name + "\" " +
                             "href=\"" + (((ODataStreamReferenceValue)property.Value).EditLink.IsAbsoluteUri ? absoluteEditLinkUri.OriginalString : relativeEditLinkUri.OriginalString) + "\" " +
                             (streamReferenceValue.ETag == null ? string.Empty : "m:etag=\"" + streamReferenceValue.ETag.Replace("\"", "&quot;") + "\" xmlns:m=\"" + TestAtomConstants.ODataMetadataNamespace + "\" ") +
                             "xmlns=\"" + TestAtomConstants.AtomNamespace + "\" />"));
                    },
                    GetExpectedJsonLightPayload = (testConfiguration) =>
                    {
                        return JsonLightWriterUtils.CombineProperties(
                            (streamReferenceValue.EditLink == null ? string.Empty : ("\"" + JsonLightUtils.GetPropertyAnnotationName(propertyName, JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"" + absoluteEditLinkUri.OriginalString + "\"")),
                            (streamReferenceValue.ReadLink == null ? string.Empty : ("\"" + JsonLightUtils.GetPropertyAnnotationName(propertyName, JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"" + absoluteReadLinkUri.OriginalString + "\"")),
                            (streamReferenceValue.ContentType == null ? string.Empty : ("\"" + JsonLightUtils.GetPropertyAnnotationName(propertyName, JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":\"" + streamReferenceValue.ContentType + "\"")),
                            (streamReferenceValue.ETag == null ? string.Empty : ("\"" + JsonLightUtils.GetPropertyAnnotationName(propertyName, JsonLightConstants.ODataMediaETagAnnotationName) + "\":\"" + streamReferenceValue.ETag.Replace("\"", "\\\"") + "\"")));
                    },
                });
            });

            var testDescriptors = testCases.SelectMany(testCase =>
            {
                EdmModel model = new EdmModel();

                EdmEntityType edmEntityType = new EdmEntityType("TestModel", "StreamPropertyEntityType");
                EdmStructuralProperty edmStructuralProperty = edmEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false);
                edmEntityType.AddKeys(new IEdmStructuralProperty[] { edmStructuralProperty });
                model.AddElement(edmEntityType);

                EdmEntityContainer edmEntityContainer = new EdmEntityContainer("TestModel", "DefaultContainer");
                model.AddElement(edmEntityContainer);

                EdmEntitySet edmEntitySet = new EdmEntitySet(edmEntityContainer, "StreamPropertyEntitySet", edmEntityType);
                edmEntityContainer.AddElement(edmEntitySet);

                ODataResource entry = new ODataResource()
                {
                    Id       = ObjectModelUtils.DefaultEntryId,
                    ReadLink = ObjectModelUtils.DefaultEntryReadLink,
                    TypeName = edmEntityType.FullName()
                };

                var streamReference = (ODataStreamReferenceValue)testCase.NamedStreamProperty.Value;
                bool needBaseUri    = (streamReference.ReadLink != null && !streamReference.ReadLink.IsAbsoluteUri) || (streamReference.EditLink != null && !streamReference.EditLink.IsAbsoluteUri);
                entry.Properties    = new ODataProperty[] { testCase.NamedStreamProperty };

                var resultDescriptor = new PayloadWriterTestDescriptor <ODataItem>(
                    this.Settings,
                    entry,
                    (testConfiguration) =>
                {
                    if (testConfiguration.Format == ODataFormat.Json)
                    {
                        return(new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            Json = string.Join(
                                "$(NL)",
                                "{",
                                testCase.GetExpectedJsonLightPayload(testConfiguration),
                                "}"),
                            FragmentExtractor = result => result.RemoveAllAnnotations(true),
                        });
                    }
                    else
                    {
                        throw new NotSupportedException("Unsupported ODataFormat found: " + testConfiguration.Format.ToString());
                    }
                })
                {
                    Model = model,
                    PayloadEdmElementContainer = edmEntityContainer,
                    PayloadEdmElementType      = edmEntityType,
                };

                var resultTestCases = new List <StreamPropertyTestDescriptor>();
                if (needBaseUri)
                {
                    resultTestCases.Add(new StreamPropertyTestDescriptor {
                        BaseUri = baseUri, TestDescriptor = resultDescriptor
                    });
                }
                else
                {
                    resultTestCases.Add(new StreamPropertyTestDescriptor {
                        BaseUri = null, TestDescriptor = resultDescriptor
                    });
                    resultTestCases.Add(new StreamPropertyTestDescriptor {
                        BaseUri = baseUri, TestDescriptor = resultDescriptor
                    });
                    resultTestCases.Add(new StreamPropertyTestDescriptor {
                        BaseUri = new Uri("http://mybaseuri/", UriKind.Absolute), TestDescriptor = resultDescriptor
                    });
                }

                return(resultTestCases);
            });

            var testDescriptorBaseUriPairSet = testDescriptors.SelectMany(descriptor =>
                                                                          WriterPayloads.NamedStreamPayloads(descriptor.TestDescriptor).Select(namedStreamPayload =>
                                                                                                                                               new Tuple <PayloadWriterTestDescriptor <ODataItem>, Uri>(namedStreamPayload, descriptor.BaseUri)));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptorBaseUriPairSet,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptorBaseUriPair, testConfiguration) =>
            {
                var testDescriptor = testDescriptorBaseUriPair.Item1;

                if (testDescriptor.IsGeneratedPayload && testConfiguration.Format == ODataFormat.Json)
                {
                    return;
                }

                ODataMessageWriterSettings settings = testConfiguration.MessageWriterSettings.Clone();
                settings.BaseUri = testDescriptorBaseUriPair.Item2;
                settings.SetServiceDocumentUri(ServiceDocumentUri);

                WriterTestConfiguration config =
                    new WriterTestConfiguration(testConfiguration.Format, settings, testConfiguration.IsRequest, testConfiguration.Synchronous);

                if (testConfiguration.IsRequest)
                {
                    ODataResource payloadEntry        = (ODataResource)testDescriptor.PayloadItems[0];
                    ODataProperty firstStreamProperty = payloadEntry.Properties.Where(p => p.Value is ODataStreamReferenceValue).FirstOrDefault();
                    this.Assert.IsNotNull(firstStreamProperty, "firstStreamProperty != null");

                    testDescriptor = new PayloadWriterTestDescriptor <ODataItem>(testDescriptor)
                    {
                        ExpectedResultCallback = tc => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            ExpectedException2 = ODataExpectedExceptions.ODataException("WriterValidationUtils_StreamPropertyInRequest", firstStreamProperty.Name)
                        }
                    };
                }

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, config, this.Assert, this.Logger);
            });
        }
Ejemplo n.º 6
0
        private void InitializeEdmModel()
        {
            this.edmModel = new EdmModel();

            EdmEntityContainer defaultContainer = new EdmEntityContainer("TestModel", "DefaultContainer");

            this.edmModel.AddElement(defaultContainer);

            addressType = new EdmComplexType("TestModel", "Address");
            addressType.AddStructuralProperty("Street", EdmCoreModel.Instance.GetString(/*isNullable*/ false));
            addressType.AddStructuralProperty("Zip", EdmCoreModel.Instance.GetString(/*isNullable*/ false));

            this.cityType = new EdmEntityType("TestModel", "City", baseType: null, isAbstract: false, isOpen: true);
            EdmStructuralProperty cityIdProperty = cityType.AddStructuralProperty("Id", EdmCoreModel.Instance.GetInt32(/*isNullable*/ false));

            cityType.AddKeys(cityIdProperty);
            cityType.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(/*isNullable*/ false));
            cityType.AddStructuralProperty("Size", EdmCoreModel.Instance.GetInt32(/*isNullable*/ false));
            cityType.AddStructuralProperty("Restaurants", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(/*isNullable*/ false)));
            cityType.AddStructuralProperty("Address", new EdmComplexTypeReference(addressType, true));
            this.edmModel.AddElement(cityType);

            this.capitolCityType = new EdmEntityType("TestModel", "CapitolCity", cityType);
            capitolCityType.AddStructuralProperty("CapitolType", EdmCoreModel.Instance.GetString(/*isNullable*/ false));
            this.edmModel.AddElement(capitolCityType);

            this.districtType = new EdmEntityType("TestModel", "District");
            EdmStructuralProperty districtIdProperty = districtType.AddStructuralProperty("Id", EdmCoreModel.Instance.GetInt32(/*isNullable*/ false));

            districtType.AddKeys(districtIdProperty);
            districtType.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(/*isNullable*/ false));
            districtType.AddStructuralProperty("Zip", EdmCoreModel.Instance.GetInt32(/*isNullable*/ false));
            this.edmModel.AddElement(districtType);

            cityType.AddBidirectionalNavigation(
                new EdmNavigationPropertyInfo {
                Name = "Districts", Target = districtType, TargetMultiplicity = EdmMultiplicity.Many
            },
                new EdmNavigationPropertyInfo {
                Name = "City", Target = cityType, TargetMultiplicity = EdmMultiplicity.One
            });

            cityType.NavigationProperties().Single(np => np.Name == "Districts");
            capitolCityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "CapitolDistrict", Target = districtType, TargetMultiplicity = EdmMultiplicity.One
            });
            capitolCityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo {
                Name = "OutlyingDistricts", Target = districtType, TargetMultiplicity = EdmMultiplicity.Many
            });

            this.citySet     = defaultContainer.AddEntitySet("Cities", cityType);
            this.districtSet = defaultContainer.AddEntitySet("Districts", districtType);

            this.singletonCity = defaultContainer.AddSingleton("SingletonCity", cityType);

            // operations
            var cityReference       = new EdmEntityTypeReference(cityType, true);
            var districtReference   = new EdmEntityTypeReference(districtType, true);
            IEdmPathExpression path = new EdmPathExpression("binding/Districts");
            var function            = new EdmFunction("TestModel", "GetOneDistrict", districtReference, true, path, true /*isComposable*/);

            function.AddParameter("binding", cityReference);
            edmModel.AddElement(function);
        }
        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);
            });
        }
Ejemplo n.º 10
0
 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);
 }
Ejemplo n.º 11
0
        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);
        }
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 13
0
        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);
        }
Ejemplo n.º 14
0
        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.");
            }
        }
        public void TopLevelOpenPropertiesTest()
        {
            EdmModel edmModel  = new EdmModel();
            var      container = new EdmEntityContainer("TestModel", "DefaultContainer");

            edmModel.AddElement(container);

            var openCustomerType = new EdmEntityType("TestModel", "OpenCustomerType", null, isAbstract: false, isOpen: true);

            openCustomerType.AddKeys(openCustomerType.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32, isNullable: false));
            edmModel.AddElement(openCustomerType);

            var addressType = new EdmComplexType("TestModel", "AddressType");

            addressType.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String, isNullable: true);
            edmModel.AddElement(addressType);

            container.AddEntitySet("CustomerSet", openCustomerType);

            ISpatial pointValue = GeographyFactory.Point(32.0, -100.0).Build();

            IEnumerable <PropertyPayloadTestCase> testCases = new[]
            {
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Top-level open primitive property.",
                    Property         = new ODataProperty {
                        Name = "Age", Value = (long)42
                    },
                    Model        = edmModel,
                    PropertyType = "Edm.Int64",
                    Json         = string.Join("$(NL)",
                                               "{{",
                                               "{0},\"value\":\"42\"",
                                               "}}")
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Top-level open spatial property.",
                    Property         = new ODataProperty {
                        Name = "Location", Value = pointValue
                    },
                    Model        = edmModel,
                    PropertyType = "Edm.GeographyPoint",
                    Json         = string.Join("$(NL)",
                                               "{{",
                                               "{0}," +
                                               "\"" + JsonLightConstants.ODataValuePropertyName + "\":{{",
                                               "\"type\":\"Point\",\"coordinates\":[",
                                               "-100.0,32.0",
                                               "],\"crs\":{{",
                                               "\"type\":\"name\",\"properties\":{{",
                                               "\"name\":\"EPSG:4326\"",
                                               "}}",
                                               "}}",
                                               "}}",
                                               "}}")
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Top-level open complex property.",
                    Property         = new ODataProperty {
                        Name = "Address", Value = new ODataComplexValue {
                            TypeName = "TestModel.AddressType"
                        }
                    },
                    Model        = edmModel,
                    PropertyType = "TestModel.AddressType",
                    Json         = string.Join("$(NL)",
                                               "{{",
                                               "{0}",
                                               "}}")
                },
            };

            IEnumerable <PayloadWriterTestDescriptor <ODataProperty> > testDescriptors = testCases.Select(testCase =>
                                                                                                          new PayloadWriterTestDescriptor <ODataProperty>(
                                                                                                              this.Settings,
                                                                                                              testCase.Property,
                                                                                                              tc => new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
            {
                Json = string.Format(
                    CultureInfo.InvariantCulture,
                    testCase.Json,
                    JsonLightWriterUtils.GetMetadataUrlPropertyForProperty(testCase.PropertyType)),
                FragmentExtractor = (result) => result.RemoveAllAnnotations(true)
            })
            {
                DebugDescription = testCase.DebugDescription,
                Model            = testCase.Model,
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.JsonLightFormatConfigurationsWithIndent,
                (testDescriptor, testConfiguration) =>
            {
                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteProperty(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
Ejemplo n.º 16
0
        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);
        }
Ejemplo n.º 17
0
        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.AspNet.OData.Test.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);

            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);

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

            // action with optional parameters
            EdmAction updateSalaray = new EdmAction("NS", "UpdateSalaray", returnType: null, isBound: true, entitySetPathExpression: null);

            updateSalaray.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            updateSalaray.AddParameter("minSalaray", intType);
            updateSalaray.AddOptionalParameter("maxSalaray", intType);
            updateSalaray.AddOptionalParameter("aveSalaray", intType, "129");

            // functions
            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);

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

            // 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;
        }
        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);
            }
        }
Ejemplo n.º 19
0
        public void TopLevelPropertiesWithMetadataTest()
        {
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = PayloadReaderTestDescriptorGenerator.CreatePrimitiveValueTestDescriptors(this.Settings);

            testDescriptors = testDescriptors.Concat(PayloadReaderTestDescriptorGenerator.CreateComplexValueTestDescriptors(this.Settings, true));
            testDescriptors = testDescriptors.Concat(PayloadReaderTestDescriptorGenerator.CreateCollectionTestDescriptors(this.Settings, true));

            testDescriptors = testDescriptors.Select(collectionTestDescriptor => collectionTestDescriptor.InProperty("propertyName"));
            testDescriptors = testDescriptors.SelectMany(td => this.PayloadGenerator.GenerateReaderPayloads(td));

            // Limit to only top-level property payloads
            testDescriptors = testDescriptors.Where(td => td.PayloadElement is PropertyInstance);

            // Add a couple of invalid cases which use a standard model
            EdmModel model = new EdmModel();

            model.ComplexType("UnusedComplexType");

            EdmEntityType unusedEntityType = model.EntityType("UnusedEntityType");

            unusedEntityType.AddKeys(unusedEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, isNullable: false));
            unusedEntityType.Property("Name", EdmPrimitiveTypeKind.String, isNullable: false);

            EdmEntityType streamPropertyEntityType = model.EntityType("EntityTypeWithStreamProperty");

            streamPropertyEntityType.AddKeys(streamPropertyEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, isNullable: false));
            streamPropertyEntityType.AddStructuralProperty("Video", EdmPrimitiveTypeKind.Stream, isNullable: false);
            streamPropertyEntityType.Property("NonStreamProperty", EdmPrimitiveTypeKind.Boolean, isNullable: false);

            EdmEntityType navigationPropertyEntityType = model.EntityType("EntityTypeWithNavigationProperty");

            navigationPropertyEntityType.AddKeys(navigationPropertyEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, isNullable: false));
            navigationPropertyEntityType.NavigationProperty("Navigation", streamPropertyEntityType);

            model.Fixup();

            EdmEntityContainer container = model.EntityContainer as EdmEntityContainer;

            EdmFunction nameFunction = new EdmFunction(container.Namespace, "NameFunctionImport", EdmCoreModel.Instance.GetInt32(false), false /*isBound*/, null, false /*isComposable*/);

            model.AddElement(nameFunction);
            container.AddFunctionImport("NameFunctionImport", nameFunction);
            model.Fixup();

            var videoPropertyType = model.GetEntityType("TestModel.EntityTypeWithStreamProperty").Properties().Single(p => p.Name == "Video").Type;

            var explicitTestDescriptors = new[]
            {
                // Non existant type name
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.Property("propertyName", PayloadBuilder.ComplexValue("TestModel.NonExistantType")),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", "TestModel.NonExistantType"),
                    // This test has different meaning in JSON-L (no expected type + non-existent typename)
                    SkipTestConfiguration = (tc) => tc.Format == ODataFormat.Json,
                },
                // Existing type name without namespace
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.Property("propertyName", PayloadBuilder.ComplexValue("UnusedComplexType")),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", "UnusedComplexType"),
                    // This test has different meaning in JSON-L (no expected type + non-existent typename)
                    SkipTestConfiguration = (tc) => tc.Format == ODataFormat.Json,
                },
                // Existing type of wrong kind
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.Property("propertyName", PayloadBuilder.ComplexValue("TestModel.UnusedEntityType")),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectValueTypeKind", "TestModel.UnusedEntityType", "Entity"),
                    // This test has different meaning in JSON-L
                    SkipTestConfiguration = (tc) => tc.Format == ODataFormat.Json,
                },
                // A stream is not allowed in a property with a non-stream property kind.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement         = PayloadBuilder.Entity("TestModel.EntityTypeWithStreamProperty").StreamProperty("NonStreamProperty", "http://readlink", "http://editlink"),
                    PayloadEdmModel        = model,
                    ExpectedResultCallback = tc =>
                                             new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException = tc.Format == ODataFormat.Atom
                                    ? tc.IsRequest
                                        ? null
                                        : ODataExpectedExceptions.ODataException("ValidationUtils_MismatchPropertyKindForStreamProperty", "NonStreamProperty")
                                    : tc.Format == ODataFormat.Json
                                        ? ODataExpectedExceptions.ODataException("ODataJsonLightEntryAndFeedDeserializer_PropertyWithoutValueWithWrongType", "NonStreamProperty", "Edm.Boolean")
                                        : ODataExpectedExceptions.ODataException("JsonReaderExtensions_UnexpectedNodeDetected", "PrimitiveValue", "StartObject")
                    },
                },
                // Top-level property of stream type is not allowed
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.PrimitiveProperty("Video", 42).ExpectedPropertyType(videoPropertyType),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ArgumentException("ODataMessageReader_ExpectedPropertyTypeStream"),
                },
                // Top-level deferred navigation property is not allowed
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.PrimitiveProperty("Video", 42).ExpectedPropertyType(streamPropertyEntityType),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ArgumentException("ODataMessageReader_ExpectedPropertyTypeEntityKind"),
                },
                // Top-level expanded navigation property is not allowed
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.PrimitiveProperty("Video", 42).ExpectedPropertyType(streamPropertyEntityType),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ArgumentException("ODataMessageReader_ExpectedPropertyTypeEntityKind"),
                },
            };

            testDescriptors = testDescriptors.Concat(explicitTestDescriptors);

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                var property = testDescriptor.PayloadElement as PropertyInstance;
                if (property != null && testConfiguration.Format == ODataFormat.Atom)
                {
                    property.Name = null;
                }
                testDescriptor.RunTest(testConfiguration);
            });
        }
Ejemplo n.º 20
0
        /// <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);
        }
Ejemplo n.º 21
0
        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 EdmEnumMemberValue(0));
            genderType.AddMember("Female", new EdmEnumMemberValue(1));
            genderType.AddMember("Unknown", new EdmEnumMemberValue(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);

            var path = new EdmPathExpression("Trips/PlanItems/Microsoft.OData.SampleService.Models.TripPin.Flight/Airline");

            personSet.AddNavigationTarget(flightAirlineNavigation, airlineSet, path);
            me.AddNavigationTarget(flightAirlineNavigation, airlineSet, path);

            path = new EdmPathExpression("Trips/PlanItems/Microsoft.OData.SampleService.Models.TripPin.Flight/From");
            personSet.AddNavigationTarget(flightFromAirportNavigation, airportSet, path);
            me.AddNavigationTarget(flightFromAirportNavigation, airportSet, path);

            path = new EdmPathExpression("Trips/PlanItems/Microsoft.OData.SampleService.Models.TripPin.Flight/To");
            personSet.AddNavigationTarget(flightToAirportNavigation, airportSet, path);
            me.AddNavigationTarget(flightToAirportNavigation, airportSet, path);

            personSet.AddNavigationTarget(personPhotoNavigation, photoSet);
            me.AddNavigationTarget(personPhotoNavigation, photoSet);

            path = new EdmPathExpression("Trips/Photos");
            personSet.AddNavigationTarget(tripPhotosNavigation, photoSet, path);
            me.AddNavigationTarget(tripPhotosNavigation, photoSet, path);

            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 EdmPathExpression("Airports"), 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);
        }
Ejemplo n.º 22
0
        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);
        }
Ejemplo n.º 23
0
        private static IEdmModel BuildModel()
        {
            EdmModel model = new EdmModel();

            var movieType = new EdmEntityType("TestModel", "Movie");
            EdmStructuralProperty idProperty = new EdmStructuralProperty(movieType, "Id", EdmCoreModel.Instance.GetInt32(false));

            movieType.AddProperty(idProperty);
            movieType.AddKeys(idProperty);
            movieType.AddProperty(new EdmStructuralProperty(movieType, "Name", EdmCoreModel.Instance.GetString(true)));
            model.AddElement(movieType);

            var tvMovieType = new EdmEntityType("TestModel", "TVMovie", movieType);

            tvMovieType.AddProperty(new EdmStructuralProperty(tvMovieType, "Channel", EdmCoreModel.Instance.GetString(false)));
            model.AddElement(tvMovieType);

            EdmEntityContainer defaultContainer = new EdmEntityContainer("TestModel", "Default");

            defaultContainer.AddEntitySet("Movies", movieType);
            model.AddElement(defaultContainer);

            EdmAction simpleAction = new EdmAction("TestModel", "SimpleAction", null /*returnType*/, false /*isBound*/, null /*entitySetPath*/);

            model.AddElement(simpleAction);
            defaultContainer.AddActionImport(simpleAction);

            EdmAction checkoutAction1 = new EdmAction("TestModel", "Checkout", EdmCoreModel.Instance.GetInt32(false), false /*isBound*/, null /*entitySetPath*/);

            checkoutAction1.AddParameter("movie", movieType.ToTypeReference());
            checkoutAction1.AddParameter("duration", EdmCoreModel.Instance.GetInt32(false));
            model.AddElement(checkoutAction1);

            EdmAction rateAction1 = new EdmAction("TestModel", "Rate", null /*returnType*/, true /*isBound*/, null /*entitySetPath*/);

            rateAction1.AddParameter("movie", movieType.ToTypeReference());
            rateAction1.AddParameter("rating", EdmCoreModel.Instance.GetInt32(false));
            model.AddElement(rateAction1);

            EdmAction changeChannelAction1 = new EdmAction("TestModel", "ChangeChannel", null /*returnType*/, true /*isBound*/, null /*entitySetPath*/);

            changeChannelAction1.AddParameter("movie", tvMovieType.ToTypeReference());
            changeChannelAction1.AddParameter("channel", EdmCoreModel.Instance.GetString(false));
            model.AddElement(changeChannelAction1);

            EdmAction checkoutAction = new EdmAction("TestModel", "Checkout", EdmCoreModel.Instance.GetInt32(false) /*returnType*/, false /*isBound*/, null /*entitySetPath*/);

            checkoutAction.AddParameter("movie", movieType.ToTypeReference());
            checkoutAction.AddParameter("duration", EdmCoreModel.Instance.GetInt32(false));
            model.AddElement(checkoutAction);

            var movieCollectionTypeReference = (new EdmCollectionType(movieType.ToTypeReference(nullable: false))).ToTypeReference(nullable: false);

            EdmAction checkoutMultiple1Action = new EdmAction("TestModel", "CheckoutMultiple", EdmCoreModel.Instance.GetInt32(false), false /*isBound*/, null /*entitySetPath*/);

            checkoutMultiple1Action.AddParameter("movies", movieCollectionTypeReference);
            checkoutMultiple1Action.AddParameter("duration", EdmCoreModel.Instance.GetInt32(false));
            model.AddElement(checkoutMultiple1Action);

            EdmAction rateMultiple1Action = new EdmAction("TestModel", "RateMultiple", null /*returnType*/, true /*isBound*/, null /*entitySetPath*/);

            rateMultiple1Action.AddParameter("movies", movieCollectionTypeReference);
            rateMultiple1Action.AddParameter("rating", EdmCoreModel.Instance.GetInt32(false));
            model.AddElement(rateMultiple1Action);

            EdmAction checkoutMultiple2Action = new EdmAction("TestModel", "CheckoutMultiple", EdmCoreModel.Instance.GetInt32(false) /*returnType*/, false /*isBound*/, null /*entitySetPath*/);

            checkoutMultiple2Action.AddParameter("movies", movieCollectionTypeReference);
            checkoutMultiple2Action.AddParameter("duration", EdmCoreModel.Instance.GetInt32(false));
            model.AddElement(checkoutMultiple2Action);

            EdmAction rateMultiple2Action = new EdmAction("TestModel", "RateMultiple", null /*returnType*/, true /*isBound*/, null /*entitySetPath*/);

            rateMultiple2Action.AddParameter("movies", movieCollectionTypeReference);
            rateMultiple2Action.AddParameter("rating", EdmCoreModel.Instance.GetInt32(false));
            model.AddElement(rateMultiple2Action);

            return(model);
        }
Ejemplo n.º 24
0
        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"
                                     } }
            };
        }
Ejemplo n.º 25
0
        public CustomersModelWithInheritance()
        {
            EdmModel model = new EdmModel();

            // Enum type simpleEnum
            EdmEnumType simpleEnum = new EdmEnumType("NS", "SimpleEnum");

            simpleEnum.AddMember(new EdmEnumMember(simpleEnum, "First", new EdmIntegerConstant(0)));
            simpleEnum.AddMember(new EdmEnumMember(simpleEnum, "Second", new EdmIntegerConstant(1)));
            simpleEnum.AddMember(new EdmEnumMember(simpleEnum, "Third", new EdmIntegerConstant(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("Country", EdmPrimitiveTypeKind.String);
            model.AddElement(address);

            // 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));
            IEdmTypeReference primitiveTypeReference = EdmCoreModel.Instance.GetPrimitive(
                EdmPrimitiveTypeKind.String,
                isNullable: true);

            customer.AddStructuralProperty(
                "City",
                primitiveTypeReference,
                defaultValue: null,
                concurrencyMode: EdmConcurrencyMode.Fixed);
            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
            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);

            specialOrder.AddStructuralProperty("SpecialOrderProperty", EdmPrimitiveTypeKind.Guid);
            model.AddElement(specialOrder);

            // test entity
            EdmEntityType testEntity = new EdmEntityType("System.Web.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,
            });

            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);

            // containment
            IEdmContainedEntitySet orderLines = (IEdmContainedEntitySet)myOrders.FindNavigationTarget(orderLinesNavProp);

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

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

            // 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 <BindableProcedureFinder>(model, new BindableProcedureFinder(model));

            // set properties
            Model                     = model;
            Container                 = container;
            Customer                  = customer;
            Order                     = order;
            Address                   = address;
            SpecialCustomer           = specialCustomer;
            SpecialOrder              = specialOrder;
            Orders                    = orders;
            Customers                 = customers;
            VipCustomer               = vipCustomer;
            Mary                      = mary;
            OrderLine                 = orderLine;
            OrderLines                = orderLines;
            UpgradeCustomer           = upgrade;
            UpgradeSpecialCustomer    = specialUpgrade;
            CustomerName              = customerName;
            IsCustomerUpgraded        = isCustomerUpgradedWithParam;
            IsSpecialCustomerUpgraded = IsSpecialUpgraded;
            Tag = tag;
        }
        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);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Creates a set of interesting entity instances along with metadata.
        /// </summary>
        /// <param name="settings">The test descriptor settings to use.</param>
        /// <param name="model">If non-null, the method creates complex types for the complex values and adds them to the model.</param>
        /// <param name="withTypeNames">true if the payloads should specify type names.</param>
        /// <returns>List of test descriptors with interesting entity instances as payload.</returns>
        public static IEnumerable <PayloadTestDescriptor> CreateEntityInstanceTestDescriptors(
            EdmModel model,
            bool withTypeNames)
        {
            IEnumerable <PrimitiveValue>             primitiveValues       = TestValues.CreatePrimitiveValuesWithMetadata(fullSet: false);
            IEnumerable <ComplexInstance>            complexValues         = TestValues.CreateComplexValues(model, withTypeNames, fullSet: false);
            IEnumerable <NamedStreamInstance>        streamReferenceValues = TestValues.CreateStreamReferenceValues(fullSet: false);
            IEnumerable <PrimitiveMultiValue>        primitiveMultiValues  = TestValues.CreatePrimitiveCollections(withTypeNames, fullSet: false);
            IEnumerable <ComplexMultiValue>          complexMultiValues    = TestValues.CreateComplexCollections(model, withTypeNames, fullSet: false);
            IEnumerable <NavigationPropertyInstance> navigationProperties  = TestValues.CreateDeferredNavigationLinks();

            // NOTE we have to copy the EntityModelTypeAnnotation on the primitive value to the NullPropertyInstance for null values since the
            //      NullPropertyInstance does not expose a value. We will later copy it back to the value we generate for the null property.
            IEnumerable <PropertyInstance> primitiveProperties =
                primitiveValues.Select((pv, ix) => PayloadBuilder.Property("PrimitiveProperty" + ix, pv).CopyAnnotation <PropertyInstance, EntityModelTypeAnnotation>(pv));
            IEnumerable <PropertyInstance> complexProperties             = complexValues.Select((cv, ix) => PayloadBuilder.Property("ComplexProperty" + ix, cv));
            IEnumerable <PropertyInstance> primitiveMultiValueProperties = primitiveMultiValues.Select((pmv, ix) => PayloadBuilder.Property("PrimitiveMultiValueProperty" + ix, pmv));
            IEnumerable <PropertyInstance> complexMultiValueProperties   = complexMultiValues.Select((cmv, ix) => PayloadBuilder.Property("ComplexMultiValueProperty" + ix, cmv));

            PropertyInstance[][] propertyMatrix = new PropertyInstance[6][];
            propertyMatrix[0] = primitiveProperties.ToArray();
            propertyMatrix[1] = complexProperties.ToArray();
            propertyMatrix[2] = streamReferenceValues.ToArray();
            propertyMatrix[3] = primitiveMultiValueProperties.ToArray();
            propertyMatrix[4] = complexMultiValueProperties.ToArray();
            propertyMatrix[5] = navigationProperties.ToArray();

            IEnumerable <PropertyInstance[]> propertyCombinations = propertyMatrix.ColumnCombinations(0, 1, 6);

            int count = 0;

            foreach (PropertyInstance[] propertyCombination in propertyCombinations)
            {
                // build the entity type, add it to the model
                EdmEntityType      generatedEntityType = null;
                string             typeName            = "PGEntityType" + count;
                EdmEntityContainer container           = null;
                EdmEntitySet       entitySet           = null;
                if (model != null)
                {
                    // generate a new type with the auto-generated name, check that no type with this name exists and add the default key property to it.
                    Debug.Assert(model.FindDeclaredType(typeName) == null, "Entity type '" + typeName + "' already exists.");
                    generatedEntityType = new EdmEntityType("TestModel", typeName);
                    generatedEntityType.AddKeys(generatedEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
                    model.AddElement(generatedEntityType);
                    container = model.EntityContainer as EdmEntityContainer;

                    if (container == null)
                    {
                        container = new EdmEntityContainer("TestModel", "DefaultNamespace");
                        model.AddElement(container);
                    }

                    entitySet = container.AddEntitySet(typeName, generatedEntityType);
                }

                EntityInstance entityInstance = PayloadBuilder.Entity("TestModel." + typeName)
                                                .Property("Id", PayloadBuilder.PrimitiveValue(count).WithTypeAnnotation(EdmCoreModel.Instance.GetInt32(false)));

                for (int i = 0; i < propertyCombination.Length; ++i)
                {
                    PropertyInstance currentProperty = propertyCombination[i];
                    entityInstance.Add(currentProperty);

                    if (model != null)
                    {
                        if (entitySet == null)
                        {
                            entitySet = container.FindEntitySet(typeName) as EdmEntitySet;
                        }

                        switch (currentProperty.ElementType)
                        {
                        case ODataPayloadElementType.ComplexProperty:
                            ComplexProperty complexProperty = (ComplexProperty)currentProperty;
                            generatedEntityType.AddStructuralProperty(complexProperty.Name,
                                                                      complexProperty.Value.GetAnnotation <EntityModelTypeAnnotation>().EdmModelType);
                            break;

                        case ODataPayloadElementType.PrimitiveProperty:
                            PrimitiveProperty primitiveProperty = (PrimitiveProperty)currentProperty;
                            if (primitiveProperty.Value == null)
                            {
                                generatedEntityType.AddStructuralProperty(
                                    primitiveProperty.Name,
                                    PayloadBuilder.PrimitiveValueType(null));
                            }
                            else
                            {
                                generatedEntityType.AddStructuralProperty(primitiveProperty.Name,
                                                                          primitiveProperty.Value.GetAnnotation <EntityModelTypeAnnotation>().EdmModelType);
                            }
                            break;

                        case ODataPayloadElementType.NamedStreamInstance:
                            NamedStreamInstance streamProperty = (NamedStreamInstance)currentProperty;
                            generatedEntityType.AddStructuralProperty(streamProperty.Name, EdmPrimitiveTypeKind.Stream);
                            break;

                        case ODataPayloadElementType.EmptyCollectionProperty:
                            throw new NotImplementedException();

                        case ODataPayloadElementType.NavigationPropertyInstance:
                            NavigationPropertyInstance navigationProperty = (NavigationPropertyInstance)currentProperty;
                            var navProperty = generatedEntityType.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
                            {
                                ContainsTarget     = false,
                                Name               = navigationProperty.Name,
                                Target             = generatedEntityType,
                                TargetMultiplicity = EdmMultiplicity.One
                            });
                            entitySet.AddNavigationTarget(navProperty, entitySet);
                            break;

                        case ODataPayloadElementType.ComplexMultiValueProperty:
                            ComplexMultiValueProperty complexMultiValueProperty = (ComplexMultiValueProperty)currentProperty;
                            generatedEntityType.AddStructuralProperty(complexMultiValueProperty.Name,
                                                                      complexMultiValueProperty.Value.GetAnnotation <EntityModelTypeAnnotation>().EdmModelType);
                            break;

                        case ODataPayloadElementType.PrimitiveMultiValueProperty:
                            PrimitiveMultiValueProperty primitiveMultiValueProperty = (PrimitiveMultiValueProperty)currentProperty;
                            generatedEntityType.AddStructuralProperty(primitiveMultiValueProperty.Name,
                                                                      primitiveMultiValueProperty.Value.GetAnnotation <EntityModelTypeAnnotation>().EdmModelType);
                            break;

                        default:
                            throw new NotSupportedException("Unsupported element type found : " + propertyCombination[i].ElementType);
                        }
                    }
                }

                if (generatedEntityType != null)
                {
                    entityInstance.AddAnnotation(new EntityModelTypeAnnotation(generatedEntityType.ToTypeReference(true)));
                }

                yield return(new PayloadTestDescriptor()
                {
                    PayloadElement = entityInstance, PayloadEdmModel = model
                });

                count++;
            }
        }
        private static EdmModel GetModel()
        {
            var model = new EdmModel();

            var person   = new EdmEntityType("DefaultNs", "Person");
            var entityId = person.AddStructuralProperty("UserName", EdmCoreModel.Instance.GetString(false));

            person.AddKeys(entityId);

            var employee = new EdmEntityType("DefaultNs", "Employee", person);

            var city   = new EdmEntityType("DefaultNs", "City");
            var cityId = city.AddStructuralProperty("ZipCode", EdmCoreModel.Instance.GetInt32(false));

            city.AddKeys(cityId);

            var personCity   = new EdmEntityType("DefaultNs", "PersonCity");
            var personcityId = personCity.AddStructuralProperty("ZipCode", EdmCoreModel.Instance.GetInt32(false));

            personCity.AddKeys(personcityId);

            var city3   = new EdmEntityType("DefaultNs", "City3");
            var cityId3 = city.AddStructuralProperty("ZipCode3", EdmCoreModel.Instance.GetInt32(false));

            city.AddKeys(cityId3);

            var region   = new EdmEntityType("DefaultNs", "Region");
            var regionId = region.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(false));

            region.AddKeys(regionId);

            var cityRegion = city.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo()
            {
                Name               = "Region",
                Target             = region,
                TargetMultiplicity = EdmMultiplicity.One,
            });

            var complex = new EdmComplexType("DefaultNs", "Address");

            complex.AddStructuralProperty("Road", EdmCoreModel.Instance.GetString(false));

            var subcomplex = new EdmComplexType("DefaultNs", "SubAddress");

            subcomplex.AddStructuralProperty("SubRoad", EdmCoreModel.Instance.GetString(false));

            complex.AddStructuralProperty("SubAddress", new EdmComplexTypeReference(subcomplex, false));

            var navP = complex.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo()
            {
                Name               = "City",
                Target             = city,
                TargetMultiplicity = EdmMultiplicity.One,
            });

            var navP3 = complex.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo()
            {
                Name               = "City3",
                Target             = city3,
                TargetMultiplicity = EdmMultiplicity.One,
            });


            var derivedComplex = new EdmComplexType("DefaultNs", "WorkAddress", complex);
            var navP2          = derivedComplex.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo()
            {
                Name               = "City2",
                Target             = city,
                TargetMultiplicity = EdmMultiplicity.One,
            });

            complex.AddStructuralProperty("WorkAddress", new EdmComplexTypeReference(complex, false));

            person.AddStructuralProperty("Address", new EdmComplexTypeReference(complex, false));
            person.AddStructuralProperty("Addresses", new EdmCollectionTypeReference(new EdmCollectionType(new EdmComplexTypeReference(complex, false))));
            var navP4 = person.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo()
            {
                Name               = "PersonCity",
                Target             = personCity,
                TargetMultiplicity = EdmMultiplicity.One,
            });

            model.AddElement(person);
            model.AddElement(employee);
            model.AddElement(city);
            model.AddElement(personCity);
            model.AddElement(city3);
            model.AddElement(region);
            model.AddElement(complex);
            model.AddElement(derivedComplex);

            var entityContainer = new EdmEntityContainer("DefaultNs", "Container");

            model.AddElement(entityContainer);
            EdmEntitySet people  = new EdmEntitySet(entityContainer, "People", person);
            EdmEntitySet cities  = new EdmEntitySet(entityContainer, "City", city);
            EdmEntitySet pcities = new EdmEntitySet(entityContainer, "PersonCity", personCity);
            EdmEntitySet regions = new EdmEntitySet(entityContainer, "Regions", region);

            people.AddNavigationTarget(navP, cities, new EdmPathExpression("Address/City"));
            people.AddNavigationTarget(navP3, cities, new EdmPathExpression("Address/City3"));
            people.AddNavigationTarget(navP, cities, new EdmPathExpression("Addresses/City"));
            people.AddNavigationTarget(navP2, cities, new EdmPathExpression("Address/WorkAddress/DefaultNs.WorkAddress/City2"));
            people.AddNavigationTarget(navP4, pcities, new EdmPathExpression("PersonCity"));


            cities.AddNavigationTarget(cityRegion, regions);
            entityContainer.AddElement(people);
            entityContainer.AddElement(cities);
            entityContainer.AddElement(pcities);

            return(model);
        }
        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))));
            model.AddElement(entityType);

            EdmEntityContainer container = new EdmEntityContainer("EntityNs", "MyContainer_sub");
            EdmEntitySet       entitySet = new EdmEntitySet(container, "MyTestEntitySet", entityType);

            model.AddElement(container);

            ODataEntry entry = new ODataEntry()
            {
                Id         = new Uri("http://mytest"),
                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
                                },
                            }
                        }
                    }
                },
            };

            string outputPayload   = this.WriterEntry(TestUtils.WrapReferencedModelsToMainModel("EntityNs", "MyContainer", model), entry, entitySet, entityType);
            string expectedPayload =
                "{" +
                "\"@odata.context\":\"http://www.example.com/$metadata#MyTestEntitySet/$entity\"," +
                "\"@odata.id\":\"http://mytest/\"," +
                "\"LongId\":12," +
                "\"FloatId\":34.98," +
                "\"DoubleId\":56.01," +
                "\"DecimalId\":78.62," +
                "\"BoolValue1\":true," +
                "\"BoolValue2\":false," +
                "\"LongNumbers\":[" +
                "0," +
                "-9223372036854775808," +
                "9223372036854775807" +
                "]," +
                "\"FloatNumbers\":[" +
                "1," +
                "-3.40282347E+38," +
                "3.40282347E+38," +
                "\"INF\"," +
                "\"-INF\"," +
                "\"NaN\"" +
                "]," +
                "\"DoubleNumbers\":[" +
                "-1.0," +
                "-1.7976931348623157E+308," +
                "1.7976931348623157E+308," +
                "\"INF\"," +
                "\"-INF\"," +
                "\"NaN\"" +
                "]," +
                "\"DecimalNumbers\":[" +
                "0," +
                "-79228162514264337593543950335," +
                "79228162514264337593543950335" +
                "]," +
                "\"ComplexProperty\":{" +
                "\"CLongId\":1," +
                "\"CFloatId\":-1," +
                "\"CDoubleId\":1.0," +
                "\"CDecimalId\":1.0}" +
                "}";

            outputPayload.Should().Be(expectedPayload);
        }
Ejemplo n.º 30
0
        public void ReadingComplexInheritInCollection()
        {
            EdmModel              model      = new EdmModel();
            EdmEntityType         entityType = new EdmEntityType("NS", "MyTestEntity");
            EdmStructuralProperty key        = entityType.AddStructuralProperty("LongId", EdmPrimitiveTypeKind.Int64, false);

            entityType.AddKeys(key);

            EdmComplexType complexType = new EdmComplexType("NS", "MyComplexType");

            complexType.AddStructuralProperty("CLongId", EdmPrimitiveTypeKind.Int64, false);

            EdmComplexType derivedComplexType = new EdmComplexType("NS", "MyDerivedComplexType", complexType, false);

            derivedComplexType.AddStructuralProperty("CFloatId", EdmPrimitiveTypeKind.Single, false);

            model.AddElement(complexType);
            model.AddElement(derivedComplexType);

            EdmComplexTypeReference complexTypeRef = new EdmComplexTypeReference(complexType, true);

            entityType.AddStructuralProperty("ComplexCollectionProperty", new EdmCollectionTypeReference(new EdmCollectionType(complexTypeRef)));
            model.AddElement(entityType);

            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://MyTestEntity\"," +
                "\"LongId\":\"12\"," +
                "\"ComplexCollectionProperty\":[{\"@odata.type\":\"#NS.MyDerivedComplexType\",\"CLongId\":\"1\",\"CFloatId\":1},{\"CLongId\":\"1\"},{\"CLongId\":\"1\",\"CFloatId\":1,\"@odata.type\":\"#NS.MyDerivedComplexType\"}]" +
                "}";

            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,
                    "ComplexCollectionProperty",
                    StringComparison.OrdinalIgnoreCase)).Value.As <ODataCollectionValue>();
            var list = new List <int?>();

            Boolean derived = true;

            foreach (var val in intCollection.Items)
            {
                var complextProperty = val as ODataComplexValue;
                complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CLongId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(1L, "value should be in correct type.");
                if (derived)
                {
                    complextProperty.Properties.FirstOrDefault(s => string.Equals(s.Name, "CFloatId", StringComparison.OrdinalIgnoreCase)).Value.ShouldBeEquivalentTo(1.0F, "value should be in correct type.");
                }
                derived = false;
            }
        }