Exemplo n.º 1
0
 private ODataWriter CreateODataEntryWriter(ODataMessageWriter messageWriter, IEdmEntitySet entitySet, IEdmEntityType entityType, bool hasModel)
 {
     if (hasModel)
     {
         return(messageWriter.CreateODataEntryWriter(entitySet, entityType));
     }
     else
     {
         return(messageWriter.CreateODataEntryWriter());
     }
 }
Exemplo n.º 2
0
        private static void WriteTopLevelEntry()
        {
            Console.WriteLine("WriteTopLevelEntry");

            var msg = ODataSamplesUtil.CreateMessage();

            msg.PreferenceAppliedHeader().AnnotationFilter = "*";

            var settings = new ODataMessageWriterSettings(BaseSettings)
            {
                ODataUri = new ODataUri()
                {
                    ServiceRoot = ServiceRoot
                },
            };

            using (var omw = new ODataMessageWriter((IODataResponseMessage)msg, settings, ExtModel.Model))
            {
                var writer = omw.CreateODataEntryWriter(ExtModel.People);
                writer.WriteStart(PersonEntry);
                writer.WriteEnd();
            }

            Console.WriteLine(ODataSamplesUtil.MessageToString(msg));
        }
        /// <inheritdoc />
        public override void WriteObject(object graph, Type type, ODataMessageWriter messageWriter,
                                         ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            if (writeContext == null)
            {
                throw Error.ArgumentNull("writeContext");
            }

            IEdmNavigationSource navigationSource = writeContext.NavigationSource;

            if (navigationSource == null)
            {
                throw new SerializationException(SRResources.NavigationSourceMissingDuringSerialization);
            }

            var path = writeContext.Path;

            if (path == null)
            {
                throw new SerializationException(SRResources.ODataPathMissing);
            }

            ODataWriter writer = messageWriter.CreateODataEntryWriter(navigationSource, path.EdmType as IEdmEntityType);

            WriteObjectInline(graph, navigationSource.EntityType().ToEdmTypeReference(isNullable: false), writer, writeContext);
        }
Exemplo n.º 4
0
        public static Stream CreatePackageStream(string baseAddress, IWebPackage package)
        {
            var writerSettings = new ODataMessageWriterSettings()
            {
                Indent          = true, // pretty printing
                CheckCharacters = false,
                BaseUri         = new Uri("http://localhost:12345"),
                Version         = ODataVersion.V3
            };

            writerSettings.SetContentType(ODataFormat.Atom);

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

            var feedWriter = writer.CreateODataEntryWriter();

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

            var stream = responseMessage.GetStream();

            stream.Seek(0, SeekOrigin.Begin);

            return(stream);
        }
        public void EntryMetadataUrlRoundTrip()
        {
            var stream = new MemoryStream();
            var writerRequestMemoryMessage = new InMemoryMessage();
            writerRequestMemoryMessage.Stream = stream;
            writerRequestMemoryMessage.SetHeader("Content-Type", "application/json");

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

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

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

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

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

            var messageReader = new ODataMessageReader((IODataResponseMessage)readerResponseMemoryMessage, new ODataMessageReaderSettings() {MaxProtocolVersion = ODataVersion.V4, DisableMessageStreamDisposal = true}, this.model);
            var organizationReader = messageReader.CreateODataEntryReader(this.organizationsSet, this.organizationsSet.EntityType());
            organizationReader.Read().Should().Be(true);
            organizationReader.Item.As<ODataEntry>();
        }
Exemplo n.º 6
0
        public void UpdateUsingAtomShouldBeFailed()
        {
            var entry = new ODataEntry()
            {
                TypeName = NameSpacePrefix + "Person"
            };

            entry.Properties = new[]
            {
                new ODataProperty
                {
                    Name  = "HomeAddress",
                    Value = new ODataComplexValue
                    {
                        TypeName   = NameSpacePrefix + "HomeAddress",
                        Properties = new[]
                        {
                            new ODataProperty
                            {
                                Name  = "City",
                                Value = "Chengdu"
                            },
                            new ODataProperty
                            {
                                Name  = "FamilyName",
                                Value = "Tigers"
                            }
                        }
                    }
                }
            };
            var settings = new ODataMessageWriterSettings();

            settings.PayloadBaseUri = ServiceBaseUri;
            settings.AutoComputePayloadMetadataInJson = true;

            var personType = Model.FindDeclaredType(NameSpacePrefix + "Person") as IEdmEntityType;
            var personSet  = Model.EntityContainer.FindEntitySet("People");

            var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri + "People(1)"));

            requestMessage.SetHeader("Content-Type", MimeTypes.ApplicationAtomXml);
            requestMessage.SetHeader("Accept", MimeTypes.ApplicationAtomXml);
            requestMessage.Method = "PATCH";

            using (var messageWriter = new ODataMessageWriter(requestMessage, settings, Model))
            {
                try
                {
                    var odataWriter = messageWriter.CreateODataEntryWriter(personSet, personType);
                    odataWriter.WriteStart(entry);
                    odataWriter.WriteEnd();
                }
                catch (Microsoft.OData.Core.ODataContentTypeException)
                {
                    return;
                }
                Assert.IsTrue(false);
            }
        }
Exemplo n.º 7
0
        /// <inheritdoc />
        public override void WriteObject(object graph, Type type, ODataMessageWriter messageWriter,
            ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            if (writeContext == null)
            {
                throw Error.ArgumentNull("writeContext");
            }

            IEdmNavigationSource navigationSource = writeContext.NavigationSource;
            if (navigationSource == null)
            {
                throw new SerializationException(SRResources.NavigationSourceMissingDuringSerialization);
            }

            var path = writeContext.Path;
            if (path == null)
            {
                throw new SerializationException(SRResources.ODataPathMissing);
            }

            ODataWriter writer = messageWriter.CreateODataEntryWriter(navigationSource, path.EdmType as IEdmEntityType);
            WriteObjectInline(graph, navigationSource.EntityType().ToEdmTypeReference(isNullable: false), writer, writeContext);
        }
Exemplo n.º 8
0
        private string WriteAtomEntry(ODataEntry entry)
        {
            MemoryStream    stream  = new MemoryStream();
            InMemoryMessage message = new InMemoryMessage {
                Stream = stream
            };

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

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

            settings.SetContentType(ODataFormat.Atom);


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

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

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

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

            return(actual);
        }
