private string WriterEntry(IEdmModel userModel, ODataEntry entry, EdmEntitySet entitySet, IEdmEntityType entityType, bool fullMetadata = false)
        {
            var message = new InMemoryMessage()
            {
                Stream = new MemoryStream()
            };

            var writerSettings = new ODataMessageWriterSettings {
                DisableMessageStreamDisposal = true, AutoComputePayloadMetadataInJson = true
            };

            writerSettings.SetContentType(ODataFormat.Json);
            writerSettings.SetServiceDocumentUri(new Uri("http://www.example.com"));
            writerSettings.SetContentType(fullMetadata ?
                                          "application/json;odata.metadata=full;odata.streaming=false" :
                                          "application/json;odata.metadata=minimal;odata.streaming=false", "utf-8");

            using (var msgReader = new ODataMessageWriter((IODataResponseMessage)message, writerSettings, userModel))
            {
                var writer = msgReader.CreateODataEntryWriter(entitySet, entityType);
                writer.WriteStart(entry);
                writer.WriteEnd();
            }

            message.Stream.Seek(0, SeekOrigin.Begin);
            using (StreamReader reader = new StreamReader(message.Stream))
            {
                return(reader.ReadToEnd());
            }
        }
        private ODataMessageWriterSettings GetWriterSettings()
        {
            var settings = new ODataMessageWriterSettings()
            {
                ODataUri = new ODataUri()
                {
                    RequestUri = new Uri(_session.Settings.UrlBase),
                },
                Indent = true,
                DisableMessageStreamDisposal = !IsBatch,
            };

            switch (_session.Settings.PayloadFormat)
            {
            case ODataPayloadFormat.Atom:
                settings.SetContentType(ODataFormat.Atom);
                break;

            case ODataPayloadFormat.Json:
            default:
                settings.SetContentType(ODataFormat.Json);
                break;
            }
            return(settings);
        }
        private static string WriteJsonLightEntryForUndeclared(bool isOpenType, Action <ODataWriter> writeAction, bool throwOnUndeclaredProperty = true)
        {
            EdmModel model = new EdmModel();

            AddAndGetComplexType(model);
            EdmEntityType entityType = AddAndGetEntityType(model);

            if (isOpenType)
            {
                entityType = AddAndGetOpenEntityType(model);
            }
            var entitySet = GetEntitySet(model, entityType);

            var requestUri = new Uri("http://temp.org/FakeSet('parent')");
            var odataUri   = new ODataUri {
                RequestUri = requestUri
            };

            odataUri.Path = new ODataUriParser(model, new Uri("http://temp.org/"), requestUri).ParsePath();

            var stream  = new MemoryStream();
            var message = new InMemoryMessage {
                Stream = stream
            };

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

            if (!throwOnUndeclaredProperty)
            {
                settings.Validations &= ~ValidationKinds.ThrowOnUndeclaredPropertyForNonOpenType;
            }
            settings.ODataUri = odataUri;
            settings.SetServiceDocumentUri(new Uri("http://temp.org"));

            settings.SetContentType(ODataFormat.Json);
            settings.SetContentType("application/json;odata.metadata=full", null);

            ODataMessageWriter messageWriter;

            messageWriter = new ODataMessageWriter((IODataResponseMessage)message, settings, model);
            ODataWriter writer = null;

            writer = messageWriter.CreateODataResourceWriter(entitySet, entityType);

            if (writeAction != null)
            {
                writeAction(writer);
            }

            writer.Flush();

            var actual = Encoding.UTF8.GetString(stream.ToArray());

            return(actual);
        }
        public void SetContentTypeTest()
        {
            settings.SetContentType("application/xml", null);
            ODataMessageWriterSettings copyOfSettings = settings.Clone();

            settings.Format.Should().BeNull();
            copyOfSettings.Format.Should().BeNull();
            settings.AcceptableMediaTypes.Should().Be("application/xml");
            copyOfSettings.AcceptableMediaTypes.Should().Be("application/xml");
            settings.AcceptableCharsets.Should().BeNull();
            copyOfSettings.AcceptableCharsets.Should().BeNull();

            settings.SetContentType("application/json", "utf8");
            copyOfSettings = settings.Clone();
            settings.Format.Should().BeNull();
            copyOfSettings.Format.Should().BeNull();
            settings.AcceptableMediaTypes.Should().Be("application/json");
            copyOfSettings.AcceptableMediaTypes.Should().Be("application/json");
            settings.AcceptableCharsets.Should().Be("utf8");
            copyOfSettings.AcceptableCharsets.Should().Be("utf8");

            settings.SetContentType(null, "utf8");
            copyOfSettings = settings.Clone();
            settings.Format.Should().BeNull();
            copyOfSettings.Format.Should().BeNull();
            settings.AcceptableMediaTypes.Should().BeNull();
            copyOfSettings.AcceptableMediaTypes.Should().BeNull();
            settings.AcceptableCharsets.Should().Be("utf8");
            copyOfSettings.AcceptableCharsets.Should().Be("utf8");

            settings.SetContentType(string.Empty, "utf8");
            copyOfSettings = settings.Clone();
            settings.Format.Should().BeNull();
            copyOfSettings.Format.Should().BeNull();
            settings.AcceptableMediaTypes.Should().BeEmpty();
            copyOfSettings.AcceptableMediaTypes.Should().BeEmpty();
            settings.AcceptableCharsets.Should().Be("utf8");
            copyOfSettings.AcceptableCharsets.Should().Be("utf8");

            settings.SetContentType("json", "utf8");
            copyOfSettings = settings.Clone();
            settings.Format.Should().BeNull();
            copyOfSettings.Format.Should().BeNull();
            settings.AcceptableMediaTypes.Should().Be("application/json");
            copyOfSettings.AcceptableMediaTypes.Should().Be("application/json");
            settings.AcceptableCharsets.Should().Be("utf8");
            copyOfSettings.AcceptableCharsets.Should().Be("utf8");
        }
Beispiel #5
0
        public void SetContentTypeTest()
        {
            settings.SetContentType("application/xml", null);
            ODataMessageWriterSettings copyOfSettings = settings.Clone();

            Assert.Null(settings.Format);
            Assert.Null(copyOfSettings.Format);
            Assert.Equal("application/xml", settings.AcceptableMediaTypes);
            Assert.Equal("application/xml", copyOfSettings.AcceptableMediaTypes);
            Assert.Null(settings.AcceptableCharsets);
            Assert.Null(copyOfSettings.AcceptableCharsets);

            settings.SetContentType("application/json", "utf8");
            copyOfSettings = settings.Clone();
            Assert.Null(settings.Format);
            Assert.Null(copyOfSettings.Format);
            Assert.Equal("application/json", settings.AcceptableMediaTypes);
            Assert.Equal("application/json", copyOfSettings.AcceptableMediaTypes);
            Assert.Equal("utf8", settings.AcceptableCharsets);
            Assert.Equal("utf8", copyOfSettings.AcceptableCharsets);

            settings.SetContentType(null, "utf8");
            copyOfSettings = settings.Clone();
            Assert.Null(settings.Format);
            Assert.Null(copyOfSettings.Format);
            Assert.Null(settings.AcceptableMediaTypes);
            Assert.Null(copyOfSettings.AcceptableMediaTypes);
            Assert.Equal("utf8", settings.AcceptableCharsets);
            Assert.Equal("utf8", copyOfSettings.AcceptableCharsets);

            settings.SetContentType(string.Empty, "utf8");
            copyOfSettings = settings.Clone();
            Assert.Null(settings.Format);
            Assert.Null(copyOfSettings.Format);
            Assert.Empty(settings.AcceptableMediaTypes);
            Assert.Empty(copyOfSettings.AcceptableMediaTypes);
            Assert.Equal("utf8", settings.AcceptableCharsets);
            Assert.Equal("utf8", copyOfSettings.AcceptableCharsets);

            settings.SetContentType("json", "utf8");
            copyOfSettings = settings.Clone();
            Assert.Null(settings.Format);
            Assert.Null(copyOfSettings.Format);
            Assert.Equal("application/json", settings.AcceptableMediaTypes);
            Assert.Equal("application/json", copyOfSettings.AcceptableMediaTypes);
            Assert.Equal("utf8", settings.AcceptableCharsets);
            Assert.Equal("utf8", copyOfSettings.AcceptableCharsets);
        }
        private ODataMessageWriterSettings GetAvroWriterSettings()
        {
            var settings = new ODataMessageWriterSettings();

            settings.SetContentType(AvroFormat.Avro);
            return(settings);
        }
