Esempio n. 1
0
        public void WritingMultipleInstanceAnnotationInComplexValueShouldWrite()
        {
            var complexType = new EdmComplexType("TestNamespace", "Address");

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

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

            result.Should().Contain("\"@Annotation.1\":true,\"@Annotation.2\":123,\"@Annotation.3\":\"annotation\"");
        }
Esempio n. 2
0
        static ODataEntityReferenceLinksTests()
        {
            EdmModel       tmpModel    = new EdmModel();
            EdmComplexType complexType = new EdmComplexType("TestNamespace", "TestComplexType");

            complexType.AddProperty(new EdmStructuralProperty(complexType, "StringProperty", EdmCoreModel.Instance.GetString(false)));
            tmpModel.AddElement(complexType);

            EntityType = new EdmEntityType("TestNamespace", "TestEntityType");
            tmpModel.AddElement(EntityType);
            var keyProperty = new EdmStructuralProperty(EntityType, "ID", EdmCoreModel.Instance.GetInt32(false));

            EntityType.AddKeys(new IEdmStructuralProperty[] { keyProperty });
            EntityType.AddProperty(keyProperty);

            var defaultContainer = new EdmEntityContainer("TestNamespace", "DefaultContainer_sub");

            tmpModel.AddElement(defaultContainer);
            EntitySet = new EdmEntitySet(defaultContainer, "Customers", EntityType);
            defaultContainer.AddElement(EntitySet);

            EdmModel = TestUtils.WrapReferencedModelsToMainModel("TestNamespace", "DefaultContainer", tmpModel);
            MessageReaderSettingsReadAndValidateCustomInstanceAnnotations = new ODataMessageReaderSettings {
                ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*")
            };
        }
Esempio n. 3
0
        private ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, IEdmModel model, IJsonWriter jsonWriter, ODataMessageWriterSettings settings = null)
        {
            if (settings == null)
            {
                settings = new ODataMessageWriterSettings {
                    Version = ODataVersion.V4
                };
                settings.SetServiceDocumentUri(new Uri("http://example.com/"));
                settings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");
            }

            var messageInfo = new ODataMessageInfo
            {
                MessageStream = new NonDisposingStream(stream),
                MediaType     = new ODataMediaType("application", "json"),
                Encoding      = Encoding.UTF8,
                IsResponse    = true,
                IsAsync       = false,
                Model         = model,
                Container     =
                    ContainerBuilderHelper.BuildContainer(
                        builder =>
                        builder.AddService <IJsonWriterFactory>(ServiceLifetime.Singleton, sp => new MockJsonWriterFactory(jsonWriter))),
            };

            return(new ODataJsonLightOutputContext(messageInfo, settings));
        }