Exemplo n.º 9
0
        private void UpdateEntry(string singletonType, string singletonName, string mimeType, IEnumerable <ODataProperty> properties)
        {
            ODataEntry entry = new ODataEntry()
            {
                TypeName = NameSpacePrefix + singletonType
            };

            entry.Properties = properties;

            var settings = new ODataMessageWriterSettings();

            settings.PayloadBaseUri = ServiceBaseUri;

            var customerType = Model.FindDeclaredType(NameSpacePrefix + singletonType) as IEdmEntityType;
            var customerSet  = Model.EntityContainer.FindSingleton(singletonName);

            var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri + singletonName));

            requestMessage.SetHeader("Content-Type", mimeType);
            requestMessage.SetHeader("Accept", mimeType);
            requestMessage.Method = "PATCH";

            using (var messageWriter = new ODataMessageWriter(requestMessage, settings))
            {
                var odataWriter = messageWriter.CreateODataEntryWriter(customerSet, customerType);
                odataWriter.WriteStart(entry);
                odataWriter.WriteEnd();
            }

            var responseMessage = requestMessage.GetResponse();

            // verify the update
            Assert.AreEqual(204, responseMessage.StatusCode);
        }
        private string WriterEntry(IEdmModel userModel, ODataEntry entry, EdmEntitySet entitySet, IEdmEntityType entityType, bool fullMetadata = false)
        {
            var message = new InMemoryMessage()
            {
                Stream = new MemoryStream()
            };

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

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

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

            message.Stream.Seek(0, SeekOrigin.Begin);
            using (StreamReader reader = new StreamReader(message.Stream))
            {
                return(reader.ReadToEnd());
            }
        }
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            if (writeContext == null)
            {
                throw Error.ArgumentNull("writeContext");
            }

            if (graph == null)
            {
                throw new SerializationException(Error.Format(Properties.SRResources.CannotSerializerNull,
                    ODataFormatterConstants.Entry));
            }

            IEdmEntitySet entitySet = writeContext.EntitySet;

            if (entitySet == null)
            {
                throw new SerializationException(SRResources.EntitySetMissingDuringSerialization);
            }

            // No null check; entity type is not required for successful serialization.
            IEdmEntityType entityType = _edmEntityTypeReference.Definition as IEdmEntityType;

            ODataWriter writer = messageWriter.CreateODataEntryWriter(entitySet, entityType);
            WriteObjectInline(graph, writer, writeContext);
            writer.Flush();
        }
Exemplo n.º 12
0
        public void CarEntryTest()
        {
            foreach (var mimeType in this.mimeTypes)
            {
                var settings = new ODataMessageWriterSettings();
                settings.ODataUri = new ODataUri()
                {
                    ServiceRoot = this.ServiceUri
                };
                string outputWithModel    = null;
                string outputWithoutModel = null;

                var responseMessageWithModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithModel.SetHeader("Content-Type", mimeType);
                responseMessageWithModel.PreferenceAppliedHeader().AnnotationFilter = "*";
                using (var messageWriter = new ODataMessageWriter(responseMessageWithModel, settings, WritePayloadHelper.Model))
                {
                    var odataWriter = messageWriter.CreateODataEntryWriter(WritePayloadHelper.CarSet, WritePayloadHelper.CarType);
                    outputWithModel = this.WriteAndVerifyCarEntry(responseMessageWithModel, odataWriter, true, mimeType);
                }

                var responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                responseMessageWithoutModel.PreferenceAppliedHeader().AnnotationFilter = "*";
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var odataWriter = messageWriter.CreateODataEntryWriter();
                    outputWithoutModel = this.WriteAndVerifyCarEntry(responseMessageWithoutModel, odataWriter, false,
                                                                     mimeType);
                }

                WritePayloadHelper.VerifyPayloadString(outputWithModel, outputWithoutModel, mimeType);
            }
        }
        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());
            }
        }
        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);
        }
Exemplo n.º 15
0
        public void RequestMessageTest()
        {
            foreach (var mimeType in this.mimeTypes)
            {
                var settings = new ODataMessageWriterSettings();
                settings.ODataUri = new ODataUri()
                {
                    ServiceRoot = this.ServiceUri
                };
                string outputWithModel    = null;
                string outputWithoutModel = null;

                var requestMessageWithModel = new StreamRequestMessage(new MemoryStream(),
                                                                       new Uri(this.ServiceUri + "Order"), "POST");
                requestMessageWithModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(requestMessageWithModel, settings, WritePayloadHelper.Model))
                {
                    var odataWriter = messageWriter.CreateODataEntryWriter(WritePayloadHelper.OrderSet, WritePayloadHelper.OrderType);
                    outputWithModel = this.WriteAndVerifyRequestMessage(requestMessageWithModel, odataWriter,
                                                                        true, mimeType);
                }

                var requestMessageWithoutModel = new StreamRequestMessage(new MemoryStream(),
                                                                          new Uri(this.ServiceUri + "Order"), "POST");
                requestMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(requestMessageWithoutModel, settings))
                {
                    var odataWriter = messageWriter.CreateODataEntryWriter();
                    outputWithoutModel = this.WriteAndVerifyRequestMessage(requestMessageWithoutModel,
                                                                           odataWriter, false, mimeType);
                }

                WritePayloadHelper.VerifyPayloadString(outputWithModel, outputWithoutModel, mimeType);
            }
        }
        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);
        }
Exemplo n.º 17
0
        private static void WriteTopLevelEntry()
        {
            Console.WriteLine("WriteTopLevelEntry");

            var msg = ODataSamplesUtil.CreateMessage();

            msg.PreferenceAppliedHeader().AnnotationFilter = "*";

            using (var omw = new ODataMessageWriter((IODataResponseMessage)msg, BaseSettings, ExtModel.Model))
            {
                var writer = omw.CreateODataEntryWriter(ExtModel.People);
                writer.WriteStart(PersonEntry);

                writer.WriteStart(PersonPetsNavigationLink);
                writer.WriteStart(new ODataFeed());
                writer.WriteStart(PetEntry);
                writer.WriteEnd();
                writer.WriteEnd();
                writer.WriteEnd();

                writer.WriteStart(PersonFavouritePetNavigationLink);
                writer.WriteStart(PetEntry);
                writer.WriteEnd();
                writer.WriteEnd();

                writer.WriteEnd();
            }

            Console.WriteLine(ODataSamplesUtil.MessageToString(msg));
        }
Exemplo n.º 18
0
        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);
        }
Exemplo n.º 19
0
        public void VerifyCanSendRequestPayloadSyncTest()
        {
            var request = new ClientHttpRequestMessage(new Uri(TestDemoService.ServiceBaseUri, "Products"));

            request.Method = ODataConstants.MethodPost;
            using (ODataMessageWriter messageWriter = new ODataMessageWriter(
                       request,
                       new ODataMessageWriterSettings(),
                       TestUtils.GetServiceModel(TestDemoService.ServiceBaseUri)))
            {
                ODataWriter writer = messageWriter.CreateODataEntryWriter();
                writer.WriteStart(new ODataEntry()
                {
                    TypeName   = "DataServiceProviderDemo.Product",
                    Properties = new ODataProperty[]
                    {
                        new ODataProperty {
                            Name = "ID", Value = 42
                        }
                    }
                });

                writer.WriteEnd();
                writer.Flush();
            }

            var response = request.GetResponse();

            Assert.AreEqual(201, response.StatusCode);
        }
        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);
        }