Beispiel #7
0
        public void WriteTopLevelStringPropertyWithStringEscapeOnlyControlsOptionShouldWork()
        {
            var settings         = new ODataMessageWriterSettings();
            var containerBuilder = new Test.OData.DependencyInjection.TestContainerBuilder();

            containerBuilder.AddDefaultODataServices();
            containerBuilder.AddService <IJsonWriterFactory>(ServiceLifetime.Singleton, sp => new DefaultJsonWriterFactory(ODataStringEscapeOption.EscapeOnlyControls));

            settings.ODataUri.ServiceRoot = new Uri("http://host/service");
            settings.SetContentType(ODataFormat.Json);
            var model = new EdmModel();
            IODataRequestMessage request = new InMemoryMessage()
            {
                Stream    = new MemoryStream(),
                Container = containerBuilder.BuildContainer()
            };
            var    writer = new ODataMessageWriter(request, settings, model);
            Action write  = () => writer.WriteProperty(new ODataProperty()
            {
                Name  = "Name",
                Value = "ия"
            });

            write.ShouldNotThrow();
            request.GetStream().Position = 0;
            var    reader = new StreamReader(request.GetStream());
            string output = reader.ReadToEnd();

            output.Should().Be("{\"@odata.context\":\"http://host/service/$metadata#Edm.String\",\"value\":\"ия\"}");
        }
        public void ReadJsonLight()
        {
            // Arrange
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage    requestMessage = new MockODataRequestMessage();
            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings();

            writerSettings.SetContentType(ODataFormat.Json);
            IEdmModel          model         = CreateModel();
            ODataMessageWriter messageWriter = new ODataMessageWriter(requestMessage, writerSettings, model);

            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink {
                Url = new Uri("http://localhost/samplelink")
            });
            ODataMessageReader messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage),
                                                                      new ODataMessageReaderSettings(), model);

            IEdmNavigationProperty navigationProperty = GetNavigationProperty(model);

            var request = RequestFactory.Create("Get", "http://localhost", opt => opt.AddModel("odata", model));

            request.ODataFeature().PrefixName = "odata";
            ODataDeserializerContext context  = new ODataDeserializerContext
            {
                Request = request,
                Path    = new ODataPath(new NavigationPropertySegment(navigationProperty, navigationSource: null))
            };

            // Act
            Uri uri = deserializer.Read(messageReader, typeof(Uri), context) as Uri;

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
Beispiel #9
0
        public void WriteTopLevelUIntPropertyShouldWork()
        {
            var settings = new ODataMessageWriterSettings();

            settings.ODataUri.ServiceRoot = new Uri("http://host/service");
            settings.SetContentType(ODataFormat.Json);
            var model = new EdmModel();

            model.GetUInt32("MyNS", false);
            IODataRequestMessage request = new InMemoryMessage()
            {
                Stream = new MemoryStream()
            };
            var    writer = new ODataMessageWriter(request, settings, model);
            Action write  = () => writer.WriteProperty(new ODataProperty()
            {
                Name  = "Id",
                Value = (UInt32)123
            });

            write.ShouldNotThrow();
            request.GetStream().Position = 0;
            var    reader = new StreamReader(request.GetStream());
            string output = reader.ReadToEnd();

            output.Should().Be("{\"@odata.context\":\"http://host/service/$metadata#MyNS.UInt32\",\"value\":123}");
        }
        public async Task WriteObjectAsync_CanWrite_TopLevelResourceSet_ContainsEmptyCollectionOfDynamicComplexElement()
        {
            // Arrange
            ODataSerializerProvider    serializerProvider = GetServiceProvider().GetService <ODataSerializerProvider>();
            ODataResourceSetSerializer serializer         = new ODataResourceSetSerializer(serializerProvider);
            MemoryStream stream = new MemoryStream();
            IODataResponseMessageAsync message = new ODataMessageWrapper(stream);

            ODataMessageWriterSettings settings = new ODataMessageWriterSettings
            {
                ODataUri = new ODataUri {
                    ServiceRoot = new Uri("http://any/"),
                }
            };

            settings.SetContentType(ODataFormat.Json);

            ODataMessageWriter        writer    = new ODataMessageWriter(message, settings);
            IList <SimpleOpenAddress> addresses = new[]
            {
                new SimpleOpenAddress
                {
                    City       = "Redmond",
                    Street     = "Microsoft Rd",
                    Properties = new Dictionary <string, object>
                    {
                        { "StringProp", "abc" },
                        { "Locations", new SimpleOpenAddress[] {} } // empty collection of complex
                    }
                }
            };

            var builder = new ODataConventionModelBuilder();

            builder.ComplexType <SimpleOpenAddress>();
            IEdmModel model = builder.GetEdmModel();
            ODataSerializerContext writeContext = new ODataSerializerContext {
                Model = model
            };

            // Act
            await serializer.WriteObjectAsync(addresses, typeof(IList <SimpleOpenAddress>), writer, writeContext);

            stream.Seek(0, SeekOrigin.Begin);
            JObject result = JObject.Parse(await new StreamReader(stream).ReadToEndAsync());//.ToString();

            // Assert
            Assert.Equal(JObject.Parse(@"{
                ""@odata.context"": ""http://any/$metadata#Collection(Microsoft.AspNetCore.OData.Tests.Formatter.Models.SimpleOpenAddress)"",
                ""value"": [
                {
                    ""Street"": ""Microsoft Rd"",
                    ""City"": ""Redmond"",
                    ""StringProp"": ""abc"",
                    ""*****@*****.**"": ""#Collection(Microsoft.AspNetCore.OData.Tests.Formatter.Models.SimpleOpenAddress)"",
                    ""Locations"": []
                }
                ]
            }"), result);
        }
        public void ODataEntityReferenceLinkSerializer_Serializes_Uri(object link)
        {
            // Arrange
            ODataEntityReferenceLinkSerializer serializer   = new ODataEntityReferenceLinkSerializer();
            ODataSerializerContext             writeContext = new ODataSerializerContext();
            MemoryStream          stream  = new MemoryStream();
            IODataResponseMessage message = new ODataMessageWrapper(stream);

            ODataMessageWriterSettings settings = new ODataMessageWriterSettings
            {
                ODataUri = new ODataUri {
                    ServiceRoot = new Uri("http://any/")
                }
            };

            settings.SetContentType(ODataFormat.Json);
            ODataMessageWriter writer = new ODataMessageWriter(message, settings);

            // Act
            serializer.WriteObject(link, typeof(ODataEntityReferenceLink), writer, writeContext);
            stream.Seek(0, SeekOrigin.Begin);
            string result = new StreamReader(stream).ReadToEnd();

            // Assert
            Assert.Equal("{\"@odata.context\":\"http://any/$metadata#$ref\",\"@odata.id\":\"http://sampleuri/\"}", result);
        }
Beispiel #12
0
        private string WriteAtomEntry(ODataEntry entry)
        {
            MemoryStream    stream  = new MemoryStream();
            InMemoryMessage message = new InMemoryMessage {
                Stream = stream
            };

            var settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4, AutoComputePayloadMetadataInJson = true, EnableAtom = true
            };

            settings.SetServiceDocumentUri(new Uri("http://temp.org/"));

            settings.SetContentType(ODataFormat.Atom);


            ODataMessageWriter messageWriter = new ODataMessageWriter((IODataResponseMessage)message, settings, Model);

            var entryWriter = messageWriter.CreateODataEntryWriter(EntitySet, EntityType);

            entryWriter.WriteStart(entry);
            entryWriter.WriteEnd();
            entryWriter.Flush();

            var actual = Encoding.UTF8.GetString(stream.ToArray());

            return(actual);
        }
