public void WriterSettingsIntegrationTest()
        {
            var settings = new ODataMessageWriterSettings();
            settings.SetServiceDocumentUri(ServiceDocumentUri);
            settings.MetadataDocumentUri.Should().Equals(ServiceDocumentUri + "/$metadata");

            settings.SetServiceDocumentUri(null);
            settings.MetadataDocumentUri.Should().BeNull();
        }
        public void WriteCompletedAsyncResponse()
        {
            var asyncWriter = this.TestInit();

            var innerMessage = asyncWriter.CreateResponseMessage();
            innerMessage.StatusCode = 200;
            innerMessage.SetHeader("Content-Type", "application/json");

            var settings = new ODataMessageWriterSettings();
            settings.SetServiceDocumentUri(new Uri(ServiceDocumentUri));
            settings.DisableMessageStreamDisposal = true;

            using (var innerMessageWriter = new ODataMessageWriter(innerMessage, settings, this.userModel))
            {
                var entryWriter = innerMessageWriter.CreateODataEntryWriter(singleton, testType);
                var entry = new ODataEntry() {TypeName = "NS.Test", Properties = new[] {new ODataProperty() {Name = "Id", Value = 1}}};
                entryWriter.WriteStart(entry);
                entryWriter.WriteEnd();
            }

            asyncWriter.Flush();

            var payload = this.TestFinish();
            Assert.Equal("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nOData-Version: 4.0\r\n\r\n{\"@odata.context\":\"http://host/service/$metadata#MySingleton\",\"Id\":1}", payload);
        }
 public ODataJsonLightValueSerializerTests()
 {
     model = new EdmModel();
     stream = new MemoryStream();
     settings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true, Version = ODataVersion.V4 };
     settings.SetServiceDocumentUri(new Uri("http://example.com"));
 }
        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");
        }
        private ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream)
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4
            };

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

            return(new ODataJsonLightOutputContext(
                       ODataFormat.Json,
                       new NonDisposingStream(stream),
                       new ODataMediaType("application", "json"),
                       Encoding.UTF8,
                       settings,
                       /*writingResponse*/ true,
                       /*synchronous*/ true,
                       this.model,
                       /*urlResolver*/ null));
        }
Exemple #6
0
        private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, bool writingResponse = true, bool synchronous = true)
        {
            var messageInfo = new ODataMessageInfo
            {
                MessageStream = new NonDisposingStream(stream),
                MediaType     = new ODataMediaType("application", "json"),
                Encoding      = Encoding.UTF8,
                IsResponse    = writingResponse,
                IsAsync       = !synchronous,
                Model         = EdmCoreModel.Instance
            };

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

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

            return(new ODataJsonLightOutputContext(messageInfo, settings));
        }
        private ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream)
        {
            var settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4
            };

            settings.SetServiceDocumentUri(new Uri("http://example.com/"));

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

            return(new ODataJsonLightOutputContext(messageInfo, settings));
        }
Exemple #8
0
        private string WriteEntryPayload(EdmEntitySet entitySet, EdmEntityType entityType, Action <ODataWriter> action)
        {
            MemoryStream          stream  = new MemoryStream();
            IODataResponseMessage message = new InMemoryMessage()
            {
                Stream = stream
            };

            message.SetHeader("Content-Type", "application/json");
            writerSettings.SetServiceDocumentUri(new Uri("http://www.sampletest.com"));
            using (var msgReader = new ODataMessageWriter((IODataResponseMessage)message, writerSettings, this.serverModel))
            {
                var writer = msgReader.CreateODataResourceWriter(entitySet, entityType);
                action(writer);

                stream.Seek(0, SeekOrigin.Begin);
                string payload = (new StreamReader(stream)).ReadToEnd();
                return(payload);
            }
        }
        private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, bool writingResponse = true, bool synchronous = true)
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4
            };

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

            return(new ODataJsonLightOutputContext(
                       ODataFormat.Json,
                       new NonDisposingStream(stream),
                       new ODataMediaType("application", "json"),
                       Encoding.UTF8,
                       settings,
                       writingResponse,
                       synchronous,
                       EdmCoreModel.Instance,
                       /*urlResolver*/ null));
        }
        private void WriteEntry()
        {
            var asyncWriter = this.CreateAsyncWriter();

            var innerMessage = asyncWriter.CreateResponseMessage();
            innerMessage.StatusCode = 200;
            innerMessage.SetHeader("Content-Type", "application/json");

            var settings = new ODataMessageWriterSettings();
            settings.SetServiceDocumentUri(new Uri(ServiceDocumentUri));
            settings.DisableMessageStreamDisposal = true;

            using (var innerMessageWriter = new ODataMessageWriter(innerMessage, settings, userModel))
            {
                var entryWriter = innerMessageWriter.CreateODataEntryWriter(singleton, testType);
                entryWriter.WriteStart(entry);
                entryWriter.WriteEnd();
            }

            asyncWriter.Flush();
        }
        private ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream)
        {
            var settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4
            };

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

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

            return(new ODataJsonLightOutputContext(messageInfo, settings));
        }
Exemple #12
0
        private static ODataJsonLightSerializer GetSerializer(Stream stream, string jsonpFunctionName = null, bool nometadata = false, bool setMetadataDocumentUri = true)
        {
            var model       = new EdmModel();
            var complexType = new EdmComplexType("ns", "ErrorDetails");

            //var collectionType = new EdmCollectionType(new EdmComplexTypeReference(complexType, false));
            model.AddElement(complexType);

            var settings = new ODataMessageWriterSettings {
                JsonPCallback = jsonpFunctionName, DisableMessageStreamDisposal = true, Version = ODataVersion.V4
            };

            if (setMetadataDocumentUri)
            {
                settings.SetServiceDocumentUri(new Uri("http://example.com"));
            }
            ODataMediaType mediaType = nometadata ? new ODataMediaType("application", "json", new KeyValuePair <string, string>("odata", "none")) : new ODataMediaType("application", "json");
            IEdmModel      mainModel = TestUtils.WrapReferencedModelsToMainModel(model);
            var            context   = new ODataJsonLightOutputContext(ODataFormat.Json, stream, mediaType, Encoding.Default, settings, true, true, mainModel, null);

            return(new ODataJsonLightSerializer(context, setMetadataDocumentUri));
        }
        protected void WriteAnnotationsAndValidatePayload(Action <ODataWriter> action, ODataFormat format, string expectedPayload, bool request, bool createFeedWriter)
        {
            var writerSettings = new ODataMessageWriterSettings {
                EnableMessageStreamDisposal = false
            };

            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.CreateODataResourceSetWriter(EntitySet, EntityType) : messageWriter.CreateODataResourceWriter(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.CreateODataResourceSetWriter(EntitySet, EntityType) : messageWriter.CreateODataResourceWriter(EntitySet, EntityType);
                    action(odataWriter);
                }
            }

            stream.Position = 0;
            string payload = (new StreamReader(stream)).ReadToEnd();

            Assert.Equal(expectedPayload, payload);
        }