Exemplo n.º 21
0
        protected override async Task <Stream> WriteEntryContentAsync(string method, string collection, string commandText, IDictionary <string, object> entryData, bool resultRequired)
        {
#if SILVERLIGHT
            IODataRequestMessage
#else
            IODataRequestMessageAsync
#endif
            message = IsBatch
                ? await CreateBatchOperationMessageAsync(method, collection, entryData, commandText, resultRequired)
                      .ConfigureAwait(false) : new ODataRequestMessage();

            if (method == RestVerbs.Get || method == RestVerbs.Delete)
            {
                return(null);
            }

            var entityType = _model.FindDeclaredType(
                _session.Metadata.GetQualifiedTypeName(collection)) as IEdmEntityType;
            var model = method == RestVerbs.Patch ? new EdmDeltaModel(_model, entityType, entryData.Keys) : _model;

            using (var messageWriter = new ODataMessageWriter(message, GetWriterSettings(), model))
            {
                var contentId = _deferredBatchWriter != null?_deferredBatchWriter.Value.GetContentId(entryData, null) : null;

                //var entityCollection = _session.Metadata.GetEntityCollection(collection);
                var entityCollection = _session.Metadata.NavigateToCollection(collection);
                var entryDetails     = _session.Metadata.ParseEntryDetails(entityCollection.Name, entryData, contentId);

                var entryWriter = messageWriter.CreateODataEntryWriter();
                var entry       = CreateODataEntry(entityType.FullName(), entryDetails.Properties);

                entryWriter.WriteStart(entry);

                if (entryDetails.Links != null)
                {
                    foreach (var link in entryDetails.Links)
                    {
                        if (link.Value.Any(x => x.LinkData != null))
                        {
                            WriteLink(entryWriter, entry, link.Key, link.Value);
                        }
                    }
                }

                entryWriter.WriteEnd();

                if (IsBatch)
                {
                    return(null);
                }

#if SILVERLIGHT
                return(message.GetStream());
#else
                return(await message.GetStreamAsync().ConfigureAwait(false));
#endif
            }
        }
Exemplo n.º 22
0
        public void PutEntity()
        {
            int RequestsPerIteration = 100;

            foreach (var iteration in Benchmark.Iterations)
            {
                int PersonIdBase = 1;

                ResetDataSource();

                using (iteration.StartMeasurement())
                {
                    for (int i = 0; i < RequestsPerIteration; i++)
                    {
                        ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
                        {
                            PayloadBaseUri = serviceFixture.ServiceBaseUri
                        };
                        writerSettings.ODataUri = new ODataUri()
                        {
                            ServiceRoot = serviceFixture.ServiceBaseUri
                        };
                        var requestMessage = new HttpWebRequestMessage(new Uri(serviceFixture.ServiceBaseUri.AbsoluteUri + "SimplePeopleSet(" + PersonIdBase + ")", UriKind.Absolute));
                        requestMessage.Method = "PUT";

                        var peopleEntry = new ODataEntry()
                        {
                            Properties = new[]
                            {
                                new ODataProperty {
                                    Name = "PersonID", Value = PersonIdBase++
                                },
                                new ODataProperty {
                                    Name = "FirstName", Value = "PostEntity"
                                },
                                new ODataProperty {
                                    Name = "LastName", Value = "PostEntity"
                                },
                                new ODataProperty {
                                    Name = "MiddleName", Value = "NewMiddleName"
                                }
                            },
                        };

                        using (var messageWriter = new ODataMessageWriter(requestMessage, writerSettings))
                        {
                            var odataWriter = messageWriter.CreateODataEntryWriter();
                            odataWriter.WriteStart(peopleEntry);
                            odataWriter.WriteEnd();
                        }
                        var responseMessage = requestMessage.GetResponse();
                        Assert.Equal(204, responseMessage.StatusCode);
                    }
                }
            }
        }
Exemplo n.º 23
0
        public string GetSampleEntityPayload(object entity, IEnumerable<string> projectedProperties)
        {
            var message = new SimpleResponseMessage(this.StatusCode, this.ContentType);
            using (var writer = new ODataMessageWriter(message, Settings))
            {
                WriteEntry(writer.CreateODataEntryWriter(), entity, projectedProperties);
            }

            return message.GetMessageString();
        }
Exemplo n.º 24
0
        public void WriterShouldNotIncludeTypeNameForCollectionOfDerivedType()
        {
            // JSON Light: writer doesn't include type name for collection of derived type
            // If I have a collection property declared in metadata as Collection(Edm.Geography), 
            // and at serialization type, it's clearly a Collection(Edm.GeographyPoint), 
            // we won't write the type name for that property by default (i.e., minimal metadata mode).

            var model = new EdmModel();
            var entityType = new EdmEntityType("Var1", "Type");
            entityType.AddKeys(entityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
            entityType.AddProperty(new EdmStructuralProperty(entityType, "Geographies", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.Geography, false)))));
            model.AddElement(entityType);
            
            var writerSettings = new ODataMessageWriterSettings();
            writerSettings.SetContentType(ODataFormat.Json);
            writerSettings.DisableMessageStreamDisposal = true;

            var message = new InMemoryMessage { Stream = new MemoryStream() };
            using (ODataMessageWriter odataMessageWriter = new ODataMessageWriter((IODataRequestMessage)message, writerSettings, model))
            {
                ODataWriter odataWriter = odataMessageWriter.CreateODataEntryWriter();
                odataWriter.WriteStart(
                    new ODataEntry
                    {
                        TypeName = "Var1.Type",
                        Properties = new[] 
                        {
                            new ODataProperty() 
                            { 
                                Name = "Id", 
                                Value = 1 
                            }, 
                            new ODataProperty() 
                            { 
                                Name = "Geographies", 
                                Value = new ODataCollectionValue 
                                { 
                                    Items = new[] 
                                    { 
                                        GeographyPoint.Create(0,0),
                                        GeographyPoint.Create(1,1), 
                                        GeographyPoint.Create(2,2) 
                                    } 
                                } 
                            }, 
                        }
                    });
                odataWriter.WriteEnd();
                odataWriter.Flush();
            }
            
            message.Stream.Position = 0;
            var output = new StreamReader(message.Stream).ReadToEnd();
            Assert.IsFalse(output.Contains("Collection(Edm.GeographyPoint)"), @"output.Contains(""Collection(Edm.GeographyPoint)"" == false");
        }
Exemplo n.º 25
0
        public string GetSampleEntityPayload(object entity, IEnumerable <string> projectedProperties)
        {
            var message = new SimpleResponseMessage(this.StatusCode, this.ContentType);

            using (var writer = new ODataMessageWriter(message, Settings))
            {
                WriteEntry(writer.CreateODataEntryWriter(), entity, projectedProperties);
            }

            return(message.GetMessageString());
        }
Exemplo n.º 26
0
        public void UpdateEnumProperty()
        {
            // query an entry
            ODataEntry productEntry = this.QueryEntityItem("Products(5)") as ODataEntry;

            // send a request to update an entry property
            productEntry = new ODataEntry()
            {
                TypeName   = NameSpacePrefix + "Product",
                Properties = new[]
                {
                    new ODataProperty {
                        Name = "SkinColor", Value = new ODataEnumValue("Green")
                    },
                    new ODataProperty {
                        Name = "UserAccess", Value = new ODataEnumValue("Read")
                    }
                }
            };

            var settings = new ODataMessageWriterSettings();

            settings.PayloadBaseUri = ServiceBaseUri;
            settings.AutoComputePayloadMetadataInJson = true;

            var productType = Model.FindDeclaredType(NameSpacePrefix + "Product") as IEdmEntityType;
            var productSet  = Model.EntityContainer.FindEntitySet("Products");

            foreach (var mimeType in mimeTypes)
            {
                var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri + "Products(5)"));
                requestMessage.SetHeader("Content-Type", mimeType);
                requestMessage.SetHeader("Accept", mimeType);
                requestMessage.Method = "PATCH";

                using (var messageWriter = new ODataMessageWriter(requestMessage, settings, Model))
                {
                    var odataWriter = messageWriter.CreateODataEntryWriter(productSet, productType);
                    odataWriter.WriteStart(productEntry);
                    odataWriter.WriteEnd();
                }

                var responseMessage = requestMessage.GetResponse();

                // verify the update
                Assert.AreEqual(204, responseMessage.StatusCode);
                ODataEntry     updatedProduct = this.QueryEntityItem("Products(5)") as ODataEntry;
                ODataEnumValue skinColor      = updatedProduct.Properties.Single(p => p.Name == "SkinColor").Value as ODataEnumValue;
                ODataEnumValue userAccess     = updatedProduct.Properties.Single(p => p.Name == "UserAccess").Value as ODataEnumValue;
                Assert.AreEqual("Green", skinColor.Value);
                Assert.AreEqual("Read", userAccess.Value);
            }
        }