Beispiel #13
0
        public void JsonPaddingEnabledWithJsonFormatSpecified()
        {
            var settings = new ODataMessageWriterSettings {
                JsonPCallback = "functionName", EnableMessageStreamDisposal = false
            };

            settings.SetContentType(ODataFormat.Json);
            settings.SetServiceDocumentUri(new Uri("http://stuff"));
            IODataResponseMessage message = new InMemoryMessage {
                StatusCode = 200, Stream = new MemoryStream()
            };
            var property = new ODataProperty {
                Name = "PropertyName", Value = "value"
            };

            using (var writer = new ODataMessageWriter(message, settings))
            {
                writer.WriteProperty(property);
            }

            var responseStream = message.GetStream();

            responseStream.Position = 0;
            var responseString = new StreamReader(responseStream).ReadToEnd();

            responseString.Should().Be("functionName({\"@odata.context\":\"http://stuff/$metadata#Edm.String\",\"value\":\"value\"})");
            message.GetHeader("Content-Type").Should().StartWith("text/javascript");
        }
Beispiel #14
0
        public async Task ODataEntityReferenceLinkSerializer_Serializes_UrisAndEntityReferenceLinks(object uris)
        {
            // Arrange
            ODataEntityReferenceLinksSerializer serializer = new ODataEntityReferenceLinksSerializer();
            ODataSerializerContext writeContext            = new ODataSerializerContext();
            MemoryStream           stream  = new MemoryStream();
            IODataResponseMessage  message = new ODataMessageWrapper(stream);

            ODataMessageWriterSettings settings = new ODataMessageWriterSettings
            {
                ODataUri = new ODataUri {
                    ServiceRoot = new Uri("http://any/")
                }
            };

            settings.SetContentType(ODataFormat.Json);
            ODataMessageWriter writer = new ODataMessageWriter(message, settings);

            // Act
            await serializer.WriteObjectAsync(uris, typeof(ODataEntityReferenceLinks), writer, writeContext);

            stream.Seek(0, SeekOrigin.Begin);
            string result = await new StreamReader(stream).ReadToEndAsync();

            // Assert
            Assert.Equal("{\"@odata.context\":\"http://any/$metadata#Collection($ref)\"," +
                         "\"value\":[{\"@odata.id\":\"http://uri1/\"},{\"@odata.id\":\"http://uri2/\"}]}",
                         result);
        }
Beispiel #15
0
        public void ODataEntityReferenceLinkSerializer_Serializes_UrisAndEntityReferenceLinks_WithCount(object uris)
        {
            // Arrange
            ODataEntityReferenceLinksSerializer serializer = new ODataEntityReferenceLinksSerializer();
            ODataSerializerContext writeContext            = new ODataSerializerContext();

            writeContext.Request = new HttpRequestMessage();
            writeContext.Request.ODataProperties().TotalCount = 1;

            MemoryStream          stream  = new MemoryStream();
            IODataResponseMessage message = new ODataMessageWrapper(stream);

            ODataMessageWriterSettings settings = new ODataMessageWriterSettings
            {
                ODataUri = new ODataUri {
                    ServiceRoot = new Uri("http://any/")
                }
            };

            settings.SetContentType(ODataFormat.Json);
            ODataMessageWriter writer = new ODataMessageWriter(message, settings);

            // Act
            serializer.WriteObject(uris, typeof(ODataEntityReferenceLinks), writer, writeContext);
            stream.Seek(0, SeekOrigin.Begin);
            string result = new StreamReader(stream).ReadToEnd();

            Assert.Equal(
                string.Format("{0},{1},{2}",
                              "{\"@odata.context\":\"http://any/$metadata#Collection($ref)\"",
                              "\"@odata.count\":1",
                              "\"value\":[{\"@odata.id\":\"http://uri1/\"}]}"), result);
        }
        public async Task ODataServiceDocumentSerializer_Works()
        {
            // Arrange
            ODataServiceDocumentSerializer serializer = new ODataServiceDocumentSerializer();
            MemoryStream          stream  = new MemoryStream();
            IODataResponseMessage message = new ODataMessageWrapper(stream);

            ODataMessageWriterSettings settings = new ODataMessageWriterSettings
            {
                ODataUri = new ODataUri {
                    ServiceRoot = new Uri("http://any/"),
                }
            };

            settings.SetContentType(ODataFormat.Json);

            ODataMessageWriter writer = new ODataMessageWriter(message, settings);

            // Act
            await serializer.WriteObjectAsync(new ODataServiceDocument(), _workspaceType, writer, new ODataSerializerContext());

            await stream.FlushAsync();

            stream.Seek(0, SeekOrigin.Begin);
            string result = new StreamReader(stream).ReadToEnd();

            // Assert
            Assert.Equal("{\"@odata.context\":\"http://any/$metadata\",\"value\":[]}", result);
        }
        public void ReadJsonLight()
        {
            // Arrange
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage    requestMessage = new MockODataRequestMessage();
            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings();

            writerSettings.SetContentType(ODataFormat.Json);
            IEdmModel          model         = CreateModel();
            ODataMessageWriter messageWriter = new ODataMessageWriter(requestMessage, writerSettings, model);

            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink {
                Url = new Uri("http://localhost/samplelink")
            });
            ODataMessageReader messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage),
                                                                      new ODataMessageReaderSettings(), model);

            IEdmNavigationProperty navigationProperty = GetNavigationProperty(model);

            ODataDeserializerContext context = new ODataDeserializerContext
            {
                Request = new HttpRequestMessage(),
                Path    = new ODataPath(new NavigationPathSegment(navigationProperty))
            };

            // Act
            Uri uri = deserializer.Read(messageReader, typeof(Uri), context) as Uri;

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
Beispiel #18
0
        /// <summary>
        /// Creates ODataMessageWriterSettings
        /// </summary>
        /// <param name="isFullValidation">Whether turn on EnableFullValidation</param>
        /// <returns>Instance of ODataMessageWriterSettings</returns>
        private static ODataMessageWriterSettings CreateMessageWriterSettings(bool isFullValidation)
        {
            var settings = new ODataMessageWriterSettings
            {
                PayloadBaseUri  = BaseUri,
                CheckCharacters = CheckCharacters,
                Indent          = Indent,
                DisableMessageStreamDisposal = DisableMessageStreamDisposal,
                Version = Version,
                EnableFullValidation = isFullValidation,
                MessageQuotas        = new ODataMessageQuotas
                {
                    MaxPartsPerBatch          = MaxPartsPerBatch,
                    MaxOperationsPerChangeset = MaxOperationsPerChangeset,
                    MaxNestingDepth           = MaxNestingDepth,
                },
            };

            settings.ODataUri = new ODataUri()
            {
                ServiceRoot = BaseUri
            };
            settings.SetContentType(ODataFormat.Json);

            return(settings);
        }
