public void ReadValueOfAbbreviativeDateShouldWork()
 {
     Stream stream = new MemoryStream(Encoding.Default.GetBytes("2014-1-3"));
     IODataResponseMessage responseMessage = new InMemoryMessage() { StatusCode = 200, Stream = stream };
     ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel());
     reader.ReadValue(new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "DateValue", EdmPrimitiveTypeKind.Date), true)).Should().Be(new Date(2014, 1, 3));
 }
 public void CreateMessageReaderShouldSetAnnotationFilterWhenODataAnnotationIsSetOnPreferenceAppliedHeader()
 {
     IODataResponseMessage responseMessage = new InMemoryMessage();
     responseMessage.PreferenceAppliedHeader().AnnotationFilter = "*";
     ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings());
     reader.Settings.ShouldIncludeAnnotation.Should().NotBeNull();
 }
 public void ReadValueOfTypeDefinitionShouldWork()
 {
     Stream stream = new MemoryStream(Encoding.Default.GetBytes("123"));
     IODataResponseMessage responseMessage = new InMemoryMessage() { StatusCode = 200, Stream = stream };
     ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel());
     reader.ReadValue(new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "Length", EdmPrimitiveTypeKind.Int32), true)).Should().Be(123);
 }
        public void EntryMetadataUrlRoundTrip()
        {
            var stream = new MemoryStream();
            var writerRequestMemoryMessage = new InMemoryMessage();
            writerRequestMemoryMessage.Stream = stream;
            writerRequestMemoryMessage.SetHeader("Content-Type", "application/json");

            var writerSettings = new ODataMessageWriterSettings() {Version = ODataVersion.V4, DisableMessageStreamDisposal = true};
            writerSettings.ODataUri = new ODataUri() {ServiceRoot = new Uri("http://christro.svc/")};

            var messageWriter = new ODataMessageWriter((IODataResponseMessage)writerRequestMemoryMessage, writerSettings, this.model);
            var organizationSetWriter = messageWriter.CreateODataEntryWriter(this.organizationsSet);
            var odataEntry = new ODataEntry(){ TypeName = ModelNamespace + ".Corporation" };
            odataEntry.Property("Id", 1);
            odataEntry.Property("Name", "");
            odataEntry.Property("TickerSymbol", "MSFT");

            organizationSetWriter.WriteStart(odataEntry);
            organizationSetWriter.WriteEnd();

            var readerPayloadInput = Encoding.UTF8.GetString(stream.GetBuffer());
            Console.WriteLine(readerPayloadInput);

            var readerResponseMemoryMessage = new InMemoryMessage();
            readerResponseMemoryMessage.Stream = new MemoryStream(stream.GetBuffer());
            readerResponseMemoryMessage.SetHeader("Content-Type", "application/json");

            var messageReader = new ODataMessageReader((IODataResponseMessage)readerResponseMemoryMessage, new ODataMessageReaderSettings() {MaxProtocolVersion = ODataVersion.V4, DisableMessageStreamDisposal = true}, this.model);
            var organizationReader = messageReader.CreateODataEntryReader(this.organizationsSet, this.organizationsSet.EntityType());
            organizationReader.Read().Should().Be(true);
            organizationReader.Item.As<ODataEntry>();
        }
 public void EncodingShouldRemainInvariantInReader()
 {
     Stream stream = new MemoryStream(Encoding.GetEncoding("iso-8859-1").GetBytes("{\"@odata.context\":\"http://stuff/#Edm.Int32\",\"value\":4}"));
     IODataResponseMessage responseMessage = new InMemoryMessage() { StatusCode = 200, Stream = stream };
     responseMessage.SetHeader("Content-Type", "application/json;odata.metadata=minimal;");
     ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel());
     reader.ReadProperty();
 }
 public void CreateMessageReaderShouldNotSetAnnotationFilterWhenItIsAlreadySet()
 {
     IODataResponseMessage responseMessage = new InMemoryMessage();
     responseMessage.PreferenceAppliedHeader().AnnotationFilter = "*";
     Func<string, bool> shouldWrite = name => false;
     ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings { ShouldIncludeAnnotation = shouldWrite });
     reader.Settings.ShouldIncludeAnnotation.Should().BeSameAs(shouldWrite);
 }
        public void GetDataServiceVersionWorksForResponse()
        {
            InMemoryMessage simulatedRequestMessage = new InMemoryMessage();
            simulatedRequestMessage.SetHeader(ODataConstants.ODataVersionHeader, "4.0");

            IODataResponseMessage response = new ODataResponseMessage(simulatedRequestMessage, false, false, long.MaxValue);
            ODataVersion version = response.GetODataVersion(ODataVersion.V4);
            version.Should().Be(ODataUtils.StringToODataVersion(response.GetHeader(ODataConstants.ODataVersionHeader)));
        }
        public void GetHeaderGoesToInnerMessageAfterConstruction()
        {
            const string headerName = "CustomHeaderName";
            const string headerValue = "CustomerHeaderValue";

            var simulatedRequestMessage = new InMemoryMessage();
            simulatedRequestMessage.SetHeader(headerName, headerValue);
            
            var odataRequestMessage = new ODataRequestMessage(simulatedRequestMessage, false, false, -1);

            odataRequestMessage.GetHeader(headerName).Should().Be(headerValue);
        }
        private byte[] ClientWriteAsyncBatchRequest()
        {
            var stream = new MemoryStream();

            IODataRequestMessage requestMessage = new InMemoryMessage { Stream = stream };
            requestMessage.SetHeader("Content-Type", batchContentType);

            using (var messageWriter = new ODataMessageWriter(requestMessage))
            {
                var batchWriter = messageWriter.CreateODataBatchWriter();

                batchWriter.WriteStartBatch();

                // Write a query operation.
                var queryOperationMessage = batchWriter.CreateOperationRequestMessage("GET", new Uri(serviceDocumentUri + "/Customers('ALFKI')"), /*contentId*/ null);

                // Write a changeset with multi update operation.
                batchWriter.WriteStartChangeset();

                // Create a creation operation in the changeset.
                var updateOperationMessage = batchWriter.CreateOperationRequestMessage("POST", new Uri(serviceDocumentUri + "/Customers"), "1");

                // Use a new message writer to write the body of this operation.
                using (var operationMessageWriter = new ODataMessageWriter(updateOperationMessage))
                {
                    var entryWriter = operationMessageWriter.CreateODataEntryWriter();
                    var entry = new ODataEntry() { TypeName = "MyNS.Customer", Properties = new[] { new ODataProperty() { Name = "Id", Value = "AFKIL" }, new ODataProperty() { Name = "Name", Value = "Bob" } } };
                    entryWriter.WriteStart(entry);
                    entryWriter.WriteEnd();
                }

                updateOperationMessage = batchWriter.CreateOperationRequestMessage("PATCH", new Uri(serviceDocumentUri + "/Customers('ALFKI')"), "2");

                using (var operationMessageWriter = new ODataMessageWriter(updateOperationMessage))
                {
                    var entryWriter = operationMessageWriter.CreateODataEntryWriter();
                    var entry = new ODataEntry() { TypeName = "MyNS.Customer", Properties = new[] { new ODataProperty() { Name = "Name", Value = "Jack" } } };
                    entryWriter.WriteStart(entry);
                    entryWriter.WriteEnd();
                }

                batchWriter.WriteEndChangeset();

                // Write a query operation.
                batchWriter.CreateOperationRequestMessage("GET", new Uri(serviceDocumentUri + "/Products"), /*contentId*/ null);

                batchWriter.WriteEndBatch();

                stream.Position = 0;
                return stream.ToArray();
            }
        }
        public void SetHeaderIsNotAllowedWhenReading()
        {
            const string headerName = "CustomHeaderName";
            const string headerValueBefore = "CustomerHeaderValueBefore";
            const string headerValueAfter = "CustomerHeaderValueAfter";

            var simulatedRequestMessage = new InMemoryMessage(); 
            simulatedRequestMessage.SetHeader(headerName, headerValueBefore);
            
            var odataRequestMessage = new ODataRequestMessage(simulatedRequestMessage, false, false, -1);
            Action setHeader = (() => odataRequestMessage.SetHeader(headerName, headerValueAfter));
            setHeader.ShouldThrow<ODataException>().WithMessage(Strings.ODataMessage_MustNotModifyMessage);
        }
        public void GetHeaderOnInnerMessagePicksUpSetHeaderFromOuterCallOnWriting()
        {
            const string headerName = "CustomHeaderName";
            const string headerValueBefore = "CustomerHeaderValueBefore";
            const string headerValueAfter = "CustomerHeaderValueAfter";

            var simulatedRequestMessage = new InMemoryMessage { Method = "GET", Url = new Uri("http://example.com/Customers") }; 
            simulatedRequestMessage.SetHeader(headerName, headerValueBefore);
            
            var odataRequestMessage = new ODataRequestMessage(simulatedRequestMessage, true, false, -1);
            odataRequestMessage.SetHeader(headerName, headerValueAfter);

            simulatedRequestMessage.GetHeader(headerName).Should().Be(headerValueAfter);
        }