Exemplo n.º 27
0
        public static byte[] Serialize(this ITableEntity entity)
        {
            MemoryStream ms = new MemoryStream();

            using (var messageWriter = new ODataMessageWriter(new Message(ms), new ODataMessageWriterSettings()))
            {
                // Create an entry writer to write a top-level entry to the message.
                ODataWriter entryWriter = messageWriter.CreateODataEntryWriter();
                TableOperationHttpWebRequestFactory.WriteOdataEntity(entity, TableOperationType.Insert, null, entryWriter, null, true);
                return(ms.ToArray());
            }
        }
Exemplo n.º 28
0
        protected override async Task<Stream> WriteEntryContentAsync(string method, string collection, string commandText, IDictionary<string, object> entryData, bool resultRequired)
        {
#if SILVERLIGHT
            IODataRequestMessage
#else
            IODataRequestMessageAsync
#endif
            message = IsBatch
                ? await CreateBatchOperationMessageAsync(method, collection, entryData, commandText, resultRequired)
                : new ODataRequestMessage();

            if (method == RestVerbs.Get || method == RestVerbs.Delete)
                return null;

            var entityType = _model.FindDeclaredType(
                _session.Metadata.GetQualifiedTypeName(collection)) as IEdmEntityType;
            var model = method == RestVerbs.Patch ? new EdmDeltaModel(_model, entityType, entryData.Keys) : _model;

            using (var messageWriter = new ODataMessageWriter(message, GetWriterSettings(), model))
            {
                var contentId = _deferredBatchWriter != null ? _deferredBatchWriter.Value.GetContentId(entryData, null) : null;
                //var entityCollection = _session.Metadata.GetEntityCollection(collection);
                var entityCollection = _session.Metadata.NavigateToCollection(collection);
                var entryDetails = _session.Metadata.ParseEntryDetails(entityCollection.Name, entryData, contentId);

                var entryWriter = messageWriter.CreateODataEntryWriter();
                var entry = CreateODataEntry(entityType.FullName(), entryDetails.Properties);

                entryWriter.WriteStart(entry);

                if (entryDetails.Links != null)
                {
                    foreach (var link in entryDetails.Links)
                    {
                        if (link.Value.Any(x => x.LinkData != null))
                        {
                            WriteLink(entryWriter, entry, link.Key, link.Value);
                        }
                    }
                }

                entryWriter.WriteEnd();

                if (IsBatch)
                    return null;

#if SILVERLIGHT
                return message.GetStream();
#else
                return await message.GetStreamAsync();
#endif
            }
        }
        private byte[] ClientWriteAsyncBatchRequest()
        {
            var stream = new MemoryStream();

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

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

                batchWriter.WriteStartBatch();

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

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

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

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

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

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

                batchWriter.WriteEndChangeset();

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

                batchWriter.WriteEndBatch();

                stream.Position = 0;
                return stream.ToArray();
            }
        }
Exemplo n.º 30
0
        public void EmployeeEntryTest()
        {
            foreach (var mimeType in this.mimeTypes)
            {
                var settings = new ODataMessageWriterSettings()
                {
                    PayloadBaseUri = this.ServiceUri
                };
                settings.ODataUri = new ODataUri()
                {
                    ServiceRoot = this.ServiceUri
                };
                string outputWithTypeCast    = null;
                string outputWithoutTypeCast = null;

                // employee entry as response of person(1)
                var responseMessageWithoutTypeCast = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutTypeCast.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutTypeCast, settings))
                {
                    var odataWriter = messageWriter.CreateODataEntryWriter();
                    outputWithoutTypeCast = this.WriteAndVerifyEmployeeEntry(responseMessageWithoutTypeCast, odataWriter,
                                                                             false, mimeType);
                }

                // employee entry as response of person(1)/EmployeeTyeName, in this case the test sets ExpectedTypeName as Employee in Serialization info
                var responseMessageWithTypeCast = new StreamResponseMessage(new MemoryStream());
                responseMessageWithTypeCast.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithTypeCast, settings))
                {
                    var odataWriter = messageWriter.CreateODataEntryWriter();
                    outputWithTypeCast = this.WriteAndVerifyEmployeeEntry(responseMessageWithTypeCast, odataWriter, true,
                                                                          mimeType);
                }

                if (mimeType.Contains(MimeTypes.ODataParameterMinimalMetadata) || mimeType.Contains(MimeTypes.ODataParameterFullMetadata))
                {
                    // expect type cast in odata.metadata if EntitySetElementTypeName != ExpectedTypeName
                    Assert.IsTrue(outputWithoutTypeCast.Contains(this.ServiceUri + "$metadata#Person/$entity"));
                    Assert.IsTrue(
                        outputWithTypeCast.Contains(this.ServiceUri + "$metadata#Person/" + NameSpace +
                                                    "Employee/$entity"));
                }

                if (mimeType.Contains(MimeTypes.ApplicationJsonLight))
                {
                    // write odata.type if entry TypeName != ExpectedTypeName
                    Assert.IsTrue(outputWithoutTypeCast.Contains("odata.type"));
                    Assert.IsFalse(outputWithTypeCast.Contains("odata.type"));
                }
            }
        }
        public void TestCreateODataEntryWriter_InJsonLight_WithoutEntitySetOrType_DoesNotThrow()
        {
            // Arrange
            IODataResponseMessage      response = CreateResponse();
            ODataMessageWriterSettings settings = CreateJsonLightSettings();
            IEdmModel model = CreateModel();

            using (ODataMessageWriter writer = new ODataMessageWriter(response, settings, model))
            {
                // Act & Assert
                Assert.DoesNotThrow(() => writer.CreateODataEntryWriter());
            }
        }
        public void TestCreateODataEntryWriter_InJsonLight_WithoutEntitySetOrType_Throws()
        {
            // Arrange
            IODataResponseMessage response = CreateResponse();
            ODataMessageWriterSettings settings = CreateJsonLightSettings();
            IEdmModel model = CreateModel();

            using (ODataMessageWriter writer = new ODataMessageWriter(response, settings, model))
            {
                // Act & Assert
                Assert.Throws<ODataException>(() => writer.CreateODataEntryWriter());
            }
        }
Exemplo n.º 33
0
        public void TestCreateODataEntryWriter_InJsonLight_WithEntitySetButWithoutType_DoesNotThrow()
        {
            // Arrange
            IODataResponseMessage      response = CreateResponse();
            ODataMessageWriterSettings settings = CreateJsonLightSettings();
            IEdmModel     model     = CreateModel();
            IEdmEntitySet entitySet = model.EntityContainers().Single().EntitySets().First();

            using (ODataMessageWriter writer = new ODataMessageWriter(response, settings, model))
            {
                // Act & Assert
                Assert.DoesNotThrow(() => writer.CreateODataEntryWriter(entitySet));
            }
        }
        public void TestCreateODataEntryWriter_InJsonLight_WithEntitySetButWithoutType_DoesNotThrow()
        {
            // Arrange
            IODataResponseMessage response = CreateResponse();
            ODataMessageWriterSettings settings = CreateJsonLightSettings();
            IEdmModel model = CreateModel();
            IEdmEntitySet entitySet = model.EntityContainers().Single().EntitySets().First();

            using (ODataMessageWriter writer = new ODataMessageWriter(response, settings, model))
            {
                // Act & Assert
                Assert.DoesNotThrow(() => writer.CreateODataEntryWriter(entitySet));
            }
        }