Beispiel #19
0
        /// <summary>
        /// Writes an ODataError with the given custom instance annotation to the test stream.
        /// </summary>
        private void WriteError(params KeyValuePair <string, ODataValue>[] annotations)
        {
            var writerSettings = new ODataMessageWriterSettings {
                DisableMessageStreamDisposal = true
            };

            writerSettings.SetContentType(ODataFormat.Json);
            writerSettings.SetServiceDocumentUri(new Uri("http://example.com/"));

            IODataResponseMessage messageToWrite = new InMemoryMessage {
                StatusCode = 400, Stream = this.stream
            };

            var error = new ODataError();
            var instanceAnnotations = new Collection <ODataInstanceAnnotation>();

            error.SetInstanceAnnotations(instanceAnnotations);

            foreach (var pair in annotations)
            {
                ODataInstanceAnnotation annotation = new ODataInstanceAnnotation(pair.Key, pair.Value);
                instanceAnnotations.Add(annotation);
            }

            using (var writer = new ODataMessageWriter(messageToWrite, writerSettings, this.model))
            {
                writer.WriteError(error, false);
            }
        }
Beispiel #20
0
        public static Stream CreatePackageStream(string baseAddress, IWebPackage package)
        {
            var writerSettings = new ODataMessageWriterSettings()
            {
                Indent          = true, // pretty printing
                CheckCharacters = false,
                BaseUri         = new Uri("http://localhost:12345"),
                Version         = ODataVersion.V3
            };

            writerSettings.SetContentType(ODataFormat.Atom);

            var responseMessage = new MemoryResposneMessage();
            var writer          = new ODataMessageWriter(responseMessage, writerSettings);

            var feedWriter = writer.CreateODataEntryWriter();

            feedWriter.WriteStart(MapPackageToEntry(baseAddress, package));
            feedWriter.WriteEnd();
            feedWriter.Flush();

            var stream = responseMessage.GetStream();

            stream.Seek(0, SeekOrigin.Begin);

            return(stream);
        }
Beispiel #21
0
        /// <summary>
        /// Creates ODataMessageWriterSettings
        /// </summary>
        /// <param name="isFullValidation">Whether turn on FullValidation</param>
        /// <returns>Instance of ODataMessageWriterSettings</returns>
        private static ODataMessageWriterSettings CreateMessageWriterSettings(bool isFullValidation)
        {
            var settings = new ODataMessageWriterSettings
            {
                BaseUri = BaseUri,
                EnableCharactersCheck       = CheckCharacters,
                EnableMessageStreamDisposal = EnableMessageStreamDisposal,
                Version       = Version,
                Validations   = isFullValidation ? ValidationKinds.All : ValidationKinds.None,
                MessageQuotas = new ODataMessageQuotas
                {
                    MaxPartsPerBatch          = MaxPartsPerBatch,
                    MaxOperationsPerChangeset = MaxOperationsPerChangeset,
                    MaxNestingDepth           = MaxNestingDepth,
                },
            };

            settings.ODataUri = new ODataUri()
            {
                ServiceRoot = BaseUri
            };
            settings.SetContentType(ODataFormat.Json);

            return(settings);
        }
Beispiel #22
0
        /// <summary>
        /// Determines the response format based on the results of content negotiation.
        /// </summary>
        /// <param name="payloadKind">The payload kind of the response.</param>
        /// <param name="acceptableMediaTypes">
        /// The acceptable media types used to determine the content type of the message.
        /// This is a comma separated list of content types as specified in RFC 2616, Section 14.1
        /// </param>
        /// <param name="acceptableCharSets">
        /// The acceptable charsets to use to the determine the encoding of the message.
        /// This is a comma separated list of charsets as specified in RFC 2616, Section 14.2
        /// </param>
        /// <returns>The format the response should use. </returns>
        internal ODataFormatWithParameters DetermineResponseFormat(ODataPayloadKind payloadKind, string acceptableMediaTypes, string acceptableCharSets)
        {
            Debug.Assert(payloadKind != ODataPayloadKind.Unsupported, "kind != ODataPayloadKind.Unsupported");

            ContentNegotiationResponseMessage responseMessage = new ContentNegotiationResponseMessage();

            ODataMessageWriterSettings settings = new ODataMessageWriterSettings {
                Version = this.responseVersion
            };

            // settings.EnableAtomSupport();
            settings.SetContentType(acceptableMediaTypes, acceptableCharSets);

            try
            {
                using (ODataMessageWriter writer = new ODataMessageWriter(responseMessage, settings))
                {
                    ODataFormat format = ODataUtils.SetHeadersForPayload(writer, payloadKind);
                    return(new ODataFormatWithParameters(format, responseMessage.ContentType));
                }
            }
            catch (ODataContentTypeException exception)
            {
                if (this.throwIfNoMatch)
                {
                    throw new DataServiceException(415, null, Microsoft.OData.Service.Strings.DataServiceException_UnsupportedMediaType, null, exception);
                }

                return(null);
            }
        }
Beispiel #23
0
        public void ODataEntityReferenceLinkSerializer_Serializes_UrisAndEntityReferenceLinks_Json(object uris)
        {
            // Arrange
            ODataEntityReferenceLinksSerializer serializer = new ODataEntityReferenceLinksSerializer();
            IEdmNavigationProperty navigationProperty      = _customerSet.ElementType.NavigationProperties().First();
            ODataPath path = new ODataPath(new EntitySetPathSegment(_customerSet), new KeyValuePathSegment("1"),
                                           new NavigationPathSegment(navigationProperty));
            ODataSerializerContext writeContext = new ODataSerializerContext {
                Path = path
            };
            MemoryStream          stream  = new MemoryStream();
            IODataResponseMessage message = new ODataMessageWrapper(stream);

            ODataMessageWriterSettings settings = new ODataMessageWriterSettings
            {
                BaseUri = new Uri("http://any/")
            };

            settings.SetMetadataDocumentUri(new Uri("http://any/$metadata"));
            settings.SetContentType(ODataFormat.Json);

            // Act
            serializer.WriteObject(uris, typeof(ODataEntityReferenceLinks), new ODataMessageWriter(message, settings), writeContext);
            stream.Seek(0, SeekOrigin.Begin);
            string result = new StreamReader(stream).ReadToEnd();

            // Assert
            Assert.Equal(
                string.Format("{0},{1}",
                              "{\"odata.metadata\":\"http://any/$metadata#Default.Container.Customers/$links/Orders\"",
                              "\"value\":[{\"url\":\"http://uri1/\"},{\"url\":\"http://uri2/\"}]}"), result);
        }
        private ODataMessageWriterSettings GetWriterSettings()
        {
            var settings = new ODataMessageWriterSettings()
            {
                BaseUri = new Uri(_session.Settings.UrlBase),
                Indent  = true,
                DisableMessageStreamDisposal = !IsBatch,
            };
            ODataFormat contentType;

            switch (_session.Settings.PayloadFormat)
            {
            case ODataPayloadFormat.Atom:
            default:
                contentType = ODataFormat.Atom;
                break;

            case ODataPayloadFormat.Json:
                switch (_session.Adapter.ProtocolVersion)
                {
                case ODataProtocolVersion.V1:
                case ODataProtocolVersion.V2:
                    contentType = ODataFormat.VerboseJson;
                    break;

                default:
                    contentType = ODataFormat.Json;
                    break;
                }
                break;
            }
            settings.SetContentType(contentType);
            return(settings);
        }
 public void CreateCollectionWriterWithoutTypeShouldPassForJsonLight()
 {
     var settings = new ODataMessageWriterSettings();
     settings.SetContentType(ODataFormat.Json);
     var writer = new ODataMessageWriter(new DummyRequestMessage(), settings, new EdmModel());
     writer.CreateODataCollectionWriter(null).Should().BeOfType<ODataJsonLightCollectionWriter>();
 }