Esempio n. 4
0
        public ODataJsonLightResourceSerializerTests()
        {
            this.model = new EdmModel();

            this.categoryEntityType = new EdmEntityType("NS", "Category", /* baseType */ null, /* isAbstract */ false, /* isOpen */ true, /* hasStream */ true);
            this.productEntityType  = new EdmEntityType("NS", "Product");

            this.categoryEntityType.AddKeys(this.categoryEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
            this.categoryEntityType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            this.categoryEntityType.AddStructuralProperty("BestSeller", new EdmEntityTypeReference(this.productEntityType, true));

            this.productEntityType.AddKeys(this.productEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
            this.productEntityType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            this.productEntityType.AddStructuralProperty("Category", new EdmEntityTypeReference(this.categoryEntityType, true));

            this.model.AddElement(this.categoryEntityType);
            this.model.AddElement(this.productEntityType);

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

            this.model.AddElement(entityContainer);

            this.categoriesEntitySet = new EdmEntitySet(entityContainer, "Categories", this.categoryEntityType, true);

            this.stream = new MemoryStream();
            this.messageWriterSettings = new ODataMessageWriterSettings
            {
                EnableMessageStreamDisposal = false,
                Version = ODataVersion.V4,
                ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*")
            };

            this.messageWriterSettings.SetServiceDocumentUri(new Uri(ServiceUri));
        }
        private static ODataJsonLightOutputContext CreateJsonLightOutputContext(
            MemoryStream stream,
            bool writingResponse = true,
            bool synchronous     = true,
            bool use6x           = false)
        {
            var messageInfo = new ODataMessageInfo
            {
                MessageStream = new NonDisposingStream(stream),
                MediaType     = new ODataMediaType("application", "json"),
                Encoding      = Encoding.UTF8,
                IsResponse    = writingResponse,
                IsAsync       = !synchronous,
                Model         = EdmCoreModel.Instance
            };

            var settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4
            };

            settings.SetServiceDocumentUri(new Uri("http://odata.org/test"));
            settings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");

            if (use6x)
            {
                settings.LibraryCompatibility = ODataLibraryCompatibility.Version6;
            }

            return(new ODataJsonLightOutputContext(messageInfo, settings));
        }
Esempio n. 6
0
        public void WritingMultipleInstanceAnnotationInResourceValueShouldWrite(string filter, string expect)
        {
            var complexType = new EdmComplexType("NS", "Address");

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

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

            Assert.Equal(expect, result);
        }
Esempio n. 7
0
        public void CreateInstanceAnnotationsFilterShouldTranslateFilterStringToFunc()
        {
            Func <string, bool> filter = ODataUtils.CreateAnnotationFilter("*,-ns.*");

            filter.Should().NotBeNull();
            filter("ns.name").Should().BeFalse();
            filter("foo.bar").Should().BeTrue();
        }
Esempio n. 8
0
        public void CreateInstanceAnnotationsFilterShouldTranslateFilterStringToFunc()
        {
            Func <string, bool> filter = ODataUtils.CreateAnnotationFilter("*,-ns.*");

            Assert.NotNull(filter);
            Assert.False(filter("ns.name"));
            Assert.True(filter("foo.bar"));
        }
        public void CopyConstructorShouldCopyAnnotationFilter()
        {
            ODataMessageReaderSettings testSubject = new ODataMessageReaderSettings();

            testSubject.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("namespace.*");
            var copy = testSubject.Clone();

            Assert.Same(testSubject.ShouldIncludeAnnotation, copy.ShouldIncludeAnnotation);
        }
Esempio n. 10
0
        public void CopyConstructorShouldCopyAnnotationFilter()
        {
            ODataMessageReaderSettings testSubject = new ODataMessageReaderSettings();

            testSubject.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("namespace.*");
            var copy = new ODataMessageReaderSettings(testSubject);

            copy.ShouldIncludeAnnotation.Should().BeSameAs(testSubject.ShouldIncludeAnnotation);
        }
        public void WritingResourceValueAndNestedResourceValueWithSimilarPropertiesShouldWrite()
        {
            var complexType = new EdmComplexType("NS", "Address");

            complexType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            complexType.AddStructuralProperty("City", EdmPrimitiveTypeKind.String);
            model.AddElement(complexType);

            var entityType = new EdmEntityType("NS", "Customer");

            entityType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            entityType.AddStructuralProperty("Location", new EdmComplexTypeReference(complexType, false));
            model.AddElement(entityType);

            settings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");
            var result = this.SetupSerializerAndRunTest(serializer =>
            {
                var resourceValue = new ODataResourceValue
                {
                    TypeName   = "NS.Customer",
                    Properties = new[]
                    {
                        new ODataProperty {
                            Name = "Name", Value = "MyName"
                        },
                        new ODataProperty {
                            Name = "Location", Value = new ODataResourceValue
                            {
                                TypeName   = "NS.Address",
                                Properties = new [] {
                                    new ODataProperty {
                                        Name = "Name", Value = "AddressName"
                                    },
                                    new ODataProperty {
                                        Name = "City", Value = "MyCity"
                                    }
                                }
                            }
                        }
                    }
                };

                var entityTypeRef = new EdmEntityTypeReference(entityType, false);
                serializer.WriteResourceValue(resourceValue, entityTypeRef, false, serializer.GetDuplicatePropertyNameChecker());
            });

            Assert.Equal(@"{""Name"":""MyName"",""Location"":{""Name"":""AddressName"",""City"":""MyCity""}}", result);
        }
Esempio n. 12
0
        public void Init()
        {
            model = new EdmModel();
            EdmComplexType complexType = new EdmComplexType("ns", "complex");

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

            this.stream   = new MemoryStream();
            this.settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4, ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*")
            };
            this.settings.SetServiceDocumentUri(ServiceDocumentUri);
            this.serializer = new ODataAtomPropertyAndValueSerializer(this.CreateAtomOutputContext(model, this.stream));
            this.instanceAnnotationWriteTracker = new InstanceAnnotationWriteTracker();
        }
 public ODataJsonLightOutputContextTests()
 {
     InitializeEdmModel();
     this.stream = new MemoryStream();
     this.messageWriterSettings = new ODataMessageWriterSettings {
         Version = ODataVersion.V4
     };
     this.messageWriterSettings.SetServiceDocumentUri(new Uri(ServiceUri));
     this.messageWriterSettings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");
     this.nullReferenceError = new ODataError
     {
         ErrorCode           = "NRE",
         Message             = "Object reference not set to an instance of an object",
         InstanceAnnotations = new List <ODataInstanceAnnotation>
         {
             new ODataInstanceAnnotation("Is.Error", new ODataPrimitiveValue(true))
         }
     };
 }