Exemple #14
0
//        [TestMethod, Variation(Description = "Test feeds with invalid content.")]
        public void FeedInvalidContentTests()
        {
            ODataResourceSet defaultFeed = ObjectModelUtils.CreateDefaultFeed();

            ODataItem[] invalidPayload1 = new ODataItem[] { defaultFeed, defaultFeed };

            var testCases = new[]
            {
                new
                {
                    Items         = invalidPayload1,
                    ExpectedError = "Cannot transition from state 'ResourceSet' to state 'ResourceSet'. The only valid action in state 'ResourceSet' is to write a resource."
                }
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                ODataFormatUtils.ODataFormats.Where(f => f != null),
                new bool[] { false, true },
                (testCase, format, synchronous) =>
            {
                using (var memoryStream = new TestStream())
                {
                    ODataMessageWriterSettings settings = new ODataMessageWriterSettings();
                    settings.Version = ODataVersion.V4;
                    settings.SetServiceDocumentUri(ServiceDocumentUri);

                    using (var messageWriter = TestWriterUtils.CreateMessageWriter(memoryStream, new WriterTestConfiguration(format, settings, false, synchronous), this.Assert))
                    {
                        ODataWriter writer = messageWriter.CreateODataWriter(isFeed: true);
                        TestExceptionUtils.ExpectedException <ODataException>(
                            this.Assert,
                            () => TestWriterUtils.WritePayload(messageWriter, writer, true, testCase.Items),
                            testCase.ExpectedError);
                    }
                }
            });
        }
Exemple #15
0
        private void WriteEntry()
        {
            var asyncWriter = this.CreateAsyncWriter();

            var innerMessage = asyncWriter.CreateResponseMessage();

            innerMessage.StatusCode = 200;
            innerMessage.SetHeader("Content-Type", "application/json");

            var settings = new ODataMessageWriterSettings();

            settings.SetServiceDocumentUri(new Uri(ServiceDocumentUri));
            settings.EnableMessageStreamDisposal = false;

            using (var innerMessageWriter = new ODataMessageWriter(innerMessage, settings, userModel))
            {
                var entryWriter = innerMessageWriter.CreateODataResourceWriter(singleton, testType);
                entryWriter.WriteStart(entry);
                entryWriter.WriteEnd();
            }

            asyncWriter.Flush();
        }
Exemple #16
0
        private static ODataMessageWriter CreateODataMessageWriter(IEdmModel model, string contentType)
        {
            var settings = new ODataMessageWriterSettings {
                EnableMessageStreamDisposal = false, Version = ODataVersion.V4
            };

            settings.SetServiceDocumentUri(new Uri("http://example.com"));

            var message = new InMemoryMessage();

            message.Stream = new MemoryStream();
            message.SetHeader("Accept", contentType);
            message.SetHeader("Content-Type", contentType);
            message.SetHeader("OData-Version", "4.0");
            if (model == null)
            {
                return(new ODataMessageWriter((IODataRequestMessage)message, settings));
            }
            else
            {
                return(new ODataMessageWriter((IODataRequestMessage)message, settings, model));
            }
        }
Exemple #17
0
        private static string GetWriterOutput(ODataResource entry, EdmModel model, IEdmEntitySetBase entitySet, EdmEntityType entityType, IServiceProvider container)
        {
            var outputStream = new MemoryStream();
            IODataResponseMessage message = new InMemoryMessage
            {
                Stream    = outputStream,
                Container = container
            };

            message.SetHeader("Content-Type", "application/json");
            var settings = new ODataMessageWriterSettings();

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

            using (var messageWriter = new ODataMessageWriter(message, settings, model))
            {
                var writer = messageWriter.CreateODataResourceWriter(entitySet, entityType);
                writer.WriteStart(entry);
                writer.WriteEnd();
                outputStream.Seek(0, SeekOrigin.Begin);
                return(new StreamReader(outputStream).ReadToEnd());
            }
        }
        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 static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, IEdmModel userModel, bool fullMetadata = false, ODataUri uri = null)
        {
            var settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4, ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*")
            };

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

            IEnumerable <KeyValuePair <string, string> > parameters;

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

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

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

            return(new ODataJsonLightOutputContext(messageInfo, settings));
        }
Exemple #20
0
        private string WriterEntry(IEdmModel userModel, ODataResource entry, EdmEntitySet entitySet, IEdmEntityType entityType, bool fullMetadata = false, Action <ODataWriter> writeAction = null)
        {
            var message = new InMemoryMessage()
            {
                Stream = new MemoryStream()
            };

            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());
            }
        }
        private string GetWriterOutput(IEdmModel model, Action <ODataMessageWriter> writeAction)
        {
            MemoryStream          outputStream = new MemoryStream();
            IODataResponseMessage message      = new InMemoryMessage()
            {
                Stream = outputStream
            };

            message.SetHeader("Content-Type", "application/json;odata.metadata=minimal");
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings();

            settings.SetServiceDocumentUri(new Uri("http://example.com"));

            string output;

            using (var messageWriter = new ODataMessageWriter(message, settings, model))
            {
                writeAction(messageWriter);
                outputStream.Seek(0, SeekOrigin.Begin);
                output = new StreamReader(outputStream).ReadToEnd();
            }

            return(output);
        }
        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);
        }