Ejemplo n.º 12
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");
        }
Ejemplo n.º 13
0
        public void JsonPaddingEnabledWithUserSpecifiedContentType()
        {
            var settings = new ODataMessageWriterSettings {JsonPCallback = "functionName", DisableMessageStreamDisposal = true};
            settings.SetServiceDocumentUri(new Uri("http://stuff"));
            IODataResponseMessage message = new InMemoryMessage {StatusCode = 200, Stream = new MemoryStream()};
            message.SetHeader("Content-Type", "application/json");
            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.AreEqual(expectedPayload, payload);
        }
        public void ReadingInMinialMetadataModeUseDefaultCtorWithContainedEntitySetOfAnotherTypeShouldBeAbleToGenerateId()
        {
            const string payload =
                "{" +
                    "\"@odata.context\":\"http://example.com/$metadata#EntitySet(1)/AnotherContainedNavProp\"," +
                    "\"value\":[" +
                    "{" +
                    "\"ID\" : 123," +
                    "\"Name\" : \"Bob\"" +
                    "}" +
                "] }";

            InMemoryMessage message = new InMemoryMessage();
            message.SetHeader("Content-Type", "application/json;odata.metadata=minimal");
            message.Stream = new MemoryStream(Encoding.UTF8.GetBytes(payload));

            ODataEntry topLevelEntry = null;
            List<ODataEntry> entryList = new List<ODataEntry>();

            using (var messageReader = new ODataMessageReader((IODataResponseMessage)message, null, Model))
            {
                var reader = messageReader.CreateODataFeedReader();
                while (reader.Read())
                {
                    switch (reader.State)
                    {
                        case ODataReaderState.EntryEnd:
                            topLevelEntry = (ODataEntry)reader.Item;
                            entryList.Add(topLevelEntry);
                            break;
                    }
                }
            }

            Uri containedId = new Uri("http://example.com/EntitySet(1)/AnotherContainedNavProp(123)");

            ODataEntry containedEntry = entryList[0];
            containedEntry.Id.Should().Be(containedId);
        }
        public void ReadingInMinialMetadataModeWithContainedElementShouldBeAbleToGenerateId()
        {
            const string payload =
                "{" +
                    "\"@odata.context\":\"http://example.com/$metadata#EntitySet(ContainedNavProp2,ExpandedNavLink,ExpandedNavLink(ContainedNavProp2))\"," +
                    "\"value\":[" +
                    "{" +
                        "\"[email protected]\":\"http://example.com/$metadata#EntitySet(123)/ContainedNonCollectionNavProp/$entity\"," +
                        "\"ContainedNonCollectionNavProp\":" +
                        "{" +
                            "\"ID\": 234," +
                            "\"Name\":\"Foo\"" +
                        "}," +
                    "\"ID\" : 123," +
                    "\"Name\" : \"Bob\"" +
                "} ] }";

            InMemoryMessage message = new InMemoryMessage();
            message.SetHeader("Content-Type", "application/json;odata.metadata=mini");
            message.Stream = new MemoryStream(Encoding.UTF8.GetBytes(payload));

            ODataEntry topLevelEntry = null;
            List<ODataEntry> entryList = new List<ODataEntry>();

            using (var messageReader = new ODataMessageReader((IODataResponseMessage)message, null, Model))
            {
                var reader = messageReader.CreateODataFeedReader(EntitySet, EntityType);
                while (reader.Read())
                {
                    switch (reader.State)
                    {
                        case ODataReaderState.EntryEnd:
                            topLevelEntry = (ODataEntry)reader.Item;
                            entryList.Add(topLevelEntry);
                            break;
                    }
                }
            }

            Uri containedId = new Uri("http://example.com/EntitySet(123)/ContainedNonCollectionNavProp");

            ODataEntry containedEntry = entryList[0];
            containedEntry.Id.Should().Be(containedId);
        }
        private static void RunClientRequest(Action<DataServiceContext> runTest, string expectedRequestPayload = null, string responsePayload = null, Action<IODataResponseMessage> setupResponse = null)
        {
            using (var requestStream = new MemoryStream())
            using (var responseStream = responsePayload == null ? new MemoryStream() : new MemoryStream(Encoding.UTF8.GetBytes(responsePayload)))
            {
                responseStream.Position = 0;
                var requestMessage = new InMemoryMessage {Stream = requestStream};
                var responseMessage = new InMemoryMessage {Stream = responseStream};
                if (setupResponse != null)
                {
                    setupResponse(responseMessage);
                }

                DataServiceContext ctx = new DataServiceContextWithCustomTransportLayer(ODataProtocolVersion.V4, requestMessage, responseMessage);
                runTest(ctx);

                if (expectedRequestPayload != null)
                {
                    var actualRequestPayload = Encoding.UTF8.GetString(requestStream.ToArray());
                    Assert.AreEqual(expectedRequestPayload, actualRequestPayload);
                }
            }
        }
        private byte[] ServiceReadAsyncBatchRequestAndWriteAsyncResponse(byte[] requestPayload)
        {
            IODataRequestMessage requestMessage = new InMemoryMessage() { Stream = new MemoryStream(requestPayload) };
            requestMessage.SetHeader("Content-Type", batchContentType);

            using (var messageReader = new ODataMessageReader(requestMessage, new ODataMessageReaderSettings(), this.userModel))
            {
                var responseStream = new MemoryStream();

                IODataResponseMessage responseMessage = new InMemoryMessage { Stream = responseStream };
                responseMessage.SetHeader("Content-Type", batchContentType);
                var messageWriter = new ODataMessageWriter(responseMessage);
                var batchWriter = messageWriter.CreateODataBatchWriter();
                batchWriter.WriteStartBatch();

                var batchReader = messageReader.CreateODataBatchReader();
                while (batchReader.Read())
                {
                    switch (batchReader.State)
                    {
                        case ODataBatchReaderState.Operation:
                            // Encountered an operation (either top-level or in a changeset)
                            var operationMessage = batchReader.CreateOperationRequestMessage();
                            if (operationMessage.Method == "GET" && operationMessage.Url.AbsolutePath.Contains("ALFKI"))
                            {
                                var response = batchWriter.CreateOperationResponseMessage(null);
                                response.StatusCode = 200;
                                response.SetHeader("Content-Type", "application/json;");
                                var settings = new ODataMessageWriterSettings();
                                settings.SetServiceDocumentUri(new Uri(serviceDocumentUri));
                                using (var operationMessageWriter = new ODataMessageWriter(response, settings, this.userModel))
                                {
                                    var entryWriter = operationMessageWriter.CreateODataEntryWriter(this.customers, this.customerType);
                                    var entry = new ODataEntry() { TypeName = "MyNS.Customer", Properties = new[] { new ODataProperty() { Name = "Id", Value = "ALFKI" }, new ODataProperty() { Name = "Name", Value = "John" } } };
                                    entryWriter.WriteStart(entry);
                                    entryWriter.WriteEnd();
                                }
                            }
                            break;
                    }
                }

                var asyncResponse = batchWriter.CreateOperationResponseMessage(null);
                asyncResponse.StatusCode = 202;
                asyncResponse.SetHeader("Location", "http://service/async-monitor");
                asyncResponse.SetHeader("Retry-After", "10");

                batchWriter.WriteEndBatch();

                responseStream.Position = 0;
                return responseStream.ToArray();
            }
        }
        private void ClientReadAsyncBatchResponse(byte[] responsePayload)
        {
            IODataResponseMessage responseMessage = new InMemoryMessage() { Stream = new MemoryStream(responsePayload) };
            responseMessage.SetHeader("Content-Type", batchContentType);
            using (var messageReader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), this.userModel))
            {
                var batchReader = messageReader.CreateODataBatchReader();
                while (batchReader.Read())
                {
                    switch (batchReader.State)
                    {
                        case ODataBatchReaderState.Operation:
                            // Encountered an operation (either top-level or in a changeset)
                            var operationMessage = batchReader.CreateOperationResponseMessage();
                            if (operationMessage.StatusCode == 200)
                            {
                                using (ODataMessageReader innerMessageReader = new ODataMessageReader(operationMessage, new ODataMessageReaderSettings(), this.userModel))
                                {
                                    var reader = innerMessageReader.CreateODataEntryReader();

                                    while (reader.Read())
                                    {
                                        if (reader.State == ODataReaderState.EntryEnd)
                                        {
                                            ODataEntry entry = reader.Item as ODataEntry;
                                            Assert.AreEqual("ALFKI", entry.Properties.Single(p => p.Name == "Id").Value);
                                            Assert.AreEqual("John", entry.Properties.Single(p => p.Name == "Name").Value);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                Assert.AreEqual(202, operationMessage.StatusCode);
                            }
                            break;
                    }
                }
            }
        }
        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 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;
        }
        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;
        }
 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 void ReadEntryPayload(EdmModel userModel, string payload, IEdmEntityType entityType, Action<ODataReader> action)
 {
     var message = new InMemoryMessage() { Stream = new MemoryStream(Encoding.UTF8.GetBytes(payload)) };
     message.SetHeader("Content-Type", "application/atom+xml;type=entry");
     var readerSettings = new ODataMessageReaderSettings { DisableMessageStreamDisposal = false, EnableAtom = true};
     using (var msgReader = new ODataMessageReader((IODataResponseMessage)message, readerSettings, userModel))
     {
         var reader = msgReader.CreateODataEntryReader(entityType);
         while (reader.Read())
         {
             action(reader);
         }
     }
 }
            protected virtual InMemoryMessage CreateRequestMessage(DataServiceClientRequestMessageArgs requestMessageArgs)
            {
                var requestMessage = new InMemoryMessage { Url = requestMessageArgs.RequestUri, Method = requestMessageArgs.Method, Stream = new MemoryStream() };

                foreach (var header in requestMessageArgs.Headers)
                {
                    requestMessage.SetHeader(header.Key, header.Value);
                }

                return requestMessage;
            }
 protected override InMemoryMessage CreateRequestMessage(DataServiceClientRequestMessageArgs requestMessageArgs)
 {
     this.lastMessageCreated = base.CreateRequestMessage(requestMessageArgs);
     return this.lastMessageCreated;
 }
        public void ReadingInMinialMetadataModeWithContainedEntitySetShouldBeAbleToGenerateId()
        {
            const string payload =
                "{" +
                    "\"@odata.context\":\"http://example.com/$metadata#EntitySet(1)/ContainedNavProp(ID)\"," +
                    "\"value\":[" +
                    "{" +
                    "\"ID\" : 123" +
                    "}" +
                "] }";

            InMemoryMessage message = new InMemoryMessage();
            message.SetHeader("Content-Type", "application/json;odata.metadata=minimal");
            message.Stream = new MemoryStream(Encoding.UTF8.GetBytes(payload));

            ODataEntry topLevelEntry = null;
            List<ODataEntry> entryList = new List<ODataEntry>();

            using (var messageReader = new ODataMessageReader((IODataResponseMessage)message, null, Model))
            {
                var navProp = EntityType.FindProperty("ContainedNavProp") as IEdmNavigationProperty;
                var containedEntitySet = EntitySet.FindNavigationTarget(navProp) as IEdmEntitySetBase;
                var reader = messageReader.CreateODataFeedReader(containedEntitySet, EntityType);
                while (reader.Read())
                {
                    switch (reader.State)
                    {
                        case ODataReaderState.EntryEnd:
                            topLevelEntry = (ODataEntry)reader.Item;
                            entryList.Add(topLevelEntry);
                            break;
                    }
                }
            }

            Uri containedId = new Uri("http://example.com/EntitySet(1)/ContainedNavProp(123)");

            ODataEntry containedEntry = entryList[0];
            containedEntry.Id.Should().Be(containedId);
        }
        // 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);
            }
        }