Esempio n. 14
0
        private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, bool writingResponse = true, bool synchronous = true)
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4
            };

            settings.SetServiceDocumentUri(new Uri("http://odata.org/test"));
            settings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");
            return(new ODataJsonLightOutputContext(
                       ODataFormat.Json,
                       new NonDisposingStream(stream),
                       new ODataMediaType("application", "json"),
                       Encoding.UTF8,
                       settings,
                       writingResponse,
                       synchronous,
                       EdmCoreModel.Instance,
                       /*urlResolver*/ null));
        }
        static ODataJsonLightEntryAndFeedDeserializerTests()
        {
            EdmModel       tmpModel    = new EdmModel();
            EdmComplexType complexType = new EdmComplexType("TestNamespace", "TestComplexType");

            complexType.AddProperty(new EdmStructuralProperty(complexType, "StringProperty", EdmCoreModel.Instance.GetString(false)));
            tmpModel.AddElement(complexType);

            EntityType = new EdmEntityType("TestNamespace", "TestEntityType");
            tmpModel.AddElement(EntityType);
            var keyProperty = new EdmStructuralProperty(EntityType, "ID", EdmCoreModel.Instance.GetInt32(false));

            EntityType.AddKeys(new IEdmStructuralProperty[] { keyProperty });
            EntityType.AddProperty(keyProperty);

            var defaultContainer = new EdmEntityContainer("TestNamespace", "DefaultContainer_sub");

            tmpModel.AddElement(defaultContainer);
            EntitySet = new EdmEntitySet(defaultContainer, "TestEntitySet", EntityType);
            defaultContainer.AddElement(EntitySet);

            Action = new EdmAction("TestNamespace", "DoSomething", null, true, null);
            Action.AddParameter("p1", new EdmEntityTypeReference(EntityType, false));
            tmpModel.AddElement(Action);

            ActionImport = defaultContainer.AddActionImport("DoSomething", Action);

            var serviceOperationFunction = new EdmFunction("TestNamespace", "ServiceOperation", EdmCoreModel.Instance.GetInt32(true));

            defaultContainer.AddFunctionImport("ServiceOperation", serviceOperationFunction);
            tmpModel.AddElement(serviceOperationFunction);

            tmpModel.AddElement(new EdmTerm("custom", "DateTimeOffsetAnnotation", EdmPrimitiveTypeKind.DateTimeOffset));
            tmpModel.AddElement(new EdmTerm("custom", "DateAnnotation", EdmPrimitiveTypeKind.Date));
            tmpModel.AddElement(new EdmTerm("custom", "TimeOfDayAnnotation", EdmPrimitiveTypeKind.TimeOfDay));

            EdmModel = TestUtils.WrapReferencedModelsToMainModel("TestNamespace", "DefaultContainer", tmpModel);
            MessageReaderSettingsReadAndValidateCustomInstanceAnnotations = new ODataMessageReaderSettings {
                ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*")
            };
            MessageReaderSettingsIgnoreInstanceAnnotations = new ODataMessageReaderSettings();
        }
        public JsonLightInstanceAnnotationWriterTests()
        {
            this.jsonWriter = new MockJsonWriter
            {
                WriteNameVerifier  = name => { },
                WriteValueVerifier = str => { }
            };

            this.referencedModel = new EdmModel();
            model = TestUtils.WrapReferencedModelsToMainModel(referencedModel);

            // Version will be V3+ in production since it's JSON Light only
            this.valueWriter = new MockJsonLightValueSerializer(jsonWriter, model)
            {
                Settings = new ODataMessageWriterSettings {
                    Version = ODataVersion.V4, ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*")
                }
            };
            this.jsonLightInstanceAnnotationWriter = new JsonLightInstanceAnnotationWriter(this.valueWriter, new JsonMinimalMetadataTypeNameOracle());
        }