Exemplo n.º 35
0
        public void EntryMetadataUrlRoundTrip()
        {
            var stream = new MemoryStream();
            var writerRequestMemoryMessage = new InMemoryMessage();

            writerRequestMemoryMessage.Stream = stream;
            writerRequestMemoryMessage.SetHeader("Content-Type", "application/json");

            var writerSettings = new ODataMessageWriterSettings()
            {
                Version = ODataVersion.V4, DisableMessageStreamDisposal = true
            };

            writerSettings.ODataUri = new ODataUri()
            {
                ServiceRoot = new Uri("http://christro.svc/")
            };

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

            odataEntry.Property("Id", 1);
            odataEntry.Property("Name", "");
            odataEntry.Property("TickerSymbol", "MSFT");

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

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

            Console.WriteLine(readerPayloadInput);

            var readerResponseMemoryMessage = new InMemoryMessage();

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

            var messageReader = new ODataMessageReader((IODataResponseMessage)readerResponseMemoryMessage, new ODataMessageReaderSettings()
            {
                MaxProtocolVersion = ODataVersion.V4, DisableMessageStreamDisposal = true
            }, this.model);
            var organizationReader = messageReader.CreateODataEntryReader(this.organizationsSet, this.organizationsSet.EntityType());

            organizationReader.Read().Should().Be(true);
            organizationReader.Item.As <ODataEntry>();
        }
Exemplo n.º 36
0
        public void HandCraftEdmType()
        {
            foreach (var mimeType in this.testMimeTypes)
            {
                EdmModel edmModel = new EdmModel();

                EdmEntityType edmEntityType = new EdmEntityType(NameSpace, "Person");
                edmModel.AddElement(edmEntityType);
                var keyProperty = new EdmStructuralProperty(edmEntityType, "PersonId", EdmCoreModel.Instance.GetInt32(false));
                edmEntityType.AddKeys(new IEdmStructuralProperty[] { keyProperty });
                edmEntityType.AddProperty(keyProperty);
                var property = new EdmStructuralProperty(edmEntityType, "Name", EdmCoreModel.Instance.GetString(true));
                edmEntityType.AddKeys(new IEdmStructuralProperty[] { property });
                edmEntityType.AddProperty(property);

                var defaultContainer = new EdmEntityContainer(NameSpace, "DefaultContainer");
                edmModel.AddElement(defaultContainer);

                EdmEntitySet entitySet = new EdmEntitySet(defaultContainer, "Person", edmEntityType);
                defaultContainer.AddElement(entitySet);

                var settings = new ODataMessageWriterSettings();
                settings.ODataUri = new ODataUri()
                {
                    ServiceRoot = this.ServiceUri
                };
                var responseMessageWithoutModel = new StreamResponseMessage(new MemoryStream());
                responseMessageWithoutModel.SetHeader("Content-Type", mimeType);
                using (var messageWriter = new ODataMessageWriter(responseMessageWithoutModel, settings))
                {
                    var odataWriter = messageWriter.CreateODataEntryWriter(entitySet, edmEntityType);

                    var    entry         = this.CreatePersonEntryWithoutSerializationInfo();
                    string expectedError = null;
                    if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                    {
                        expectedError = "ODataFeedAndEntryTypeContext_MetadataOrSerializationInfoMissing";
                    }

                    AssertThrows <ODataException>(
                        () =>
                    {
                        odataWriter.WriteStart(entry);
                        odataWriter.WriteEnd();
                    },
                        expectedError);
                }
            }
        }
Exemplo n.º 37
0
        public static byte[] Serialize(this ITableEntity entity)
        {
            MemoryStream ms = new MemoryStream();

            using (var messageWriter = new ODataMessageWriter(new Message(ms), new ODataMessageWriterSettings()))
            {
                // Create an entry writer to write a top-level entry to the message.
                ODataWriter entryWriter      = messageWriter.CreateODataEntryWriter();
                var         writeODataEntity = typeof(TableConstants).Assembly.GetType("Microsoft.WindowsAzure.Storage.Table.Protocol.TableOperationHttpWebRequestFactory")
                                               .GetMethod("WriteOdataEntity", BindingFlags.NonPublic | BindingFlags.Static);

                writeODataEntity.Invoke(null, new object[] { entity, TableOperationType.Insert, null, entryWriter });
                return(ms.ToArray());
            }
        }
Exemplo n.º 38
0
        private static void WriteODataEntry(IEdmModel model, Stream stream, SingletonSegment singletonSegment,
                                            ODataPath queryPath)
        {
            var entry = new ODataEntry()
            {
                Properties = new List <ODataProperty>()
                {
                    new ODataProperty()
                    {
                        Name  = "CompanyID",
                        Value = 1
                    },
                    new ODataProperty()
                    {
                        Name  = "Name",
                        Value = "Wonderland"
                    },
                    new ODataProperty()
                    {
                        Name  = "Revenue",
                        Value = 1000
                    }
                }
            };

            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings();

            writerSettings.Version  = ODataVersion.V4;
            writerSettings.ODataUri = new ODataUri()
            {
                ServiceRoot = ServiceRootUri, Path = queryPath
            };
            writerSettings.PayloadBaseUri = ServiceRootUri;
            writerSettings.SetContentType("application/json;odata.metadata=full", Encoding.UTF8.WebName);
            writerSettings.AutoComputePayloadMetadataInJson = true;

            var message = new ODataResponseMessage(stream);

            using (var messageWriter = new ODataMessageWriter(message, writerSettings, model))
            {
                var entryWriter = messageWriter.CreateODataEntryWriter(singletonSegment.Singleton,
                                                                       singletonSegment.EdmType as EdmEntityType);

                entryWriter.WriteStart(entry);
                entryWriter.WriteEnd();
                entryWriter.Flush();
            }
        }
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            if (writeContext == null)
            {
                throw Error.ArgumentNull("writeContext");
            }

            ODataWriter writer = messageWriter.CreateODataEntryWriter();
            WriteObjectInline(graph, writer, writeContext);
            writer.Flush();
        }