Exemple #23
0
        private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, IEdmModel userModel, bool fullMetadata = false, ODataUri uri = null)
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4, AutoComputePayloadMetadataInJson = true, ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*")
            };

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

            IEnumerable <KeyValuePair <string, string> > parameters;

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

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

            return(new ODataJsonLightOutputContext(
                       ODataFormat.Json,
                       new NonDisposingStream(stream),
                       mediaType,
                       Encoding.UTF8,
                       settings,
                       /*writingResponse*/ true,
                       /*synchronous*/ true,
                       userModel ?? EdmCoreModel.Instance,
                       /*urlResolver*/ null));
        }
        private ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, bool writingResponse = true, bool setMetadataDocumentUri = true)
        {
            IEdmModel model = new EdmModel();

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

            if (setMetadataDocumentUri)
            {
                settings.SetServiceDocumentUri(this.serviceDocumentUri);
            }

            return(new ODataJsonLightOutputContext(
                       ODataFormat.Json,
                       new NonDisposingStream(stream),
                       new ODataMediaType("application", "json"),
                       Encoding.UTF8,
                       settings,
                       writingResponse,
                       /*synchronous*/ true,
                       TestUtils.WrapReferencedModelsToMainModel(model),
                       /*urlResolver*/ null));
        }
        private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, bool writingResponse = true, IEdmModel userModel = null, Uri serviceDocumentUri = null)
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings {
                Version = ODataVersion.V4, AutoComputePayloadMetadataInJson = true, ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*")
            };

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

            ODataMediaType mediaType = new ODataMediaType("application", "json", new KeyValuePair <string, string>("odata.metadata", "full"));

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

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

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

            return(new ODataJsonLightOutputContext(messageInfo, settings));
        }
        private void WriteDeltaFeedAnnotationsAndValidatePayload(Action<ODataDeltaWriter> action, IEdmEntitySet entitySet, string expectedPayload)
        {
            var writerSettings = new ODataMessageWriterSettings {DisableMessageStreamDisposal = true};
            writerSettings.SetServiceDocumentUri(new Uri("http://www.example.com/"));

            MemoryStream stream = new MemoryStream();

            IODataResponseMessage responseMessageToWrite = new InMemoryMessage {StatusCode = 200, Stream = stream};
            responseMessageToWrite.PreferenceAppliedHeader().AnnotationFilter = "*";
            using (var messageWriter = new ODataMessageWriter(responseMessageToWrite, writerSettings, Model))
            {
                ODataDeltaWriter odataDeltaWriter = messageWriter.CreateODataDeltaWriter(entitySet, EntityType);
                action(odataDeltaWriter);
            }

            stream.Position = 0;
            string payload = (new StreamReader(stream)).ReadToEnd();

            Assert.Equal(expectedPayload, payload);
        }
        private byte[] ServiceReadSingletonBatchRequestAndWriterBatchResponse(ODataJsonBatchPayloadTestCase testCase, ODataVersion version)
        {
            string requestPayload = testCase.RequestPayload;
            Action <ODataBatchOperationRequestMessage, IList <string> > requestOpMessageVerifier = testCase.RequestMessageDependsOnIdVerifier;

            IODataRequestMessage requestMessage = new InMemoryMessage()
            {
                Stream = new MemoryStream(Encoding.ASCII.GetBytes(requestPayload))
            };

            requestMessage.SetHeader("Content-Type", batchContentTypeApplicationJson);

            MemoryStream responseStream = new MemoryStream();

            using (ODataMessageReader messageReader =
                       new ODataMessageReader(requestMessage, new ODataMessageReaderSettings()
            {
                Version = version
            }, this.edmModel))
            {
                IODataResponseMessage responseMessage = new InMemoryMessage {
                    Stream = responseStream
                };

                // Client is expected to receive the response message in the same format as that is used in the request sent.
                responseMessage.SetHeader("Content-Type", batchContentTypeApplicationJson);

                ODataMessageWriterSettings settings = new ODataMessageWriterSettings()
                {
                    Version = version
                };
                settings.SetServiceDocumentUri(new Uri(serviceDocumentUri));

                ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, settings, null);
                int operationIdx = 0;

                ODataBatchWriter batchWriter = messageWriter.CreateODataBatchWriter();
                batchWriter.WriteStartBatch();

                ODataBatchReader batchReader = messageReader.CreateODataBatchReader();
                while (batchReader.Read())
                {
                    switch (batchReader.State)
                    {
                    case ODataBatchReaderState.Operation:
                        // Encountered an operation (either top-level or in a change set)
                        ODataBatchOperationRequestMessage operationMessage = batchReader.CreateOperationRequestMessage();

                        // Verify operation message if applicable.
                        requestOpMessageVerifier?.Invoke(operationMessage, testCase.ListOfDependsOnIds.ElementAt(operationIdx));

                        if (operationMessage.Method == "POST")
                        {
                            ODataBatchOperationResponseMessage response = batchWriter.CreateOperationResponseMessage(operationMessage.ContentId);
                            response.StatusCode = 201;
                            response.SetHeader("Content-Type", batchContentTypeApplicationJson);
                        }
                        else if (operationMessage.Method == "GET")
                        {
                            ODataBatchOperationResponseMessage response = batchWriter.CreateOperationResponseMessage(operationMessage.ContentId);
                            response.StatusCode = 200;
                            response.SetHeader("Content-Type", batchContentTypeApplicationJson);

                            using (ODataMessageWriter operationMessageWriter = new ODataMessageWriter(response, settings, this.edmModel))
                            {
                                ODataWriter entryWriter = operationMessageWriter.CreateODataResourceWriter(this.singleton,
                                                                                                           this.userType);
                                ODataResource entry = new ODataResource()
                                {
                                    TypeName   = "NS.User",
                                    Properties =
                                        new[]
                                    {
                                        new ODataProperty()
                                        {
                                            Name = "UserPrincipalName", Value = "*****@*****.**"
                                        },
                                        new ODataProperty()
                                        {
                                            Name = "GivenName", Value = "Jon"
                                        }
                                    }
                                };
                                entryWriter.WriteStart(entry);
                                entryWriter.WriteEnd();
                            }
                        }

                        operationIdx++;
                        break;

                    case ODataBatchReaderState.ChangesetStart:
                        batchWriter.WriteStartChangeset();
                        break;

                    case ODataBatchReaderState.ChangesetEnd:
                        batchWriter.WriteEndChangeset();
                        break;
                    }
                }

                batchWriter.WriteEndBatch();
            }

            responseStream.Position = 0;
            return(responseStream.ToArray());
        }
        private ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, bool writingResponse = true, bool setMetadataDocumentUri = true)
        {
            IEdmModel model = new EdmModel();

            ODataMessageWriterSettings settings = new ODataMessageWriterSettings { Version = ODataVersion.V4 };
            if (setMetadataDocumentUri)
            {
                settings.SetServiceDocumentUri(this.serviceDocumentUri);
            }

            return new ODataJsonLightOutputContext(
                ODataFormat.Json,
                new NonDisposingStream(stream),
                new ODataMediaType("application", "json"),
                Encoding.UTF8,
                settings,
                writingResponse,
                /*synchronous*/ true,
                TestUtils.WrapReferencedModelsToMainModel(model),
                /*urlResolver*/ null);
        }
        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 byte[] ServiceReadBatchRequestAndWriterBatchResponse(byte[] requestPayload, BodyContentType bodyContentType)
        {
            IODataRequestMessage requestMessage = new InMemoryMessage()
            {
                Stream = new MemoryStream(requestPayload)
            };

            requestMessage.SetHeader(ODataConstants.ContentTypeHeader, batchContentTypeApplicationJson);

            using (ODataMessageReader messageReader = new ODataMessageReader(requestMessage, new ODataMessageReaderSettings(), null))
            {
                MemoryStream responseStream = new MemoryStream();

                IODataResponseMessage responseMessage = new InMemoryMessage {
                    Stream = responseStream
                };

                // Client is expected to receive the response message in the same format as that is used in the request sent.
                responseMessage.SetHeader(ODataConstants.ContentTypeHeader, batchContentTypeApplicationJson);
                ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage);
                ODataBatchWriter   batchWriter   = messageWriter.CreateODataBatchWriter();
                batchWriter.WriteStartBatch();

                ODataBatchReader batchReader = messageReader.CreateODataBatchReader();
                while (batchReader.Read())
                {
                    switch (batchReader.State)
                    {
                    case ODataBatchReaderState.Operation:

                        ODataBatchOperationRequestMessage operationMessage = batchReader.CreateOperationRequestMessage();

                        if (operationMessage.Method == "PUT")
                        {
                            using (Stream operationMessageBodyStream = operationMessage.GetStream())
                            {
                                // Verify the bytes in the request operation stream.
                                byte[] sampleBytes = bodyContentType == BodyContentType.Textual
                                        ? Encoding.UTF8.GetBytes("\"" + this.textualSampleStringA + "\"")
                                        : binarySampleBytesA;
                                Assert.Equal(operationMessageBodyStream.Length, sampleBytes.Length);
                                foreach (byte samplebyte in sampleBytes)
                                {
                                    Assert.Equal(samplebyte, operationMessageBodyStream.ReadByte());
                                }
                            }

                            // Create the response.
                            ODataBatchOperationResponseMessage operationResponse = batchWriter.CreateOperationResponseMessage(operationMessage.ContentId);
                            operationResponse.StatusCode = 201;
                            operationResponse.SetHeader("CoNtEnT-TyPe", "application/json;odata.metadata=none");
                        }
                        else if (operationMessage.Method == "GET")
                        {
                            ODataBatchOperationResponseMessage operationResponse = batchWriter.CreateOperationResponseMessage(operationMessage.ContentId);
                            operationResponse.StatusCode = 200;
                            operationResponse.SetHeader("CoNtEnT-TyPe", GetContentType(bodyContentType));
                            ODataMessageWriterSettings settings = new ODataMessageWriterSettings();
                            settings.SetServiceDocumentUri(new Uri(serviceDocumentUri));
                            using (ODataMessageWriter operationMessageWriter = new ODataMessageWriter(operationResponse, settings, null))
                            {
                                operationMessageWriter.WriteValue(GetEncodedContentObject(bodyContentType, false));
                            }
                        }

                        break;

                    case ODataBatchReaderState.ChangesetStart:
                        batchWriter.WriteStartChangeset();
                        break;

                    case ODataBatchReaderState.ChangesetEnd:
                        batchWriter.WriteEndChangeset();
                        break;
                    }
                }

                batchWriter.WriteEndBatch();
                responseStream.Position = 0;
                return(responseStream.ToArray());
            }
        }
        private byte[] ServiceReadBatchRequestAndWriteResponse(byte[] requestPayload)
        {
            IODataRequestMessage requestMessage = new InMemoryMessage()
            {
                Stream = new MemoryStream(requestPayload)
            };

            requestMessage.SetHeader("Content-Type", batchContentTypeApplicationJson);
            ODataMessageReaderSettings settings = new ODataMessageReaderSettings();

            settings.BaseUri = new Uri(serviceDocumentUri);

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

                IODataResponseMessage responseMessage = new InMemoryMessage {
                    Stream = responseStream
                };

                // Client is expected to receive the response message in the same format as that is used in the request sent.
                responseMessage.SetHeader("Content-Type", batchContentTypeApplicationJson);
                ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage);
                ODataBatchWriter   batchWriter   = messageWriter.CreateODataBatchWriter();
                batchWriter.WriteStartBatch();

                ODataBatchReader batchReader = messageReader.CreateODataBatchReader();
                while (batchReader.Read())
                {
                    switch (batchReader.State)
                    {
                    case ODataBatchReaderState.Operation:
                        // Encountered an operation (either top-level or in a change set)
                        ODataBatchOperationRequestMessage operationMessage = batchReader.CreateOperationRequestMessage();

                        ODataBatchOperationResponseMessage response =
                            batchWriter.CreateOperationResponseMessage(operationMessage.ContentId);

                        if (operationMessage.Method == "PUT")
                        {
                            response.StatusCode = 201;
                            response.SetHeader("Content-Type", "application/json;odata.metadata=none");
                        }
                        else if (operationMessage.Method == "PATCH")
                        {
                            response.StatusCode = 204;
                        }
                        else if (operationMessage.Method == "GET")
                        {
                            response.StatusCode = 200;
                            response.SetHeader("Content-Type", "application/json;");
                            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings();
                            writerSettings.SetServiceDocumentUri(new Uri(serviceDocumentUri));
                            using (var operationMessageWriter = new ODataMessageWriter(response, writerSettings, this.userModel))
                            {
                                var entryWriter = operationMessageWriter.CreateODataResourceWriter(this.singleton, this.webType);
                                var entry       = new ODataResource()
                                {
                                    TypeName   = "NS.Web",
                                    Properties = new[]
                                    {
                                        new ODataProperty()
                                        {
                                            Name = "WebId", Value = 11
                                        },
                                        new ODataProperty()
                                        {
                                            Name = "Name", Value = "SingletonWebForBatchJsonLightAtomicGroupIdTest"
                                        }
                                    }
                                };
                                entryWriter.WriteStart(entry);
                                entryWriter.WriteEnd();
                            }
                        }

                        break;

                    case ODataBatchReaderState.ChangesetStart:
                        // Set the group Id on the writer side to correlate with request.
                        string atomicGroupId = batchReader.CurrentGroupId;
                        batchWriter.WriteStartChangeset(atomicGroupId);
                        break;

                    case ODataBatchReaderState.ChangesetEnd:
                        batchWriter.WriteEndChangeset();
                        break;
                    }
                }

                batchWriter.WriteEndBatch();
                responseStream.Position = 0;
                return(responseStream.ToArray());
            }
        }
 private static ODataAtomOutputContext CreateAtomOutputContext(MemoryStream stream, ODataMediaType mediaType, bool writingResponse = true, IEdmModel userModel = null)
 {
     ODataMessageWriterSettings settings = new ODataMessageWriterSettings { Version = ODataVersion.V4, AutoComputePayloadMetadataInJson = true };
     settings.SetServiceDocumentUri(ServiceDocumentUri);
     return new ODataAtomOutputContext(
         ODataFormat.Atom,
         new NonDisposingStream(stream),
         Encoding.UTF8,
         settings,
         writingResponse,
         /*synchronous*/ true,
         userModel ?? EdmCoreModel.Instance,
         /*urlResolver*/ null);
 }
        private byte[] ServiceReadSingletonBatchRequestAndWriterBatchResponse(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 == "PATCH")
                        {
                            var response = batchWriter.CreateOperationResponseMessage(operationMessage.ContentId);
                            response.StatusCode = 204;
                            response.SetHeader("Content-Type", "application/json;odata.metadata=none");
                        }
                        else if (operationMessage.Method == "GET")
                        {
                            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.singleton, this.webType);
                                var entry       = new ODataEntry()
                                {
                                    TypeName = "NS.Web", Properties = new[] { new ODataProperty()
                                                                              {
                                                                                  Name = "WebId", Value = 10
                                                                              }, new ODataProperty()
                                                                              {
                                                                                  Name = "Name", Value = "WebSingleton"
                                                                              } }
                                };
                                entryWriter.WriteStart(entry);
                                entryWriter.WriteEnd();
                            }
                        }
                        else if (operationMessage.Method == "DELETE")
                        {
                            var response = batchWriter.CreateOperationResponseMessage(operationMessage.ContentId);
                            response.StatusCode = 500;
                        }

                        break;

                    case ODataBatchReaderState.ChangesetStart:
                        batchWriter.WriteStartChangeset();
                        break;

                    case ODataBatchReaderState.ChangesetEnd:
                        batchWriter.WriteEndChangeset();
                        break;
                    }
                }

                batchWriter.WriteEndBatch();
                responseStream.Position = 0;
                return(responseStream.ToArray());
            }
        }
        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);
        }
        private ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream)
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings { Version = ODataVersion.V4 };
            settings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");
            settings.SetServiceDocumentUri(new Uri("http://example.com/"));

            return new ODataJsonLightOutputContext(
                ODataFormat.Json,
                new NonDisposingStream(stream),
                new ODataMediaType("application", "json"),
                Encoding.UTF8,
                settings,
                /*writingResponse*/ true,
                /*synchronous*/ true,
                this.model,
                /*urlResolver*/ null);
        }
        public void WriterStreamPropertiesTests()
        {
            Uri baseUri             = new Uri("http://www.odata.org/", UriKind.Absolute);
            Uri relativeReadLinkUri = new Uri("readlink", UriKind.RelativeOrAbsolute);
            Uri relativeEditLinkUri = new Uri("editlink", UriKind.RelativeOrAbsolute);
            Uri absoluteReadLinkUri = new Uri(baseUri, relativeReadLinkUri.OriginalString);
            Uri absoluteEditLinkUri = new Uri(baseUri, relativeEditLinkUri.OriginalString);

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

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

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

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

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

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

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

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

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

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

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

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

                return(resultTestCases);
            });

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

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

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

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

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

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

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

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, config, this.Assert, this.Logger);
            });
        }
        private string GetWriterOutputForContentTypeAndKnobValue(ODataEntry entry, EdmModel model, IEdmEntitySetBase entitySet, EdmEntityType entityType)
        {
            MemoryStream outputStream = new MemoryStream();
            IODataResponseMessage message = new InMemoryMessage() { Stream = outputStream };
            message.SetHeader("Content-Type", "application/json;odata.metadata=full");
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings()
            {
                AutoComputePayloadMetadataInJson = true,
            };
            settings.SetServiceDocumentUri(new Uri("http://example.com"));

            string output;
            using (var messageWriter = new ODataMessageWriter(message, settings, model))
            {
                ODataWriter writer = messageWriter.CreateODataEntryWriter(entitySet, entityType);
                writer.WriteStart(entry);
                writer.WriteEnd();
                outputStream.Seek(0, SeekOrigin.Begin);
                output = new StreamReader(outputStream).ReadToEnd();
            }

            return output;
        }
        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();
            }
        }
        /// <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);
            }
        }
        public void WriterSettingsIntegrationTestWithSelect()
        {
            var setting = new ODataMessageWriterSettings();
            var edmModel = new EdmModel();
            var defaultContainer = new EdmEntityContainer("TestModel", "DefaultContainer");
            edmModel.AddElement(defaultContainer);
            var cityType = new EdmEntityType("TestModel", "City");
            var cityIdProperty = cityType.AddStructuralProperty("Id", EdmCoreModel.Instance.GetInt32(/*isNullable*/false));
            cityType.AddKeys(cityIdProperty);
            cityType.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(/*isNullable*/false));
            cityType.AddStructuralProperty("Size", EdmCoreModel.Instance.GetInt32(/*isNullable*/false));
            edmModel.AddElement(cityType);
            var citySet = defaultContainer.AddEntitySet("Cities", cityType);

            var result = new ODataQueryOptionParser(edmModel, cityType, citySet, new Dictionary<string, string> { { "$expand", "" }, { "$select", "Id,*" } }).ParseSelectAndExpand();

            setting.SetServiceDocumentUri(ServiceDocumentUri);
            setting.ODataUri = new ODataUri() { SelectAndExpand = result };
            setting.MetadataDocumentUri.Should().Equals(ServiceDocumentUri + "/$metadata");
            string select, expand;
            setting.SelectExpandClause.GetSelectExpandPaths(out select, out expand);
            select.Should().Be("*");
        }
        private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, IEdmModel userModel, bool fullMetadata = false, ODataUri uri = null)
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings { Version = ODataVersion.V4, AutoComputePayloadMetadataInJson = true, ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*") };
            settings.SetServiceDocumentUri(new Uri("http://host/service"));
            if (uri != null)
            {
                settings.ODataUri = uri;
            }

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

            ODataMediaType mediaType = new ODataMediaType("application", "json", parameters);
            return new ODataJsonLightOutputContext(
                ODataFormat.Json,
                new NonDisposingStream(stream),
                mediaType,
                Encoding.UTF8,
                settings,
                /*writingResponse*/ true,
                /*synchronous*/ true,
                userModel ?? EdmCoreModel.Instance,
                /*urlResolver*/ null);
        }
        public void UnsignedIntAndTypeDefinitionRoundtripJsonLightIntegrationTest()
        {
            var model = new EdmModel();

            var uint16 = new EdmTypeDefinition("MyNS", "UInt16", EdmPrimitiveTypeKind.Double);
            var uint16Ref = new EdmTypeDefinitionReference(uint16, false);
            model.AddElement(uint16);
            model.SetPrimitiveValueConverter(uint16Ref, UInt16ValueConverter.Instance);

            var uint64 = new EdmTypeDefinition("MyNS", "UInt64", EdmPrimitiveTypeKind.String);
            var uint64Ref = new EdmTypeDefinitionReference(uint64, false);
            model.AddElement(uint64);
            model.SetPrimitiveValueConverter(uint64Ref, UInt64ValueConverter.Instance);

            var guidType = new EdmTypeDefinition("MyNS", "Guid", EdmPrimitiveTypeKind.Int64);
            var guidRef = new EdmTypeDefinitionReference(guidType, true);
            model.AddElement(guidType);

            var personType = new EdmEntityType("MyNS", "Person");
            personType.AddKeys(personType.AddStructuralProperty("ID", uint64Ref));
            personType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            personType.AddStructuralProperty("FavoriteNumber", uint16Ref);
            personType.AddStructuralProperty("Age", model.GetUInt32("MyNS", true));
            personType.AddStructuralProperty("Guid", guidRef);
            personType.AddStructuralProperty("Weight", EdmPrimitiveTypeKind.Double);
            personType.AddStructuralProperty("Money", EdmPrimitiveTypeKind.Decimal);
            model.AddElement(personType);

            var container = new EdmEntityContainer("MyNS", "Container");
            var peopleSet = container.AddEntitySet("People", personType);
            model.AddElement(container);

            var stream = new MemoryStream();
            IODataResponseMessage message = new InMemoryMessage { Stream = stream };
            message.StatusCode = 200;

            var writerSettings = new ODataMessageWriterSettings();
            writerSettings.SetServiceDocumentUri(new Uri("http://host/service"));

            var messageWriter = new ODataMessageWriter(message, writerSettings, model);
            var entryWriter = messageWriter.CreateODataEntryWriter(peopleSet);

            var entry = new ODataEntry
            {
                TypeName = "MyNS.Person",
                Properties = new[]
                {
                    new ODataProperty
                    {
                        Name = "ID",
                        Value = UInt64.MaxValue
                    },
                    new ODataProperty
                    {
                        Name = "Name",
                        Value = "Foo"
                    },
                    new ODataProperty
                    {
                        Name = "FavoriteNumber",
                        Value = (UInt16)250
                    },
                    new ODataProperty
                    {
                        Name = "Age",
                        Value = (UInt32)123
                    },
                    new ODataProperty
                    {
                        Name = "Guid",
                        Value = Int64.MinValue
                    },
                    new ODataProperty
                    {
                        Name = "Weight",
                        Value = 123.45
                    },
                    new ODataProperty
                    {
                        Name = "Money",
                        Value = Decimal.MaxValue
                    }
                }
            };

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

            stream.Position = 0;

            StreamReader reader = new StreamReader(stream);
            string payload = reader.ReadToEnd();
            payload.Should().Be("{\"@odata.context\":\"http://host/service/$metadata#People/$entity\",\"ID\":\"18446744073709551615\",\"Name\":\"Foo\",\"FavoriteNumber\":250.0,\"Age\":123,\"Guid\":-9223372036854775808,\"Weight\":123.45,\"Money\":79228162514264337593543950335}");

            stream = new MemoryStream(Encoding.Default.GetBytes(payload));
            message = new InMemoryMessage { Stream = stream };
            message.StatusCode = 200;

            var readerSettings = new ODataMessageReaderSettings();

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

            var propertiesReaded = entryReaded.Properties.ToList();
            var propertiesGiven = entry.Properties.ToList();
            Assert.Equal(propertiesReaded.Count, propertiesGiven.Count);
            for (int i = 0; i < propertiesReaded.Count; ++i)
            {
                Assert.Equal(propertiesReaded[i].Name, propertiesGiven[i].Name);
                Assert.Equal(propertiesReaded[i].Value.GetType(), propertiesGiven[i].Value.GetType());
                Assert.Equal(propertiesReaded[i].Value, propertiesGiven[i].Value);
            }
        }
        // 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 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 string WriterEntry(EdmModel userModel, ODataEntry entry, IEdmEntityType entityType)
        {
            var message = new InMemoryMessage() { Stream = new MemoryStream() };
            message.SetHeader("Content-Type", "application/atom+xml;type=entry");
            var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true, EnableAtom = true };
            writerSettings.SetServiceDocumentUri(ServiceDocumentUri);
            using (var msgReader = new ODataMessageWriter((IODataResponseMessage)message, writerSettings, userModel))
            {
                var writer = msgReader.CreateODataEntryWriter();
                writer.WriteStart(entry);
                writer.WriteEnd();
            }

            message.Stream.Seek(0, SeekOrigin.Begin);
            using (StreamReader reader = new StreamReader(message.Stream))
            {
                return reader.ReadToEnd();
            }
        }