Ejemplo n.º 29
0
        private ParameterReaderResult RunParameterReaderTest(string payload)
        {
            var message = new InMemoryMessage();

            message.Stream = new MemoryStream(Encoding.UTF8.GetBytes(payload));
            message.SetHeader("Content-Type", "application/json");

            var parameterReaderResult = new ParameterReaderResult();
            using (var messageReader = new ODataMessageReader((IODataRequestMessage)message, null, this.model))
            {
                var parameterReader = messageReader.CreateODataParameterReader(this.action);

                while (parameterReader.Read())
                {
                    switch (parameterReader.State)
                    {
                        case ODataParameterReaderState.Value:
                        {
                            parameterReaderResult.Values.Add(new KeyValuePair<string, object>(parameterReader.Name, parameterReader.Value));
                            break;
                        }
                        case ODataParameterReaderState.Collection:
                        {
                            var collection = new ParameterReaderCollection();
                            parameterReaderResult.Collections.Add(new KeyValuePair<string, ParameterReaderCollection>(parameterReader.Name, collection));
                            var collectionReader = parameterReader.CreateCollectionReader();
                            while (collectionReader.Read())
                            {
                                switch (collectionReader.State)
                                {
                                    case ODataCollectionReaderState.Value:
                                    {
                                        collection.Items.Add(collectionReader.Item);
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                        case ODataParameterReaderState.Entry:
                        {
                            var entryReader = parameterReader.CreateEntryReader();

                            var entryList = new List<ODataEntry>();
                            parameterReaderResult.Entries.Add(new KeyValuePair<string, IList<ODataEntry>>(parameterReader.Name, entryList));
                            while (entryReader.Read())
                            {
                                switch (entryReader.State)
                                {
                                    case ODataReaderState.EntryEnd:
                                        entryList.Add((ODataEntry)entryReader.Item);
                                        break;

                                }
                            }
                            break;
                        }
                        case ODataParameterReaderState.Feed:
                        {
                            var entryReader = parameterReader.CreateFeedReader();
                            
                            var entryList = new List<ODataEntry>();
                            parameterReaderResult.Entries.Add(new KeyValuePair<string, IList<ODataEntry>>(parameterReader.Name, entryList));

                            var feedList = new List<ODataFeed>();
                            parameterReaderResult.Feeds.Add(new KeyValuePair<string, IList<ODataFeed>>(parameterReader.Name, feedList));

                            while (entryReader.Read())
                            {
                                switch (entryReader.State)
                                {
                                    case ODataReaderState.EntryEnd:
                                        entryList.Add((ODataEntry)entryReader.Item);
                                        break;
                                    case ODataReaderState.FeedEnd:
                                        feedList.Add((ODataFeed)entryReader.Item);
                                        break;
                                }
                            }
                            break;
                        }
                    }
                }
            }

            return parameterReaderResult;
        }
        public void DisposeShouldBeCalledOnResponseMessageForExecuteWithNoContent()
        {
            DataServiceContext context = new DataServiceContext();
            bool responseMessageDisposed = false;
            context.Configurations.RequestPipeline.OnMessageCreating = args =>
            {
                var requestMessage = new InMemoryMessage { Url = args.RequestUri, Method = args.Method, Stream = new MemoryStream() };
                var responseMessage = new InMemoryMessage { StatusCode = 204, Stream = new MemoryStream() };
                responseMessage.DisposeAction = () => responseMessageDisposed = true;
                return new TestDataServiceClientRequestMessage(requestMessage, () => responseMessage);
            };

            context.Execute(new Uri("http://host/voidAction", UriKind.Absolute), "POST").StatusCode.Should().Be(204);
            responseMessageDisposed.Should().BeTrue();
        }