Exemplo n.º 40
0
        /// <summary>
        /// Creates an OData entry response message from an RDF graph
        /// </summary>
        /// <param name="resultsGraph">The SPARQL results graph to be processed</param>
        /// <param name="entryResource">The URI of the RDF resource to be converted to an entry</param>
        /// <param name="entryType">The fully qualified name of the type of entity that the RDF resource is to be converted to</param>
        public void CreateEntryFromGraph(IGraph resultsGraph, string entryResource, string entryType)
        {
            var msgWriter   = new ODataMessageWriter(_response, _writerSettings, _map.Model);
            var entryWriter = msgWriter.CreateODataEntryWriter();
            var entry       = CreateODataEntry(resultsGraph, entryResource, entryType);

            entryWriter.WriteStart(entry);
            var navigableProperties = WriteNavigationLinks(entryWriter, entry.ReadLink, resultsGraph, entryResource, entryType);

            if (_writerSettings.Version == null || _writerSettings.Version >= ODataVersion.V3)
            {
                entry.AssociationLinks = MakeAssociationLinks(entry.ReadLink, navigableProperties);
            }
            entryWriter.WriteEnd();
            entryWriter.Flush();
        }
        public void TestCreateODataEntryWriter_InJsonLight_WithEntitySetButWithoutType_DoesNotThrow()
        {
            // Arrange
            IODataResponseMessage response = CreateResponse();
            ODataMessageWriterSettings settings = CreateJsonLightSettings();
            IEdmModel model = CreateModel();
            IEdmEntitySet entitySet = model.EntityContainers().Single().EntitySets().First();

            using (ODataMessageWriter writer = new ODataMessageWriter(response, settings, model))
            {
                // Act
                writer.CreateODataEntryWriter(entitySet);

                // No assert (just ensuring this kind of call does not throw).
            }
        }
        public static void SetODataRequestContent(IODataRequestMessage requestMessage, IEdmModel model, IInventoryItem inventoryItem)
        {
            var setting = new ODataMessageWriterSettings();

            setting.SetContentType(ODataFormat.Atom);
            ODataMessageWriter oDatamessageWriter = new ODataMessageWriter(requestMessage, setting, model);
            ODataWriter        oDataEntrywriter   = oDatamessageWriter.CreateODataEntryWriter();

            oDataEntrywriter.WriteStart(new ODataEntry()
            {
                TypeName   = TypeName,
                Properties = GetODataProperties(inventoryItem)
            });

            oDataEntrywriter.WriteEnd();
        }
        internal static Tuple<HttpWebRequest, Stream> BuildRequestForTableOperation(Uri uri, UriQueryBuilder builder, IBufferManager bufferManager, int? timeout, TableOperation operation, OperationContext ctx)
        {
            HttpWebRequest msg = BuildRequestCore(uri, builder, operation.HttpMethod, timeout, ctx);

            if (operation.OperationType == TableOperationType.InsertOrMerge || operation.OperationType == TableOperationType.Merge)
            {
                // post tunnelling
                msg.Headers.Add("X-HTTP-Method", "MERGE");
            }

            // etag
            if (operation.OperationType == TableOperationType.Delete ||
                operation.OperationType == TableOperationType.Replace ||
                operation.OperationType == TableOperationType.Merge)
            {
                if (operation.Entity.ETag != null)
                {
                    msg.Headers.Add("If-Match", operation.Entity.ETag);
                }
            }

            if (operation.OperationType == TableOperationType.Insert ||
                operation.OperationType == TableOperationType.Merge ||
                operation.OperationType == TableOperationType.InsertOrMerge ||
                operation.OperationType == TableOperationType.InsertOrReplace ||
                operation.OperationType == TableOperationType.Replace)
            {
                // create the writer, indent for readability of the examples.  
                ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
                {
                    CheckCharacters = false,   // sets this flag on the XmlWriter for ATOM  
                    Version = ODataVersion.V2 // set the Odata version to use when writing the entry 
                };

                HttpWebRequestAdapterMessage adapterMsg = new HttpWebRequestAdapterMessage(msg, bufferManager);
                ODataMessageWriter odataWriter = new ODataMessageWriter(adapterMsg, writerSettings);
                ODataWriter writer = odataWriter.CreateODataEntryWriter();
                WriteOdataEntity(operation.Entity, operation.OperationType, ctx, writer);

                return new Tuple<HttpWebRequest, Stream>(adapterMsg.GetPopulatedMessage(), adapterMsg.GetStream());
            }

            return new Tuple<HttpWebRequest, Stream>(msg, null);
        }
        /// <inheritdoc />
        public override void WriteObject(object graph, Type type, ODataMessageWriter messageWriter,
            ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            if (writeContext == null)
            {
                throw Error.ArgumentNull("writeContext");
            }

            IEdmEntitySet entitySet = writeContext.EntitySet;
            if (entitySet == null)
            {
                throw new SerializationException(SRResources.EntitySetMissingDuringSerialization);
            }

            ODataWriter writer = messageWriter.CreateODataEntryWriter(entitySet, entitySet.ElementType);
            WriteObjectInline(graph, entitySet.ElementType.ToEdmTypeReference(isNullable: false), writer, writeContext);
        }
        /// <inheritdoc />
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            if (writeContext == null)
            {
                throw Error.ArgumentNull("writeContext");
            }

            IEdmEntitySet entitySet = writeContext.EntitySet;

            if (entitySet == null)
            {
                throw new SerializationException(SRResources.EntitySetMissingDuringSerialization);
            }

            IEdmEntityType entityType = EntityType.EntityDefinition();
            ODataWriter writer = messageWriter.CreateODataEntryWriter(entitySet, entityType);
            WriteObjectInline(graph, writer, writeContext);
        }
        protected void WriteAnnotationsAndValidatePayload(Action<ODataWriter> action, ODataFormat format, string expectedPayload, bool request, bool createFeedWriter)
        {
            var writerSettings = new ODataMessageWriterSettings { DisableMessageStreamDisposal = true, EnableAtom = true };
            writerSettings.SetContentType(format);
            writerSettings.SetServiceDocumentUri(new Uri("http://www.example.com/"));

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

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

            Assert.AreEqual(expectedPayload, payload);
        }