Esempio n. 17
0
        private ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream)
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4
            };

            settings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");
            settings.SetServiceDocumentUri(new Uri("http://example.com/"));

            return(new ODataJsonLightOutputContext(
                       ODataFormat.Json,
                       new NonDisposingStream(stream),
                       new ODataMediaType("application", "json"),
                       Encoding.UTF8,
                       settings,
                       /*writingResponse*/ true,
                       /*synchronous*/ true,
                       this.model,
                       /*urlResolver*/ null));
        }
Esempio n. 18
0
        private ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream)
        {
            var settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4
            };

            settings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");
            settings.SetServiceDocumentUri(new Uri("http://example.com/"));

            var messageInfo = new ODataMessageInfo
            {
                MessageStream = new NonDisposingStream(stream),
                MediaType     = new ODataMediaType("application", "json"),
                Encoding      = Encoding.UTF8,
                IsResponse    = true,
                IsAsync       = false,
                Model         = this.model
            };

            return(new ODataJsonLightOutputContext(messageInfo, settings));
        }
Esempio n. 19
0
        public async Task ReadParameterWithCustomInstanceAnnotationAsync()
        {
            this.messageReaderSettings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");

            var setDiscountAction = new EdmAction("NS", "SetDiscount", null);

            setDiscountAction.AddParameter("discount", EdmCoreModel.Instance.GetDouble(false));
            this.model.AddElement(setDiscountAction);

            var payload = "{\"@custom.annotation\":\"foobar\",\"discount\":1.70}";

            await SetupJsonLightParameterDeserializerAndRunTestAsync(
                payload,
                async (jsonLightParameterDeserializer) =>
            {
                var parameterRead = await jsonLightParameterDeserializer.ReadNextParameterAsync(this.propertyAndAnnotationCollector);

                Assert.True(parameterRead);
            },
                setDiscountAction);
        }