Exemple #48
0
        private object WriteAsUntypedThenReadValue(string value, IEdmTypeReference typeReference, ODataVersion version)
        {
            var stream = new MemoryStream();

            var settings = new ODataMessageWriterSettings {
                Version = version
            };

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

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

            var messageInfoForWriter = new ODataMessageInfo
            {
                MessageStream = new NonDisposingStream(stream),
                MediaType     = mediaType,
                Encoding      = Encoding.UTF8,
                IsResponse    = true,
                IsAsync       = false,
                Model         = this.model,
                Container     = this.container
            };

            using (var outputContext = new ODataJsonLightOutputContext(messageInfoForWriter, settings))
            {
                var serializer = new ODataJsonLightValueSerializer(outputContext);
                // Writing the value as untyped it remains in its original form
                serializer.WriteUntypedValue(new ODataUntypedValue {
                    RawValue = value
                });
            }

            stream.Position = 0;

            var messageInfoForReader = new ODataMessageInfo
            {
                Encoding      = Encoding.UTF8,
                IsResponse    = true,
                MediaType     = mediaType,
                IsAsync       = false,
                Model         = this.model,
                MessageStream = stream,
                Container     = this.container
            };

            object actualValue;

            using (var inputContext = new ODataJsonLightInputContext(
                       messageInfoForReader, new ODataMessageReaderSettings()))
            {
                var deserializer = new ODataJsonLightPropertyAndValueDeserializer(inputContext);
                deserializer.JsonReader.Read();
                actualValue = deserializer.ReadNonEntityValue(
                    /*payloadTypeName*/ null,
                    typeReference,
                    /*propertyAndAnnotationCollector*/ null,
                    /*collectionValidator*/ null,
                    /*validateNullValue*/ true,
                    /*isTopLevel*/ true,
                    /*insideResourceValue*/ false,
                    /*propertyName*/ null);
            }

            return(actualValue);
        }