Exemplo n.º 47
0
 /// <summary>
 /// Creates an OData entry response message from an RDF graph
 /// </summary>
 /// <param name="resultsGraph">The SPARQL results graph to be processed</param>
 /// <param name="entryResource">The URI of the RDF resource to be converted to an entry</param>
 /// <param name="entryType">The fully qualified name of the type of entity that the RDF resource is to be converted to</param>
 public void CreateEntryFromGraph(IGraph resultsGraph, string entryResource, string entryType)
 {
     var msgWriter = new ODataMessageWriter(_response, _writerSettings, _map.Model);
     var entryWriter = msgWriter.CreateODataEntryWriter();
     var entry = CreateODataEntry(resultsGraph, entryResource, entryType);
     entryWriter.WriteStart(entry);
     var navigableProperties = WriteNavigationLinks(entryWriter, entry.ReadLink, resultsGraph, entryResource, entryType);
     if (_writerSettings.Version == null || _writerSettings.Version >= ODataVersion.V3)
     {
         entry.AssociationLinks = MakeAssociationLinks(entry.ReadLink, navigableProperties);
     }
     entryWriter.WriteEnd();
     entryWriter.Flush();
 }
        internal static Tuple<HttpWebRequest, Stream> BuildRequestForTableOperation(Uri uri, UriQueryBuilder builder, IBufferManager bufferManager, int? timeout, TableOperation operation, bool useVersionHeader, OperationContext ctx, TableRequestOptions options, string accountName)
        {
            HttpWebRequest msg = BuildRequestCore(uri, builder, operation.HttpMethod, timeout, useVersionHeader, ctx);

            TablePayloadFormat payloadFormat = options.PayloadFormat.Value;

            // Set Accept and Content-Type based on the payload format.
            SetAcceptHeaderForHttpWebRequest(msg, payloadFormat);
            Logger.LogInformational(ctx, SR.PayloadFormat, payloadFormat);

            if (operation.HttpMethod != "HEAD" && operation.HttpMethod != "GET")
            {
                SetContentTypeForHttpWebRequest(msg, payloadFormat);
            }

            if (operation.OperationType == TableOperationType.InsertOrMerge || operation.OperationType == TableOperationType.Merge)
            {
                options.AssertNoEncryptionPolicyOrStrictMode();

                // post tunnelling
                msg.Headers.Add("X-HTTP-Method", "MERGE");
            }

            // etag
            if (operation.OperationType == TableOperationType.Delete ||
                operation.OperationType == TableOperationType.Replace ||
                operation.OperationType == TableOperationType.Merge)
            {
                if (operation.Entity.ETag != null)
                {
                    msg.Headers.Add("If-Match", operation.Entity.ETag);
                }
            }

            // prefer header
            if (operation.OperationType == TableOperationType.Insert)
            {
                msg.Headers.Add("Prefer", operation.EchoContent ? "return-content" : "return-no-content");
            }
            
            if (operation.OperationType == TableOperationType.Insert ||
                operation.OperationType == TableOperationType.Merge ||
                operation.OperationType == TableOperationType.InsertOrMerge ||
                operation.OperationType == TableOperationType.InsertOrReplace ||
                operation.OperationType == TableOperationType.Replace)
            {
                // create the writer, indent for readability of the examples.  
                ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
                {
                    CheckCharacters = false,   // sets this flag on the XmlWriter for ATOM  
                    Version = TableConstants.ODataProtocolVersion // set the Odata version to use when writing the entry 
                };

                HttpWebRequestAdapterMessage adapterMsg = new HttpWebRequestAdapterMessage(msg, bufferManager);

                if (operation.HttpMethod != "HEAD" && operation.HttpMethod != "GET")
                {
                    SetContentTypeForAdapterMessage(adapterMsg, payloadFormat);
                }
                
                ODataMessageWriter odataWriter = new ODataMessageWriter(adapterMsg, writerSettings, new TableStorageModel(accountName));
                ODataWriter writer = odataWriter.CreateODataEntryWriter();
                WriteOdataEntity(operation.Entity, operation.OperationType, ctx, writer, options);

                return new Tuple<HttpWebRequest, Stream>(adapterMsg.GetPopulatedMessage(), adapterMsg.GetStream());
            }

            return new Tuple<HttpWebRequest, Stream>(msg, null);
        }
        internal static Tuple<HttpWebRequest, Stream> BuildRequestForTableBatchOperation(Uri uri, UriQueryBuilder builder, IBufferManager bufferManager, int? timeout, string tableName, TableBatchOperation batch, bool useVersionHeader, OperationContext ctx, TableRequestOptions options, string accountName)
        {
            HttpWebRequest msg = BuildRequestCore(NavigationHelper.AppendPathToSingleUri(uri, "$batch"), builder, "POST", timeout, useVersionHeader, ctx);
            TablePayloadFormat payloadFormat = options.PayloadFormat.Value;
            Logger.LogInformational(ctx, SR.PayloadFormat, payloadFormat);

            // create the writer, indent for readability of the examples.  
            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
            {
                CheckCharacters = false,   // sets this flag on the XmlWriter for ATOM  
                Version = TableConstants.ODataProtocolVersion // set the Odata version to use when writing the entry 
            };

            HttpWebRequestAdapterMessage adapterMsg = new HttpWebRequestAdapterMessage(msg, bufferManager);

            ODataMessageWriter odataWriter = new ODataMessageWriter(adapterMsg, writerSettings);

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

            bool isQuery = batch.Count == 1 && batch[0].OperationType == TableOperationType.Retrieve;

            // Query operations should not be inside changeset in payload
            if (!isQuery)
            {
                // Start Operation
                batchWriter.WriteStartChangeset();
                batchWriter.Flush();
            }

            foreach (TableOperation operation in batch)
            {
                string httpMethod = operation.HttpMethod;
                if (operation.OperationType == TableOperationType.Merge || operation.OperationType == TableOperationType.InsertOrMerge)
                {
                    options.AssertNoEncryptionPolicyOrStrictMode();
                    httpMethod = "MERGE";
                }

                ODataBatchOperationRequestMessage mimePartMsg = batchWriter.CreateOperationRequestMessage(httpMethod, operation.GenerateRequestURI(uri, tableName));
                SetAcceptAndContentTypeForODataBatchMessage(mimePartMsg, payloadFormat);

                // etag
                if (operation.OperationType == TableOperationType.Delete ||
                    operation.OperationType == TableOperationType.Replace ||
                    operation.OperationType == TableOperationType.Merge)
                {
                    mimePartMsg.SetHeader("If-Match", operation.Entity.ETag);
                }

                // Prefer header
                if (operation.OperationType == TableOperationType.Insert)
                {
                    mimePartMsg.SetHeader("Prefer", operation.EchoContent ? "return-content" : "return-no-content");
                }
                
                if (operation.OperationType != TableOperationType.Delete && operation.OperationType != TableOperationType.Retrieve)
                {
                    using (ODataMessageWriter batchEntryWriter = new ODataMessageWriter(mimePartMsg, writerSettings, new TableStorageModel(accountName)))
                    {
                        // Write entity
                        ODataWriter entryWriter = batchEntryWriter.CreateODataEntryWriter();
                        WriteOdataEntity(operation.Entity, operation.OperationType, ctx, entryWriter, options);
                    }
                }
            }

            if (!isQuery)
            {
                // End Operation
                batchWriter.WriteEndChangeset();
            }

            // End Batch
            batchWriter.WriteEndBatch();
            batchWriter.Flush();

            return new Tuple<HttpWebRequest, Stream>(adapterMsg.GetPopulatedMessage(), adapterMsg.GetStream());
        }
        protected override async Task<Stream> WriteEntryContentAsync(string method, string collection, string commandText, IDictionary<string, object> entryData)
        {
#if SILVERLIGHT
            IODataRequestMessage
#else
            IODataRequestMessageAsync
#endif
                message = IsBatch
                ? await CreateOperationRequestMessageAsync(method, collection, entryData, commandText)
                : new ODataRequestMessage();

            if (method == RestVerbs.Get || method == RestVerbs.Delete)
                return null;

            var entityType = _model.FindDeclaredType(
                _session.Metadata.GetEntityCollectionQualifiedTypeName(collection)) as IEdmEntityType;
            var model = method == RestVerbs.Patch ? new EdmDeltaModel(_model, entityType, entryData.Keys) : _model;

            using (var messageWriter = new ODataMessageWriter(message, GetWriterSettings(), model))
            {
                var contentId = _deferredBatchWriter != null ? _deferredBatchWriter.Value.GetContentId(entryData, null) : null;
                var entityCollection = _session.Metadata.GetEntityCollection(collection);
                var entryDetails = _session.Metadata.ParseEntryDetails(entityCollection.Name, entryData, contentId);

                var entryWriter = messageWriter.CreateODataEntryWriter();
                var entry = new Microsoft.Data.OData.ODataEntry();
                entry.TypeName = entityType.FullName();

                var typeProperties = (_model.FindDeclaredType(entry.TypeName) as IEdmEntityType).Properties();
                Func<string, string> findMatchingPropertyName = name =>
                {
                    var property = typeProperties.BestMatch(y => y.Name, name, _session.Pluralizer);
                    return property != null ? property.Name : name;
                };
                entry.Properties = entryDetails.Properties.Select(x => new ODataProperty()
                {
                    Name = findMatchingPropertyName(x.Key),
                    Value = GetPropertyValue(typeProperties, x.Key, x.Value)
                }).ToList();

                entryWriter.WriteStart(entry);

                if (entryDetails.Links != null)
                {
                    foreach (var link in entryDetails.Links)
                    {
                        if (link.Value.Any(x => x.LinkData != null))
                        {
                            WriteLink(entryWriter, entry, link.Key, link.Value);
                        }
                    }
                }

                entryWriter.WriteEnd();

                if (IsBatch)
                    return null;

#if SILVERLIGHT
                return message.GetStream();
#else
                return await message.GetStreamAsync();
#endif
            }
        }
 private ODataWriter CreateODataEntryWriter(ODataMessageWriter messageWriter, IEdmEntitySet entitySet, IEdmEntityType entityType, bool hasModel)
 {
     if (hasModel)
     {
         return messageWriter.CreateODataEntryWriter(entitySet, entityType);
     }
     else
     {
         return messageWriter.CreateODataEntryWriter();
     }
 }
        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();
            }
        }
        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 void createUpdateOperationRequestMessage(ref ODataBatchWriter writer, Change change, string tableName, string[] headers)
        {
            string id = this.getKeyType(tableName).IsString() ? "'" + change.id + "'" : change.id;
            Uri uri = new Uri(tableName + "(" + id + ")", UriKind.Relative);
            
            var updateOperaitonMessage = writer.CreateOperationRequestMessage("PATCH", uri);
            updateOperaitonMessage.SetHeader("Content-Type", "application/json");
             

            using (var operationMessageWriter = new ODataMessageWriter(updateOperaitonMessage))
            {
                var entityWriter = operationMessageWriter.CreateODataEntryWriter();
                var entry = new ODataEntry()
                {
                    Properties = createOperationProperties(change.data, tableName, headers),
                    TypeName = this.GetEntityTypeName(tableName)
                };
                entityWriter.WriteStart(entry);
                entityWriter.WriteEnd();
            }
        }
        internal static Tuple<HttpWebRequest, Stream> BuildRequestForTableBatchOperation(Uri uri, UriQueryBuilder builder, int? timeout, Uri baseUri, string tableName, TableBatchOperation batch, OperationContext ctx)
        {
            HttpWebRequest msg = BuildRequestCore(NavigationHelper.AppendPathToUri(uri, "$batch"), builder, "POST", timeout, ctx);

            // create the writer, indent for readability of the examples.  
            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
            {
                CheckCharacters = false,   // sets this flag on the XmlWriter for ATOM  
                Version = ODataVersion.V2 // set the Odata version to use when writing the entry 
            };

            HttpWebRequestAdapterMessage adapterMsg = new HttpWebRequestAdapterMessage(msg);

            // Start Batch
            ODataMessageWriter odataWriter = new ODataMessageWriter(adapterMsg, writerSettings);
            ODataBatchWriter batchWriter = odataWriter.CreateODataBatchWriter();
            batchWriter.WriteStartBatch();

            bool isQuery = batch.Count == 1 && batch[0].OperationType == TableOperationType.Retrieve;

            // Query operations should not be inside changeset in payload
            if (!isQuery)
            {
                // Start Operation
                batchWriter.WriteStartChangeset();
                batchWriter.Flush();
            }

            foreach (TableOperation operation in batch)
            {
                string httpMethod = operation.OperationType == TableOperationType.Merge || operation.OperationType == TableOperationType.InsertOrMerge ? "MERGE" : operation.HttpMethod;

                ODataBatchOperationRequestMessage mimePartMsg = batchWriter.CreateOperationRequestMessage(httpMethod, operation.GenerateRequestURI(baseUri, tableName));

                // etag
                if (operation.OperationType == TableOperationType.Delete ||
                    operation.OperationType == TableOperationType.Replace ||
                    operation.OperationType == TableOperationType.Merge)
                {
                    mimePartMsg.SetHeader("If-Match", operation.Entity.ETag);
                }

                if (operation.OperationType != TableOperationType.Delete && operation.OperationType != TableOperationType.Retrieve)
                {
                    using (ODataMessageWriter batchEntryWriter = new ODataMessageWriter(mimePartMsg, writerSettings))
                    {
                        // Write entity
                        ODataWriter entryWriter = batchEntryWriter.CreateODataEntryWriter();
                        WriteOdataEntity(operation.Entity, operation.OperationType, ctx, entryWriter);
                    }
                }
            }

            if (!isQuery)
            {
                // End Operation
                batchWriter.WriteEndChangeset();
            }

            // End Batch
            batchWriter.WriteEndBatch();
            batchWriter.Flush();

            return new Tuple<HttpWebRequest, Stream>(adapterMsg.GetPopulatedMessage(), adapterMsg.GetStream());
        }
 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(IEdmModel userModel, ODataEntry entry, EdmEntitySet entitySet, IEdmEntityType entityType, bool fullMetadata = false)
        {
            var message = new InMemoryMessage() { Stream = new MemoryStream() };

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

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

            message.Stream.Seek(0, SeekOrigin.Begin);
            using (StreamReader reader = new StreamReader(message.Stream))
            {
                return reader.ReadToEnd();
            }
        }