Esempio n. 20
0
        public void WritingCollectionResourceValueWithPropertiesShouldWrite()
        {
            var complexType = new EdmComplexType("NS", "Address");

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

            settings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");
            var result = this.SetupSerializerAndRunTest(serializer =>
            {
                var resourceValue1 = new ODataResourceValue
                {
                    TypeName   = "NS.Address",
                    Properties = new[] { new ODataProperty {
                                             Name = "City", Value = "MyCity1"
                                         } }
                };

                var resourceValue2 = new ODataResourceValue
                {
                    TypeName   = "NS.Address",
                    Properties = new[] { new ODataProperty {
                                             Name = "City", Value = "MyCity2"
                                         } }
                };

                var collectionValue = new ODataCollectionValue
                {
                    TypeName = "Collection(NS.Address)",
                    Items    = new[] { resourceValue1, resourceValue2 }
                };

                var collectionTypeRef = new EdmCollectionTypeReference(new EdmCollectionType(new EdmComplexTypeReference(complexType, false)));
                serializer.WriteCollectionValue(collectionValue, collectionTypeRef, null, false, false, false);
            });

            Assert.Equal(@"[{""City"":""MyCity1""},{""City"":""MyCity2""}]", result);
        }
        public void Init()
        {
            EdmModel model = new EdmModel();

            EdmComplexType complex1 = new EdmComplexType("ns", "complex1");

            complex1.AddProperty(new EdmStructuralProperty(complex1, "p1", EdmCoreModel.Instance.GetInt32(isNullable: false)));
            model.AddElement(complex1);

            EdmComplexType complex2 = new EdmComplexType("ns", "complex2");

            complex2.AddProperty(new EdmStructuralProperty(complex2, "p1", EdmCoreModel.Instance.GetInt32(isNullable: false)));
            model.AddElement(complex2);

            EdmComplexTypeReference    complex2Reference                = new EdmComplexTypeReference(complex2, isNullable: false);
            EdmCollectionType          primitiveCollectionType          = new EdmCollectionType(EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Int32, isNullable: false));
            EdmCollectionType          complexCollectionType            = new EdmCollectionType(complex2Reference);
            EdmCollectionTypeReference primitiveCollectionTypeReference = new EdmCollectionTypeReference(primitiveCollectionType);
            EdmCollectionTypeReference complexCollectionTypeReference   = new EdmCollectionTypeReference(complexCollectionType);

            model.AddElement(new EdmTerm("custom", "int", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Int32, isNullable: false)));
            model.AddElement(new EdmTerm("custom", "string", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.String, isNullable: false)));
            model.AddElement(new EdmTerm("custom", "double", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Double, isNullable: false)));
            model.AddElement(new EdmTerm("custom", "bool", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Boolean, isNullable: true)));
            model.AddElement(new EdmTerm("custom", "decimal", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Decimal, isNullable: false)));
            model.AddElement(new EdmTerm("custom", "timespan", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Duration, isNullable: false)));
            model.AddElement(new EdmTerm("custom", "guid", EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Guid, isNullable: false)));
            model.AddElement(new EdmTerm("custom", "complex", complex2Reference));
            model.AddElement(new EdmTerm("custom", "primitiveCollection", primitiveCollectionTypeReference));
            model.AddElement(new EdmTerm("custom", "complexCollection", complexCollectionTypeReference));

            this.stream   = new MemoryStream();
            this.settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4, ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*")
            };
            this.settings.SetServiceDocumentUri(ServiceDocumentUri);
            this.serializer = new ODataAtomPropertyAndValueSerializer(this.CreateAtomOutputContext(model, this.stream));
        }
Esempio n. 22
0
        public void WritingInstanceAnnotationInResourceValueShouldWrite()
        {
            var complexType = new EdmComplexType("TestNamespace", "Address");

            model.AddElement(complexType);
            settings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");
            var result = this.SetupSerializerAndRunTest(serializer =>
            {
                var resourceValue = new ODataResourceValue
                {
                    TypeName            = "TestNamespace.Address",
                    InstanceAnnotations = new Collection <ODataInstanceAnnotation>
                    {
                        new ODataInstanceAnnotation("Is.ReadOnly", new ODataPrimitiveValue(true))
                    }
                };

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

            Assert.Equal(@"{""@Is.ReadOnly"":true}", result);
        }
        private static string WriteInstanceAnnotation(ODataInstanceAnnotation instanceAnnotation, IEdmModel model)
        {
            var stringWriter  = new StringWriter();
            var outputContext = new ODataJsonLightOutputContext(
                ODataFormat.Json,
                stringWriter,
                new ODataMessageWriterSettings {
                Version = ODataVersion.V4, ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*")
            },
                model);

            var valueSerializer = new ODataJsonLightValueSerializer(outputContext);

            // The JSON Writer will complain if there is no active scope, so start an object scope.
            valueSerializer.JsonWriter.StartObjectScope();
            var instanceAnnotationWriter = new JsonLightInstanceAnnotationWriter(valueSerializer, new JsonMinimalMetadataTypeNameOracle());

            // The method under test.
            instanceAnnotationWriter.WriteInstanceAnnotation(instanceAnnotation);

            valueSerializer.JsonWriter.EndObjectScope();
            return(stringWriter.ToString());
        }
Esempio n. 24
0
        private ODataJsonLightInputContext CreateJsonLightInputContext(
            string payload,
            IEdmModel model,
            bool isAsync    = false,
            bool isResponse = true)
        {
            this.messageInfo = new ODataMessageInfo
            {
                IsResponse = isResponse,
                MediaType  = new ODataMediaType("application", "json", new KeyValuePair <string, string>("odata.streaming", "true")),
                IsAsync    = isAsync,
                Model      = this.model,
            };

            this.messageReaderSettings = new ODataMessageReaderSettings();
            messageReaderSettings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");
            payloadKindDetectionInfo = new ODataPayloadKindDetectionInfo(this.messageInfo, this.messageReaderSettings);

            return(new ODataJsonLightInputContext(
                       new StringReader(payload),
                       messageInfo,
                       messageReaderSettings));
        }
        private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, IEdmModel userModel, bool fullMetadata = false, ODataUri uri = null)
        {
            var settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4, ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*")
            };

            settings.SetServiceDocumentUri(new Uri("http://host/service"));
            if (uri != null)
            {
                settings.ODataUri = uri;
            }

            IEnumerable <KeyValuePair <string, string> > parameters;

            if (fullMetadata)
            {
                parameters = new[] { new KeyValuePair <string, string>("odata.metadata", "full") };
            }
            else
            {
                parameters = new List <KeyValuePair <string, string> >();
            }

            var mediaType = new ODataMediaType("application", "json", parameters);

            var messageInfo = new ODataMessageInfo
            {
                MessageStream = new NonDisposingStream(stream),
                MediaType     = mediaType,
                Encoding      = Encoding.UTF8,
                IsResponse    = true,
                IsAsync       = false,
                Model         = userModel ?? EdmCoreModel.Instance
            };

            return(new ODataJsonLightOutputContext(messageInfo, settings));
        }