Beispiel #26
0
        private static ODataMessageWriterSettings CreateJsonLightSettings()
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings();

            settings.SetContentType(ODataFormat.Json);
            settings.SetMetadataDocumentUri(CreateFakeUri());
            return(settings);
        }
        private string WriterEntry(IEdmModel userModel, ODataResource entry, EdmEntitySet entitySet, IEdmEntityType entityType,
                                   bool fullMetadata = false, Action <ODataWriter> writeAction = null, ODataStringEscapeOption?stringEscapeOption = null)
        {
            var message = new InMemoryMessage()
            {
                Stream = new MemoryStream()
            };

            if (stringEscapeOption != null)
            {
                var containerBuilder = new Test.OData.DependencyInjection.TestContainerBuilder();
                containerBuilder.AddDefaultODataServices();
                containerBuilder.AddService <IJsonWriterFactory>(ServiceLifetime.Singleton, sp => new DefaultJsonWriterFactory(stringEscapeOption.Value));
                message.Container = containerBuilder.BuildContainer();
            }

            var writerSettings = new ODataMessageWriterSettings {
                EnableMessageStreamDisposal = false
            };

            writerSettings.SetContentType(ODataFormat.Json);
            writerSettings.SetServiceDocumentUri(new Uri("http://www.example.com"));
            writerSettings.SetContentType(fullMetadata ?
                                          "application/json;odata.metadata=full;odata.streaming=false" :
                                          "application/json;odata.metadata=minimal;odata.streaming=false", "utf-8");

            using (var msgReader = new ODataMessageWriter((IODataResponseMessage)message, writerSettings, userModel))
            {
                var writer = msgReader.CreateODataResourceWriter(entitySet, entityType);
                if (writeAction != null)
                {
                    writeAction(writer);
                }
                else
                {
                    writer.WriteStart(entry);
                    writer.WriteEnd();
                }
            }

            message.Stream.Seek(0, SeekOrigin.Begin);
            using (StreamReader reader = new StreamReader(message.Stream))
            {
                return(reader.ReadToEnd());
            }
        }
Beispiel #28
0
        public void CreateCollectionWriterWithoutTypeShouldPassForJsonLight()
        {
            var settings = new ODataMessageWriterSettings();

            settings.SetContentType(ODataFormat.Json);
            var writer = new ODataMessageWriter(new DummyRequestMessage(), settings, new EdmModel());

            writer.CreateODataCollectionWriter(null).Should().BeOfType <ODataJsonLightCollectionWriter>();
        }
Beispiel #29
0
        private static string WriteJsonLightEntry(IEdmModel model, IEdmEntitySet entitySet, Action <ODataWriter> writeAction, bool isFullMetadata = false)
        {
            var stream  = new MemoryStream();
            var message = new InMemoryMessage {
                Stream = stream
            };

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

            odataUri.Path     = new ODataUriParser(model, ServiceRoot, new Uri(ServiceRoot + "/EntitySet")).ParsePath();
            settings.ODataUri = odataUri;
            settings.SetServiceDocumentUri(ServiceRoot);

            settings.SetContentType(ODataFormat.Json);
            if (isFullMetadata)
            {
                settings.SetContentType("application/json;odata.metadata=full", null);
            }
            else
            {
                settings.SetContentType("application/json;odata.metadata=minimal", null);
            }

            var         messageWriter = new ODataMessageWriter((IODataResponseMessage)message, settings, model);
            ODataWriter writer        = null;

            writer = messageWriter.CreateODataResourceWriter(entitySet);

            if (writeAction != null)
            {
                writeAction(writer);
            }

            writer.Flush();

            var actual = Encoding.UTF8.GetString(stream.ToArray());

            return(actual);
        }
Beispiel #30
0
        public override void RunTest(ReaderTestConfiguration testConfiguration)
        {
            //TODO: Use Logger to verify result, right now this change is only to unblock writer testcase checkin
            BaselineLogger logger = null;

            if (this.ShouldSkipForTestConfiguration(testConfiguration))
            {
                return;
            }

            var originalPayload = this.PayloadElement;

            this.PayloadElement = this.PayloadElement.DeepCopy();

            // Create messages (payload gets serialized in createInputMessage)
            TestMessage readerMessage = this.CreateInputMessage(testConfiguration);
            var         settings      = new ODataMessageWriterSettings()
            {
                Version = testConfiguration.Version,
                BaseUri = testConfiguration.MessageReaderSettings.BaseUri,
                EnableMessageStreamDisposal = testConfiguration.MessageReaderSettings.EnableMessageStreamDisposal,
            };

            settings.SetContentType(testConfiguration.Format);

            WriterTestConfiguration writerConfig  = new WriterTestConfiguration(testConfiguration.Format, settings, testConfiguration.IsRequest, testConfiguration.Synchronous);
            TestMessage             writerMessage = TestWriterUtils.CreateOutputMessageFromStream(new TestStream(new MemoryStream()), writerConfig, this.PayloadKind, String.Empty, this.UrlResolver);

            IEdmModel model = this.GetMetadataProvider(testConfiguration);
            WriterTestExpectedResults expectedResult = this.GetExpectedResult(writerConfig);

            ExceptionUtilities.Assert(expectedResult != null, "The expected result could not be determined for the test. Did you specify it?");

            Exception exception = TestExceptionUtils.RunCatching(() =>
            {
                using (ODataMessageReaderTestWrapper messageReaderWrapper = TestReaderUtils.CreateMessageReader(readerMessage, model, testConfiguration))
                    using (ODataMessageWriterTestWrapper messageWriterWrapper = TestWriterUtils.CreateMessageWriter(writerMessage, model, writerConfig, this.settings.Assert))
                    {
                        var streamer = new ObjectModelReadWriteStreamer();
                        streamer.StreamMessage(messageReaderWrapper, messageWriterWrapper, this.PayloadKind, writerConfig);
                        expectedResult.VerifyResult(writerMessage, this.PayloadKind, writerConfig, logger);
                    }
            });

            this.PayloadElement = originalPayload;

            try
            {
                expectedResult.VerifyException(exception);
            }
            catch (Exception)
            {
                this.TraceFailureInformation(testConfiguration);
                throw;
            }
        }
        private ODataMessageWriterSettings GetAvroWriterSettings()
        {
            var settings = new ODataMessageWriterSettings()
            {
                MediaTypeResolver = AvroMediaTypeResolver.Instance,
            };

            settings.SetContentType(AvroFormat.Avro);
            return(settings);
        }
Beispiel #32
0
        public void JsonPaddingEnabledWithRawValueSpecified()
        {
            var settings = new ODataMessageWriterSettings {JsonPCallback = "functionName", DisableMessageStreamDisposal = true};
            settings.SetContentType(ODataFormat.RawValue);
            IODataResponseMessage message = new InMemoryMessage {StatusCode = 200, Stream = new MemoryStream()};

            using (var writer = new ODataMessageWriter(message, settings))
            {
                writer.WriteValue(123);
            }

            var responseStream = message.GetStream();
            responseStream.Position = 0;
            var responseString = new StreamReader(responseStream).ReadToEnd();
            responseString.Should().Be("functionName(123)");
            message.GetHeader("Content-Type").Should().StartWith("text/javascript");
        }