Exemple #49
0
        private object WriteThenReadValue(object clrValue, IEdmTypeReference typeReference, ODataVersion version, bool isIeee754Compatible)
        {
            var stream = new MemoryStream();

            var settings = new ODataMessageWriterSettings {
                Version = version
            };

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

            var mediaType = isIeee754Compatible
                ? new ODataMediaType("application", "json", new KeyValuePair <string, string>("IEEE754Compatible", "true"))
                : new ODataMediaType("application", "json");

            var messageInfoForWriter = new ODataMessageInfo
            {
                MessageStream = new NonDisposingStream(stream),
                MediaType     = mediaType,
                Encoding      = Encoding.UTF8,
                IsResponse    = true,
                IsAsync       = false,
                Model         = this.model,
                Container     = this.container
            };

            using (var outputContext = new ODataJsonLightOutputContext(messageInfoForWriter, settings))
            {
                var serializer = new ODataJsonLightValueSerializer(outputContext);
                serializer.WritePrimitiveValue(clrValue, typeReference);
            }

            stream.Position = 0;

            var messageInfoForReader = new ODataMessageInfo
            {
                Encoding      = Encoding.UTF8,
                IsResponse    = true,
                MediaType     = mediaType,
                IsAsync       = false,
                Model         = this.model,
                MessageStream = stream,
                Container     = this.container
            };

            object actualValue;

            using (var inputContext = new ODataJsonLightInputContext(
                       messageInfoForReader, new ODataMessageReaderSettings()))
            {
                var deserializer = new ODataJsonLightPropertyAndValueDeserializer(inputContext);
                deserializer.JsonReader.Read();
                actualValue = deserializer.ReadNonEntityValue(
                    /*payloadTypeName*/ null,
                    typeReference,
                    /*propertyAndAnnotationCollector*/ null,
                    /*collectionValidator*/ null,
                    /*validateNullValue*/ true,
                    /*isTopLevel*/ true,
                    /*insideResourceValue*/ false,
                    /*propertyName*/ null);
            }

            return(actualValue);
        }
        private static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, bool writingResponse = true, IEdmModel userModel = null, Uri serviceDocumentUri = null)
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings { Version = ODataVersion.V4, AutoComputePayloadMetadataInJson = true, ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*") };
            if (serviceDocumentUri != null)
            {
                settings.SetServiceDocumentUri(serviceDocumentUri);
            }

            ODataMediaType mediaType = new ODataMediaType("application", "json", new KeyValuePair<string, string>("odata.metadata", "full"));
            return new ODataJsonLightOutputContext(
                ODataFormat.Json,
                new NonDisposingStream(stream),
                mediaType,
                Encoding.UTF8,
                settings,
                writingResponse,
                /*synchronous*/ true,
                userModel ?? EdmCoreModel.Instance,
                /*urlResolver*/ null);
        }
        private object WriteThenReadValue(object clrValue, IEdmTypeReference typeReference, ODataVersion version, bool isIeee754Compatible)
        {
            MemoryStream stream = new MemoryStream();

            ODataMessageWriterSettings settings = new ODataMessageWriterSettings { Version = version };
            settings.SetServiceDocumentUri(new Uri("http://odata.org/test/"));

            ODataMediaType mediaType = isIeee754Compatible
                ? new ODataMediaType("application", "json", new KeyValuePair<string, string>("IEEE754Compatible", "true"))
                : new ODataMediaType("application", "json");

            using (ODataJsonLightOutputContext outputContext = new ODataJsonLightOutputContext(
                ODataFormat.Json,
                new NonDisposingStream(stream),
                mediaType,
                Encoding.UTF8,
                settings,
                /*writingResponse*/ true,
                /*synchronous*/ true,
                this.model,
                /*urlResolver*/ null))
            {
                ODataJsonLightValueSerializer serializer = new ODataJsonLightValueSerializer(outputContext);
                serializer.WritePrimitiveValue(clrValue, typeReference);
            }

            stream.Position = 0;

            object actualValue;
            using (ODataJsonLightInputContext inputContext = new ODataJsonLightInputContext(
                ODataFormat.Json,
                stream,
                mediaType,
                Encoding.UTF8,
                new ODataMessageReaderSettings(),
                /*readingResponse*/ true,
                /*synchronous*/ true,
                this.model,
                /*urlResolver*/ null))
            {
                ODataJsonLightPropertyAndValueDeserializer deserializer = new ODataJsonLightPropertyAndValueDeserializer(inputContext);
                deserializer.JsonReader.Read();
                actualValue = deserializer.ReadNonEntityValue(
                    /*payloadTypeName*/ null,
                    typeReference,
                    /*duplicatePropertyNamesChecker*/ null,
                    /*collectionValidator*/ null,
                    /*validateNullValue*/ true,
                    /*isTopLevel*/ true,
                    /*insideComplexValue*/ false,
                    /*propertyName*/ null);

            }

            return actualValue;
        }
        private string SerializeEntryInFullMetadataJson(
            bool? useKeyAsSegment, 
            IEdmModel edmModel, 
            IEdmEntityType entityType = null, 
            IEdmEntitySet entitySet = null)
        {
            var settings = new ODataMessageWriterSettings
            {
                AutoComputePayloadMetadataInJson = true,
                UseKeyAsSegment = useKeyAsSegment,
            };

            settings.SetServiceDocumentUri(new Uri("http://example.com/"));

            var outputStream = new MemoryStream();
            var responseMessage = new InMemoryMessage {Stream = outputStream};
            responseMessage.SetHeader("Content-Type", "application/json;odata.metadata=full");
            string output;

            using(var messageWriter = new ODataMessageWriter((IODataResponseMessage)responseMessage, settings, edmModel))
            {
                var entryWriter = messageWriter.CreateODataEntryWriter(entitySet, entityType);
                ODataProperty keyProperty = new ODataProperty() {Name = "Key", Value = "KeyValue"};

                var entry = new ODataEntry {Properties = new[] {keyProperty}, TypeName = "Namespace.Person"};

                if (edmModel == null)
                {
                    keyProperty.SetSerializationInfo(new ODataPropertySerializationInfo
                    {
                        PropertyKind = ODataPropertyKind.Key
                    });

                    entry.SetSerializationInfo(new ODataFeedAndEntrySerializationInfo
                    {
                        NavigationSourceEntityTypeName = "Namespace.Person",
                        NavigationSourceName = "People",
                        ExpectedTypeName = "Namespace.Person"
                    });
                }

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

                outputStream.Seek(0, SeekOrigin.Begin);
                output = new StreamReader(outputStream).ReadToEnd();
            }

            return output;
        }