Esempio n. 26
0
        private ODataJsonLightInputContext CreateJsonLightInputcontext(string payload, bool isAsync = false, bool isResponse = true)
        {
            var messageInfo = new ODataMessageInfo
            {
                MediaType = new ODataMediaType("application", "json"),
#if NETCOREAPP1_1
                Encoding = Encoding.GetEncoding(0),
#else
                Encoding = Encoding.Default,
#endif
                IsResponse = isResponse,
                IsAsync    = isAsync,
                Model      = new EdmModel()
            };

            var messageReaderSettings = new ODataMessageReaderSettings();

            messageReaderSettings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");

            return(new ODataJsonLightInputContext(
                       new StringReader(payload),
                       messageInfo,
                       messageReaderSettings));
        }
        private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, bool writingResponse = true, IEdmModel userModel = null, Uri serviceDocumentUri = null)
        {
            var mediaType   = new ODataMediaType("application", "json", new KeyValuePair <string, string>("odata.metadata", "full"));
            var messageInfo = new ODataMessageInfo
            {
                MessageStream = new NonDisposingStream(stream),
                MediaType     = mediaType,
                Encoding      = Encoding.UTF8,
                IsResponse    = writingResponse,
                IsAsync       = false,
                Model         = userModel ?? EdmCoreModel.Instance
            };

            var settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4, ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*")
            };

            if (serviceDocumentUri != null)
            {
                settings.SetServiceDocumentUri(serviceDocumentUri);
            }

            return(new ODataJsonLightOutputContext(messageInfo, settings));
        }
Esempio n. 28
0
        private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, IEdmModel userModel, ODataUri uri = null)
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4, AutoComputePayloadMetadataInJson = true, ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*")
            };

            settings.SetServiceDocumentUri(new Uri("http://host/service"));
            if (uri != null)
            {
                settings.ODataUri = uri;
            }

            ODataMediaType mediaType = new ODataMediaType("application", "json", new List <KeyValuePair <string, string> >());

            //mediaType.Parameters.Add(new KeyValuePair<string, string>("odata.metadata", "full"));
            return(new ODataJsonLightOutputContext(
                       ODataFormat.Json,
                       new NonDisposingStream(stream),
                       mediaType,
                       Encoding.UTF8,
                       settings,
                       /*writingResponse*/ true,
                       /*synchronous*/ true,
                       userModel ?? EdmCoreModel.Instance,
                       /*urlResolver*/ null));
        }