Beispiel #33
0
        public void JsonPaddingEnabledWithJsonFormatSpecified()
        {
            var settings = new ODataMessageWriterSettings {JsonPCallback = "functionName", DisableMessageStreamDisposal = true};
            settings.SetContentType(ODataFormat.Json);
            settings.SetServiceDocumentUri(new Uri("http://stuff"));
            IODataResponseMessage message = new InMemoryMessage {StatusCode = 200, Stream = new MemoryStream()};
            var property = new ODataProperty {Name = "PropertyName", Value = "value"};
            
            using (var writer = new ODataMessageWriter(message, settings))
            {
                writer.WriteProperty(property);
            }

            var responseStream = message.GetStream();
            responseStream.Position = 0;
            var responseString = new StreamReader(responseStream).ReadToEnd();
            responseString.Should().Be("functionName({\"@odata.context\":\"http://stuff/$metadata#Edm.String\",\"value\":\"value\"})");
            message.GetHeader("Content-Type").Should().StartWith("text/javascript");
        }
        protected void WriteAnnotationsAndValidatePayload(Action<ODataWriter> action, ODataFormat format, string expectedPayload, bool request, bool createFeedWriter)
        {
            var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true, EnableAtom = true };
            writerSettings.SetContentType(format);
            writerSettings.SetServiceDocumentUri(new Uri("http://www.example.com/"));

            MemoryStream stream = new MemoryStream();
            if (request)
            {
                IODataRequestMessage requestMessageToWrite = new InMemoryMessage { Method = "GET", Stream = stream };
                using (var messageWriter = new ODataMessageWriter(requestMessageToWrite, writerSettings, Model))
                {
                    ODataWriter odataWriter = createFeedWriter ? messageWriter.CreateODataFeedWriter(EntitySet, EntityType) : messageWriter.CreateODataEntryWriter(EntitySet, EntityType);
                    action(odataWriter);
                }
            }
            else
            {
                IODataResponseMessage responseMessageToWrite = new InMemoryMessage { StatusCode = 200, Stream = stream };
                using (var messageWriter = new ODataMessageWriter(responseMessageToWrite, writerSettings, Model))
                {
                    ODataWriter odataWriter = createFeedWriter ? messageWriter.CreateODataFeedWriter(EntitySet, EntityType) : messageWriter.CreateODataEntryWriter(EntitySet, EntityType);
                    action(odataWriter);
                }
            }

            stream.Position = 0;
            string payload = (new StreamReader(stream)).ReadToEnd();
            if (format == ODataFormat.Atom)
            {
                // The <updated> element is computed dynamically, so we remove it from the both the baseline and the actual payload.
                payload = Regex.Replace(payload, "<updated>[^<]*</updated>", "");
                expectedPayload = Regex.Replace(expectedPayload, "<updated>[^<]*</updated>", "");
            }

            Assert.Equal(expectedPayload, payload);
        }
 private string WriteODataEntry(ODataEntry entryToWrite)
 {
     var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true };
     writerSettings.SetContentType(ODataFormat.Json);
     writerSettings.SetServiceDocumentUri(new Uri("http://www.example.com/"));
     MemoryStream stream = new MemoryStream();
     IODataRequestMessage requestMessageToWrite = new InMemoryMessage { Method = "GET", Stream = stream };
     using (var messageWriter = new ODataMessageWriter(requestMessageToWrite, writerSettings, this.model))
     {
         ODataWriter odataWriter = messageWriter.CreateODataEntryWriter(this.entitySet, this.entityType);
         odataWriter.WriteStart(entryToWrite);
         odataWriter.WriteEnd();
     }
     stream.Position = 0;
     string payload = (new StreamReader(stream)).ReadToEnd();
     return payload;
 }
        private static void WriteCustomInstanceAnnotationToFeedAndEntry(string expectedPayload, ODataFormat format)
        {
            var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true, EnableAtom = format == ODataFormat.Atom };
            writerSettings.SetContentType(format);
            writerSettings.ODataUri = new ODataUri() { ServiceRoot = new Uri("http://www.example.com/") };

            MemoryStream stream = new MemoryStream();
            IODataResponseMessage messageToWrite = new InMemoryMessage { StatusCode = 200, Stream = stream };
            messageToWrite.PreferenceAppliedHeader().AnnotationFilter = "Custom.*";

            // Write payload
            using (var messageWriter = new ODataMessageWriter(messageToWrite, writerSettings, Model))
            {
                var odataWriter = messageWriter.CreateODataFeedWriter(EntitySet, EntityType);

                // Add instance annotations to the feed.
                var feedToWrite = new ODataFeed { Id = new Uri("urn:feedId") };
                feedToWrite.InstanceAnnotations.Add(new ODataInstanceAnnotation("Custom.Int32Annotation", PrimitiveValue1));
                feedToWrite.InstanceAnnotations.Add(new ODataInstanceAnnotation("Custom.GuidAnnotation", PrimitiveValue2));
                feedToWrite.InstanceAnnotations.Add(new ODataInstanceAnnotation("ShouldSkip.Int32Annotation", PrimitiveValue1));
                feedToWrite.InstanceAnnotations.Add(new ODataInstanceAnnotation("ShouldSkip.GuidAnnotation", PrimitiveValue2));

                // Writes instance annotations at the beginning of the feed
                odataWriter.WriteStart(feedToWrite);

                // Add instance annotations to the entry.
                var entryToWrite = new ODataEntry { Properties = new[] { new ODataProperty { Name = "ID", Value = 1 } } };
                entryToWrite.InstanceAnnotations.Add(new ODataInstanceAnnotation("Custom.ComplexAnnotation", ComplexValue1));
                entryToWrite.InstanceAnnotations.Add(new ODataInstanceAnnotation("ShouldSkip.ComplexAnnotation", ComplexValue1));

                // Writes instance annotations at the beginning of the entry
                odataWriter.WriteStart(entryToWrite);

                // Add more instance annotations to the entry.
                entryToWrite.InstanceAnnotations.Add(new ODataInstanceAnnotation("Custom.PrimitiveCollectionAnnotation", PrimitiveCollectionValue));
                entryToWrite.InstanceAnnotations.Add(new ODataInstanceAnnotation("ShouldSkip.PrimitiveCollectionAnnotation", PrimitiveCollectionValue));

                // The writer remembers which instance annotations in the collection has been written
                // and only write out the unwritten ones since WriteStart() to the end of the entry.
                odataWriter.WriteEnd();

                // Add more instance annotations to the feed.
                feedToWrite.InstanceAnnotations.Add(new ODataInstanceAnnotation("Custom.ComplexCollectionAnnotation", ComplexCollectionValue));
                feedToWrite.InstanceAnnotations.Add(new ODataInstanceAnnotation("ShouldSkip.ComplexCollectionAnnotation", ComplexCollectionValue));

                // The writer remembers which instance annotations in the collection has been written
                // and only write out the unwritten ones since WriteStart() to the end of the feed.
                odataWriter.WriteEnd();
            }

            stream.Position = 0;
            string payload = (new StreamReader(stream)).ReadToEnd();
            if (format == ODataFormat.Atom)
            {
                // The <updated> element is computed dynamically, so we remove it from the both the baseline and the actual payload.
                payload = Regex.Replace(payload, "<updated>[^<]*</updated>", "");
                expectedPayload = Regex.Replace(expectedPayload, "<updated>[^<]*</updated>", "");
            }

            payload.Should().Be(expectedPayload);
        }
        private string WriteAtomEntry(ODataEntry entry)
        {
            MemoryStream stream = new MemoryStream();
            InMemoryMessage message = new InMemoryMessage { Stream = stream };

            var settings = new ODataMessageWriterSettings { Version = ODataVersion.V4, AutoComputePayloadMetadataInJson = true, EnableAtom = true};
            settings.SetServiceDocumentUri(new Uri("http://temp.org/"));

            settings.SetContentType(ODataFormat.Atom);
            

            ODataMessageWriter messageWriter = new ODataMessageWriter((IODataResponseMessage)message, settings, Model);

            var entryWriter = messageWriter.CreateODataEntryWriter(EntitySet, EntityType);

            entryWriter.WriteStart(entry);
            entryWriter.WriteEnd();
            entryWriter.Flush();

            var actual = Encoding.UTF8.GetString(stream.ToArray());
            return actual;
        }
        public void ShouldBeAbleToWriteFeedAndEntryResponseInJsonLightWithoutModel()
        {
            const string expectedPayload =
                "{" +
                    "\"@odata.context\":\"http://www.example.com/$metadata#Customers/NS.VIPCustomer\"," +
                    "\"value\":[" +
                        "{" +
                            "\"Name\":\"Bob\"," +
                            "\"[email protected]\":\"MostRecentOrder\"," +
                            "\"MostRecentOrder\":{\"OrderId\":101}" +
                        "}" +
                    "]" +
                "}";

            var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true };
            writerSettings.SetContentType(ODataFormat.Json);
            writerSettings.ODataUri = new ODataUri() { ServiceRoot = new Uri("http://www.example.com") };

            MemoryStream stream = new MemoryStream();
            IODataResponseMessage responseMessage = new InMemoryMessage { StatusCode = 200, Stream = stream };

            // Write payload
            using (var messageWriter = new ODataMessageWriter(responseMessage, writerSettings))
            {
                var odataWriter = messageWriter.CreateODataFeedWriter();

                // Create customers feed with serializtion info to write odata.metadata.
                var customersFeed = new ODataFeed();
                customersFeed.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo { NavigationSourceName = "Customers", NavigationSourceEntityTypeName = "NS.Customer", ExpectedTypeName = "NS.VIPCustomer" });

                // Write customers feed.
                odataWriter.WriteStart(customersFeed);

                // Write VIP customer
                {
                    // Create VIP customer, don't need to pass in serialization info since the writer knows the context from the feed scope.
                    var vipCustomer = new ODataEntry { TypeName = "NS.VIPCustomer" };

                    var customerKey = new ODataProperty { Name = "Name", Value = "Bob" };

                    // Provide serialization info at the property level to compute the edit link.
                    customerKey.SetSerializationInfo(new ODataPropertySerializationInfo { PropertyKind = ODataPropertyKind.Key });
                    vipCustomer.Properties = new[] { customerKey };

                    // Write customer entry.
                    odataWriter.WriteStart(vipCustomer);

                    // Write expanded most recent order
                    {
                        // No API to set serialization info on ODataNavigationLink since what we are adding on ODataFeed and ODataEntry should be sufficient for the 5.5 release.
                        var navigationLink = new ODataNavigationLink { Name = "MostRecentOrder", IsCollection = false, Url = new Uri("MostRecentOrder", UriKind.Relative) };
                        odataWriter.WriteStart(navigationLink);

                        // Write the most recent customer.
                        {
                            var mostRecentOrder = new ODataEntry { TypeName = "NS.Order" };

                            // Add serialization info so we can computer links.
                            mostRecentOrder.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo { NavigationSourceName = "Orders", NavigationSourceEntityTypeName = "NS.Order", ExpectedTypeName = "NS.Order" });

                            var orderKey = new ODataProperty { Name = "OrderId", Value = 101 };

                            // Provide serialization info at the property level to compute the edit link.
                            orderKey.SetSerializationInfo(new ODataPropertySerializationInfo { PropertyKind = ODataPropertyKind.Key });
                            mostRecentOrder.Properties = new[] { orderKey };

                            // Write order entry.
                            odataWriter.WriteStart(mostRecentOrder);
                            odataWriter.WriteEnd();
                        }

                        // End navigationLink.
                        odataWriter.WriteEnd();
                    }

                    // End customer entry.
                    odataWriter.WriteEnd();
                }

                // End customers feed.
                odataWriter.WriteEnd();
            }

            stream.Position = 0;
            string payload = (new StreamReader(stream)).ReadToEnd();
            payload.Should().Be(expectedPayload);
        }
        private string WriterEntry(IEdmModel userModel, ODataEntry entry, EdmEntitySet entitySet, IEdmEntityType entityType, bool fullMetadata = false)
        {
            var message = new InMemoryMessage() { Stream = new MemoryStream() };

            var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true, AutoComputePayloadMetadataInJson = true };
            writerSettings.SetContentType(ODataFormat.Json);
            writerSettings.SetServiceDocumentUri(new Uri("http://www.example.com"));
            writerSettings.SetContentType(fullMetadata ?
                "application/json;odata.metadata=full;odata.streaming=false" :
                "application/json;odata.metadata=minimal;odata.streaming=false", "utf-8");

            using (var msgReader = new ODataMessageWriter((IODataResponseMessage)message, writerSettings, userModel))
            {
                var writer = msgReader.CreateODataEntryWriter(entitySet, entityType);
                writer.WriteStart(entry);
                writer.WriteEnd();
            }

            message.Stream.Seek(0, SeekOrigin.Begin);
            using (StreamReader reader = new StreamReader(message.Stream))
            {
                return reader.ReadToEnd();
            }
        }
        private void WriteAndValidateContextUri(ODataFormat odataFormat, EdmModel edmModel, Action<ODataMessageWriter> test, string expectedUri, out string payload, out string contentType)
        {
            var message = new InMemoryMessage() { Stream = new MemoryStream() };

            var writerSettings = new ODataMessageWriterSettings
            {
                DisableMessageStreamDisposal = true,
                PayloadBaseUri = new Uri(TestBaseUri),
                AutoComputePayloadMetadataInJson = true,
                EnableAtom = true
            };
            writerSettings.SetServiceDocumentUri(new Uri(TestBaseUri));
            writerSettings.SetContentType(odataFormat);

            using (var msgWriter = new ODataMessageWriter((IODataResponseMessage)message, writerSettings, edmModel))
            {
                test(msgWriter);
            }

            message.Stream.Seek(0, SeekOrigin.Begin);
            using (StreamReader reader = new StreamReader(message.Stream))
            {
                contentType = message.GetHeader("Content-Type");
                payload = reader.ReadToEnd();
                payload.Should().Contain(expectedUri);
            }
        }
        /// <summary>
        /// Writes an ODataError with the given custom instance annotation to the test stream.
        /// </summary>
        private void WriteError(params KeyValuePair<string, ODataValue>[] annotations)
        {
            var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true };
            writerSettings.SetContentType(ODataFormat.Json);
            writerSettings.SetServiceDocumentUri(new Uri("http://example.com/"));

            IODataResponseMessage messageToWrite = new InMemoryMessage { StatusCode = 400, Stream = this.stream };

            var error = new ODataError();
            var instanceAnnotations = new Collection<ODataInstanceAnnotation>();
            error.SetInstanceAnnotations(instanceAnnotations);

            foreach (var pair in annotations)
            {
                ODataInstanceAnnotation annotation = new ODataInstanceAnnotation(pair.Key, pair.Value);
                instanceAnnotations.Add(annotation);
            }

            using (var writer = new ODataMessageWriter(messageToWrite, writerSettings, this.model))
            {
                writer.WriteError(error, false);
            }
        }
        // TODO: ATOM top level individual property testings
        // FlagsEnumAsComplexPropertyAsTopLevelValue_StrAsValue_StrAsTypeName
        // FlagsEnumAsCollectionItemAsTopLevelValue_StrAsValue_StrAsTypeName

        #endregion

        #region private methods
        public void WriteToMessageWriterAndVerifyPayload(string contentType, Action<ODataMessageWriter> writerAction, string expectedPayload)
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings() { Version = ODataVersion.V4, AutoComputePayloadMetadataInJson = true, DisableMessageStreamDisposal = true, EnableAtom = true};
            settings.SetContentType(contentType, "utf-8");
            settings.SetServiceDocumentUri(ServiceDocumentUri);
            // with model
            {
                MemoryStream stream = new MemoryStream();
                IODataResponseMessage message = new InMemoryMessage() { Stream = stream };
                using (ODataMessageWriter writer = new ODataMessageWriter(message, settings, this.userModel))
                {
                    writerAction(writer);
                }

                stream.Seek(0, SeekOrigin.Begin);
                string payload = (new StreamReader(stream)).ReadToEnd();
                payload.Should().Be(expectedPayload);
            }

            // without model
            {
                MemoryStream stream = new MemoryStream();
                IODataResponseMessage message = new InMemoryMessage() { Stream = stream };
                using (ODataMessageWriter writer = new ODataMessageWriter(message, settings))
                {
                    writerAction(writer);
                }

                stream.Seek(0, SeekOrigin.Begin);
                string payload = (new StreamReader(stream)).ReadToEnd();
                payload.Should().Be(expectedPayload);
            }
        }
        private static string WriteJsonLightEntry(bool isRequest, Uri serviceDocumentUri, bool specifySet,
            ODataEntry odataEntry, IEdmNavigationSource entitySet, IEdmEntityType entityType, ODataUri odataUri)
        {
            var model = new EdmModel();
            model.AddElement(new EdmEntityContainer("Fake", "Container_sub"));
            var stream = new MemoryStream();
            var message = new InMemoryMessage { Stream = stream };

            var settings = new ODataMessageWriterSettings { Version = ODataVersion.V4, AutoComputePayloadMetadataInJson = true };
            settings.ODataUri = odataUri;
            settings.SetServiceDocumentUri(serviceDocumentUri);

            settings.SetContentType(ODataFormat.Json);
            settings.SetContentType("application/json;odata.metadata=full", null);

            ODataMessageWriter messageWriter;
            if (isRequest)
            {
                messageWriter = new ODataMessageWriter((IODataRequestMessage)message, settings, TestUtils.WrapReferencedModelsToMainModel("Fake", "Container", model));
            }
            else
            {
                messageWriter = new ODataMessageWriter((IODataResponseMessage)message, settings, TestUtils.WrapReferencedModelsToMainModel("Fake", "Container", model));
            }

            var entryWriter = messageWriter.CreateODataEntryWriter(specifySet ? entitySet : null, entityType);
            entryWriter.WriteStart(odataEntry);
            entryWriter.WriteEnd();
            entryWriter.Flush();

            var actual = Encoding.UTF8.GetString(stream.ToArray());
            return actual;
        }
        public void WriteTopLevelEntityReferenceLinks()
        {
            ODataEntityReferenceLink link1 = new ODataEntityReferenceLink
            {
                Url = new Uri("http://host/Customers(1)")
            };
            link1.InstanceAnnotations.Add(new ODataInstanceAnnotation("Is.New", new ODataPrimitiveValue(true)));
            ODataEntityReferenceLink link2 = new ODataEntityReferenceLink
            {
                Url = new Uri("http://host/Customers(2)")
            };
            link2.InstanceAnnotations.Add(new ODataInstanceAnnotation("TestNamespace.unknown", new ODataPrimitiveValue(123)));
            link2.InstanceAnnotations.Add(new ODataInstanceAnnotation("custom.annotation", new ODataPrimitiveValue(456)));

            ODataEntityReferenceLinks referencelinks = new ODataEntityReferenceLinks()
            {
                Links = new[] { link1, link2 }
            };

            var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true };
            writerSettings.SetContentType(ODataFormat.Json);
            writerSettings.SetServiceDocumentUri(new Uri("http://odata.org/test"));
            MemoryStream stream = new MemoryStream();
            IODataResponseMessage requestMessageToWrite = new InMemoryMessage { StatusCode = 200, Stream = stream };
            requestMessageToWrite.PreferenceAppliedHeader().AnnotationFilter = "*";

            using (var messageWriter = new ODataMessageWriter(requestMessageToWrite, writerSettings, EdmModel))
            {
                messageWriter.WriteEntityReferenceLinks(referencelinks);
            }
            stream.Position = 0;
            string payload = (new StreamReader(stream)).ReadToEnd();

            string expectedPayload = "{\"@odata.context\":\"http://odata.org/test/$metadata#Collection($ref)\",\"value\":[{\"@odata.id\":\"http://host/Customers(1)\",\"@Is.New\":true},{\"@odata.id\":\"http://host/Customers(2)\",\"@TestNamespace.unknown\":123,\"@custom.annotation\":456}]}";

            Assert.Equal(expectedPayload, payload);
        }
 public void WriteTopLevelUIntPropertyShouldWork()
 {
     var settings = new ODataMessageWriterSettings();
     settings.ODataUri.ServiceRoot = new Uri("http://host/service");
     settings.SetContentType(ODataFormat.Json);
     var model = new EdmModel();
     model.GetUInt32("MyNS", false);
     IODataRequestMessage request = new InMemoryMessage() { Stream = new MemoryStream() };
     var writer = new ODataMessageWriter(request, settings, model);
     Action write = () => writer.WriteProperty(new ODataProperty()
     {
         Name = "Id",
         Value = (UInt32)123
     });
     write.ShouldNotThrow();
     request.GetStream().Position = 0;
     var reader = new StreamReader(request.GetStream());
     string output = reader.ReadToEnd();
     output.Should().Be("{\"@odata.context\":\"http://host/service/$metadata#MyNS.UInt32\",\"value\":123}");
 }
        public void ShouldBeAbleToWriteCustomInstanceAnnotationToErrorInJsonLight()
        {
            const string expectedPayload =
            "{" +
                "\"error\":{" +
                    "\"code\":\"400\"," +
                    "\"message\":\"Resource not found for the segment 'Address'.\"," +
                    "\"@instance.annotation\":\"stringValue\"" +
                "}" +
            "}";

            var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true };
            writerSettings.SetContentType(ODataFormat.Json);
            writerSettings.ODataUri = new ODataUri() { ServiceRoot = new Uri("http://www.example.com") };

            MemoryStream stream = new MemoryStream();
            IODataResponseMessage messageToWrite = new InMemoryMessage { StatusCode = 400, Stream = stream };

            // Write payload
            using (var messageWriter = new ODataMessageWriter(messageToWrite, writerSettings, Model))
            {
                ODataError error = new ODataError { ErrorCode = "400", Message = "Resource not found for the segment 'Address'." };
                error.InstanceAnnotations.Add(new ODataInstanceAnnotation("instance.annotation", new ODataPrimitiveValue("stringValue")));
                messageWriter.WriteError(error, includeDebugInformation: true);
            }

            stream.Position = 0;
            string payload = (new StreamReader(stream)).ReadToEnd();
            payload.Should().Be(expectedPayload);
        }