Exemple #53
0
        public void UnsignedIntAndTypeDefinitionRoundtripJsonLightIntegrationTest()
        {
            var model = new EdmModel();

            var uint16    = new EdmTypeDefinition("MyNS", "UInt16", EdmPrimitiveTypeKind.Double);
            var uint16Ref = new EdmTypeDefinitionReference(uint16, false);

            model.AddElement(uint16);
            model.SetPrimitiveValueConverter(uint16Ref, UInt16ValueConverter.Instance);

            var uint64    = new EdmTypeDefinition("MyNS", "UInt64", EdmPrimitiveTypeKind.String);
            var uint64Ref = new EdmTypeDefinitionReference(uint64, false);

            model.AddElement(uint64);
            model.SetPrimitiveValueConverter(uint64Ref, UInt64ValueConverter.Instance);

            var guidType = new EdmTypeDefinition("MyNS", "Guid", EdmPrimitiveTypeKind.Int64);
            var guidRef  = new EdmTypeDefinitionReference(guidType, true);

            model.AddElement(guidType);

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

            personType.AddKeys(personType.AddStructuralProperty("ID", uint64Ref));
            personType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            personType.AddStructuralProperty("FavoriteNumber", uint16Ref);
            personType.AddStructuralProperty("Age", model.GetUInt32("MyNS", true));
            personType.AddStructuralProperty("Guid", guidRef);
            personType.AddStructuralProperty("Weight", EdmPrimitiveTypeKind.Double);
            personType.AddStructuralProperty("Money", EdmPrimitiveTypeKind.Decimal);
            model.AddElement(personType);

            var container = new EdmEntityContainer("MyNS", "Container");
            var peopleSet = container.AddEntitySet("People", personType);

            model.AddElement(container);

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

            message.StatusCode = 200;

            var writerSettings = new ODataMessageWriterSettings();

            writerSettings.SetServiceDocumentUri(new Uri("http://host/service"));

            var messageWriter = new ODataMessageWriter(message, writerSettings, model);
            var entryWriter   = messageWriter.CreateODataResourceWriter(peopleSet);

            var entry = new ODataResource
            {
                TypeName   = "MyNS.Person",
                Properties = new[]
                {
                    new ODataProperty
                    {
                        Name  = "ID",
                        Value = UInt64.MaxValue
                    },
                    new ODataProperty
                    {
                        Name  = "Name",
                        Value = "Foo"
                    },
                    new ODataProperty
                    {
                        Name  = "FavoriteNumber",
                        Value = (UInt16)250
                    },
                    new ODataProperty
                    {
                        Name  = "Age",
                        Value = (UInt32)123
                    },
                    new ODataProperty
                    {
                        Name  = "Guid",
                        Value = Int64.MinValue
                    },
                    new ODataProperty
                    {
                        Name  = "Weight",
                        Value = 123.45
                    },
                    new ODataProperty
                    {
                        Name  = "Money",
                        Value = Decimal.MaxValue
                    }
                }
            };

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

            stream.Position = 0;

            StreamReader reader  = new StreamReader(stream);
            string       payload = reader.ReadToEnd();

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

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

            var readerSettings = new ODataMessageReaderSettings();

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

            var propertiesReaded = entryReaded.Properties.ToList();
            var propertiesGiven  = entry.Properties.ToList();
            Assert.Equal(propertiesReaded.Count, propertiesGiven.Count);
            for (int i = 0; i < propertiesReaded.Count; ++i)
            {
                Assert.Equal(propertiesReaded[i].Name, propertiesGiven[i].Name);
                Assert.Equal(propertiesReaded[i].Value.GetType(), propertiesGiven[i].Value.GetType());
                Assert.Equal(propertiesReaded[i].Value, propertiesGiven[i].Value);
            }
        }
        private static ODataMessageWriter CreateODataMessageWriter(IEdmModel model, string contentType)
        {
            var settings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true, Version = ODataVersion.V4, EnableAtom = true };
            settings.SetServiceDocumentUri(new Uri("http://example.com"));

            var message = new InMemoryMessage();
            message.Stream = new MemoryStream();
            message.SetHeader("Accept", contentType);
            message.SetHeader("Content-Type", contentType);
            message.SetHeader("OData-Version", "4.0");
            if (model == null)
            {
                return new ODataMessageWriter((IODataRequestMessage)message, settings);
            }
            else
            {
                return new ODataMessageWriter((IODataRequestMessage)message, settings, model);
            }
        }
        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 {
                BaseUri = new Uri(serviceDocumentUri)
            }, 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.CreateODataResourceWriter(this.customers, this.customerType);
                                var entry       = new ODataResource()
                                {
                                    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 static ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, bool writingResponse = true, bool synchronous = true)
        {
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings { Version = ODataVersion.V4 };
            settings.SetServiceDocumentUri(new Uri("http://odata.org/test/"));

            return new ODataJsonLightOutputContext(
                ODataFormat.Json,
                new NonDisposingStream(stream),
                new ODataMediaType("application", "json"),
                Encoding.UTF8,
                settings,
                writingResponse,
                synchronous,
                EdmCoreModel.Instance,
                /*urlResolver*/ null);
        }
        private static string WriteJsonLightEntry(bool isRequest, Uri serviceDocumentUri, bool specifySet,
                                                  ODataResource odataEntry, IEdmNavigationSource entitySet, IEdmStructuredType resourceType,
                                                  ODataUri odataUri, Action <ODataWriter> writeAction = null, bool isResourceSet = false,
                                                  EdmModel model             = null,
                                                  bool ValidatePropertyNames = true)
        {
            if (model == null)
            {
                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
            };

            settings.ODataUri = odataUri;
            settings.SetServiceDocumentUri(serviceDocumentUri);

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

            if (!ValidatePropertyNames)
            {
                settings.Validations = ValidationKinds.None;
            }

            ODataMessageWriter messageWriter;

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

            ODataWriter writer = null;

            if (isResourceSet)
            {
                writer = messageWriter.CreateODataResourceSetWriter(entitySet as IEdmEntitySetBase, resourceType);
            }
            else
            {
                writer = messageWriter.CreateODataResourceWriter(specifySet ? entitySet : null, resourceType);
            }

            if (writeAction != null)
            {
                writeAction(writer);
            }
            else if (!isResourceSet)
            {
                writer.WriteStart(odataEntry);
                writer.WriteEnd();
            }

            writer.Flush();

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

            return(actual);
        }
 private ODataMessageWriter CreateMessageWriter(bool useModel)
 {
     var responseMessage = new TestResponseMessage(this.stream);
     var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true };
     writerSettings.SetServiceDocumentUri(new Uri("http://host/service"));
     var model = useModel ? this.GetModel() : null;
     return new ODataMessageWriter(responseMessage, writerSettings, model);
 }
        private static TestODataWriterCore CreateODataWriterCore(ODataFormat format, bool writingResponse, IEdmModel model, IEdmEntitySet writerSet, IEdmEntityType writerEntityType, bool writeFeed)
        {
            var resolver = new TestUrlResolver();
            var settings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true, Version = ODataVersion.V4 };
            settings.SetServiceDocumentUri(new Uri("http://example.com"));

            var outputContext = new TestODataOutputContext(format, settings, writingResponse, false, model, resolver);
            return new TestODataWriterCore(outputContext, writerSet, writerEntityType, writeFeed);
        }
        private static ODataJsonLightSerializer GetSerializer(Stream stream, string jsonpFunctionName = null, bool nometadata = false, bool setMetadataDocumentUri = true)
        {
            var model = new EdmModel();
            var complexType = new EdmComplexType("ns", "ErrorDetails");
            //var collectionType = new EdmCollectionType(new EdmComplexTypeReference(complexType, false));
            model.AddElement(complexType);

            var settings = new ODataMessageWriterSettings { JsonPCallback = jsonpFunctionName, DisableMessageStreamDisposal = true, Version = ODataVersion.V4 };
            if (setMetadataDocumentUri)
            {
                settings.SetServiceDocumentUri(new Uri("http://example.com"));
            }
            ODataMediaType mediaType = nometadata ? new ODataMediaType("application", "json", new KeyValuePair<string, string>("odata", "none")) : new ODataMediaType("application", "json");
            IEdmModel mainModel = TestUtils.WrapReferencedModelsToMainModel(model);
            var context = new ODataJsonLightOutputContext(ODataFormat.Json, stream, mediaType, Encoding.Default, settings, true, true, mainModel, null);
            return new ODataJsonLightSerializer(context, setMetadataDocumentUri);
        }