Esempio n. 29
0
        internal static object ReadFromStream(
#endif
            Type type,
            object defaultValue,
            IEdmModel model,
            ODataVersion version,
            Uri baseAddress,
            IWebApiRequestMessage internalRequest,
            Func <IODataRequestMessage> getODataRequestMessage,
            Func <IEdmTypeReference, ODataDeserializer> getEdmTypeDeserializer,
            Func <Type, ODataDeserializer> getODataPayloadDeserializer,
            Func <ODataDeserializerContext> getODataDeserializerContext,
            Action <IDisposable> registerForDisposeAction,
            Action <Exception> logErrorAction)
        {
            object result;

            IEdmTypeReference expectedPayloadType;
            ODataDeserializer deserializer = GetDeserializer(type, internalRequest.Context.Path, model, getEdmTypeDeserializer, getODataPayloadDeserializer, out expectedPayloadType);

            if (deserializer == null)
            {
                throw Error.Argument("type", SRResources.FormatterReadIsNotSupportedForType, type.FullName, typeof(ODataInputFormatterHelper).FullName);
            }

            try
            {
                ODataMessageReaderSettings oDataReaderSettings = internalRequest.ReaderSettings;
                oDataReaderSettings.BaseUri     = baseAddress;
                oDataReaderSettings.Validations = oDataReaderSettings.Validations & ~ValidationKinds.ThrowOnUndeclaredPropertyForNonOpenType;
                oDataReaderSettings.Version     = version;

                IODataRequestMessage oDataRequestMessage = getODataRequestMessage();

                string preferHeader     = RequestPreferenceHelpers.GetRequestPreferHeader(internalRequest.Headers);
                string annotationFilter = null;
                if (!String.IsNullOrEmpty(preferHeader))
                {
                    oDataRequestMessage.SetHeader(RequestPreferenceHelpers.PreferHeaderName, preferHeader);
                    annotationFilter = oDataRequestMessage.PreferHeader().AnnotationFilter;
                }

                if (annotationFilter != null)
                {
                    oDataReaderSettings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter(annotationFilter);
                }

                ODataMessageReader oDataMessageReader = new ODataMessageReader(oDataRequestMessage, oDataReaderSettings, model);
                registerForDisposeAction(oDataMessageReader);

                ODataPath path = internalRequest.Context.Path;
                ODataDeserializerContext readContext = getODataDeserializerContext();
                readContext.Path            = path;
                readContext.Model           = model;
                readContext.ResourceType    = type;
                readContext.ResourceEdmType = expectedPayloadType;

#if NETCORE
                result = await deserializer.ReadAsync(oDataMessageReader, type, readContext);
#else
                result = deserializer.Read(oDataMessageReader, type, readContext);
#endif
            }
            catch (Exception e)
            {
                logErrorAction(e);
                result = defaultValue;
            }

            return(result);
        }
Esempio n. 30
0
        private static ODataMessageReader CreateODataMessageReader(string payload, string contentType, bool isResponse, bool shouldReadAndValidateCustomInstanceAnnotations, bool enableReadingODataAnnotationWithoutPrefix = false)
        {
            var stream         = new MemoryStream(Encoding.UTF8.GetBytes(payload));
            var readerSettings = new ODataMessageReaderSettings {
                EnableMessageStreamDisposal = false
            };
            var container = ContainerBuilderHelper.BuildContainer(null);

            container.GetRequiredService <ODataSimplifiedOptions>().EnableReadingODataAnnotationWithoutPrefix =
                enableReadingODataAnnotationWithoutPrefix;
            ODataMessageReader messageReader;

            if (isResponse)
            {
                IODataResponseMessage responseMessage = new InMemoryMessage {
                    StatusCode = 200, Stream = stream, Container = container
                };
                responseMessage.SetHeader("Content-Type", contentType);
                if (shouldReadAndValidateCustomInstanceAnnotations)
                {
                    responseMessage.PreferenceAppliedHeader().AnnotationFilter = "*";
                }

                messageReader = new ODataMessageReader(responseMessage, readerSettings, Model);
            }
            else
            {
                IODataRequestMessage requestMessage = new InMemoryMessage {
                    Method = "GET", Stream = stream, Container = container
                };
                requestMessage.SetHeader("Content-Type", contentType);
                readerSettings.ShouldIncludeAnnotation = shouldReadAndValidateCustomInstanceAnnotations ? ODataUtils.CreateAnnotationFilter("*") : null;
                messageReader = new ODataMessageReader(requestMessage, readerSettings, Model);
            }

            return(messageReader);
        }