Exemplo n.º 58
0
        private string GetWriterOutputForContentTypeAndKnobValue(
            string contentType,
            bool autoComputePayloadMetadataInJson,
            ODataItem[] itemsToWrite,
            EdmModel edmModel,
            IEdmEntitySetBase edmEntitySet,
            EdmEntityType edmEntityType,
            string selectClause = null,
            string expandClause = null,
            string resourcePath = null,
            bool enableFullValidation = true)
        {
            MemoryStream outputStream = new MemoryStream();
            IODataResponseMessage message = new InMemoryMessage() { Stream = outputStream };
            message.SetHeader("Content-Type", contentType);
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings()
            {
                AutoComputePayloadMetadataInJson = autoComputePayloadMetadataInJson,
                EnableFullValidation = enableFullValidation
            };

            var result = new ODataQueryOptionParser(edmModel, edmEntityType, edmEntitySet, new Dictionary<string, string> { { "$expand", expandClause }, { "$select", selectClause } }).ParseSelectAndExpand();

            ODataUri odataUri = new ODataUri()
            {
                ServiceRoot = new Uri("http://example.org/odata.svc"),
                SelectAndExpand = result
            };

            if (resourcePath != null)
            {
                Uri requestUri = new Uri("http://example.org/odata.svc/" + resourcePath);
                odataUri.RequestUri = requestUri;
                odataUri.Path = new ODataUriParser(edmModel, new Uri("http://example.org/odata.svc/"), requestUri).ParsePath();
            }

            settings.ODataUri = odataUri;

            string output;
            using (var messageWriter = new ODataMessageWriter(message, settings, edmModel))
            {
                int currentIdx = 0;

                if (itemsToWrite[currentIdx] is ODataFeed)
                {
                    ODataWriter writer = messageWriter.CreateODataFeedWriter(edmEntitySet, edmEntityType);
                    this.WriteFeed(writer, itemsToWrite, ref currentIdx);
                }
                else if (itemsToWrite[currentIdx] is ODataEntry)
                {
                    ODataWriter writer = messageWriter.CreateODataEntryWriter(edmEntitySet, edmEntityType);
                    this.WriteEntry(writer, itemsToWrite, ref currentIdx);
                }
                else
                {
                    Assert.True(false, "Top level item to write must be entry or feed.");
                }

                currentIdx.Should().Be(itemsToWrite.Length, "Invalid list of items to write.");

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

            return output;
        }
        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);
            }
        }
        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();
            }
        }