예제 #1
0
        private List <ODataResource> ReadPayload(string payload, IEdmModel model, IEdmNavigationSource entitySet, IEdmStructuredType entityType, bool isFullMetadata = false)
        {
            InMemoryMessage message = new InMemoryMessage();

            if (isFullMetadata)
            {
                message.SetHeader("Content-Type", "application/json;odata.metadata=full");
            }
            else
            {
                message.SetHeader("Content-Type", "application/json;odata.metadata=minimal");
            }
            message.Stream = new MemoryStream(Encoding.UTF8.GetBytes(payload));

            List <ODataResource> entryList = new List <ODataResource>();

            using (var messageReader = new ODataMessageReader((IODataResponseMessage)message, null, model))
            {
                var reader = messageReader.CreateODataResourceReader(entitySet, entityType);
                while (reader.Read())
                {
                    switch (reader.State)
                    {
                    case ODataReaderState.ResourceEnd:
                        entryList.Add((ODataResource)reader.Item);
                        break;
                    }
                }
            }

            return(entryList);
        }
        public void GetHeaderGoesToInnerMessageAfterLaterInnerSetHeaderCall()
        {
            const string headerName        = "CustomHeaderName";
            const string headerValueBefore = "CustomerHeaderValueBefore";
            const string headerValueAfter  = "CustomerHeaderValueAfter";

            var simulatedRequestMessage = new InMemoryMessage();

            simulatedRequestMessage.SetHeader(headerName, headerValueBefore);

            var odataRequestMessage = new ODataRequestMessage(simulatedRequestMessage, false, false, -1);

            simulatedRequestMessage.SetHeader(headerName, headerValueAfter);

            Assert.Equal(headerValueAfter, odataRequestMessage.GetHeader(headerName));
        }
        private async Task <string> WriteAndGetPayloadAsync(IEdmModel edmModel, string contentType, Func <ODataMessageWriter, Task> test)
        {
            var message = new InMemoryMessage()
            {
                Stream = new MemoryStream()
            };

            if (contentType != null)
            {
                message.SetHeader("Content-Type", contentType);
            }

            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings();

            writerSettings.EnableMessageStreamDisposal = false;
            writerSettings.BaseUri = new Uri("http://www.example.com/");
            writerSettings.SetServiceDocumentUri(new Uri("http://www.example.com/"));

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

            message.Stream.Seek(0, SeekOrigin.Begin);
            using (StreamReader reader = new StreamReader(message.Stream))
            {
                return(reader.ReadToEnd());
            }
        }
예제 #4
0
        public void ErrorLocationReportedByMessageReaderForBadEdmxOfSingleLineShouldBeAbsolute()
        {
            Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(
                                                 "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                                 "<!--Remark-->" +
                                                 "<edmx:Edmx xmlns:edmx=\"http://docs.oasis-open.org/odata/ns/edmx\" Version=\"4.0\">" +
                                                 "<edmx:DataServices>" +
                                                 "<Schema xmlns=\"http://docs.oasis-open.org/odata/ns/edm\" Namespace=\"Org.OData.Core.V1\" Alias=\"Core\">" +
                                                 "<Annotation Term=\"Core.Description\">" +
                                                 "<String>Core terms needed to write vocabularies</String>" +
                                                 "</Annotation>" +
                                                 "</Schema>" +
                                                 "</edmx:DataServices>" +
                                                 "</edmx:Edmx>"));

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

            responseMessage.SetHeader("Content-Type", "application/xml");
            ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel());

            const string expectedErrorMessage =
                "The metadata document could not be read from the message content.\r\n" +
                "UnexpectedXmlElement : The schema element 'Annotation' was not expected in the given context. : (1, 250)\r\n";

            Action test = () => reader.ReadMetadataDocument();

            test.ShouldThrow <ODataException>().Where(e => e.Message.Equals(expectedErrorMessage));
        }
예제 #5
0
        public void ErrorLocationReportedByMessageReaderForBadEdmxShouldBeAbsolute()
        {
            Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(
                                                 @"<?xml version=""1.0"" encoding=""utf-8""?>
<!--Remark-->
<edmx:Edmx xmlns:edmx=""http://docs.oasis-open.org/odata/ns/edmx"" Version=""4.0"">
  <edmx:DataServices>
    <Schema xmlns=""http://docs.oasis-open.org/odata/ns/edm"" Namespace=""Org.OData.Core.V1"" Alias=""Core"">
      <Invalid Term=""Core.Description"">
        <String>Core terms needed to write vocabularies</String>
      </Invalid>
    </Schema>
  </edmx:DataServices>
</edmx:Edmx>"));

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

            responseMessage.SetHeader("Content-Type", "application/xml");
            ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel());

            const string expectedErrorMessage =
                "The metadata document could not be read from the message content.\r\n" +
                "UnexpectedXmlElement : The schema element 'Invalid' was not expected in the given context. : (6, 8)\r\n";

            Action test = () => reader.ReadMetadataDocument();

            test.Throws <ODataException>(expectedErrorMessage);
        }
        public void ReadMetadataDocument_WorksForJsonCSDL()
        {
            Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(@"{
  ""$Version"": ""4.0"",
  ""$EntityContainer"": ""NS.Container"",
  ""NS"": {
    ""Customer"": {
      ""$Kind"": ""EntityType"",
      ""$Key"": [
        ""Id""
      ],
      ""Id"": {
        ""$Type"": ""Edm.Int32""
      },
      ""Name"": {}
    },
    ""Container"": {
      ""$Kind"": ""EntityContainer"",
      ""Customers"": {
        ""$Collection"": true,
        ""$Type"": ""NS.Customer""
      }
    }
  }
}"));

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

            responseMessage.SetHeader("Content-Type", "application/json");
            ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel());

#if NETCOREAPP3_1 || NETCOREAPP2_1
            IEdmModel model = reader.ReadMetadataDocument();

            IEdmEntityType customerType = model.FindDeclaredType("NS.Customer") as IEdmEntityType;
            Assert.NotNull(customerType);

            IEdmProperty idProperty = customerType.FindProperty("Id");
            Assert.NotNull(idProperty);
            Assert.Equal("Edm.Int32", idProperty.Type.FullName());

            IEdmProperty nameProperty = customerType.FindProperty("Name");
            Assert.NotNull(nameProperty);
            Assert.Equal("Edm.String", nameProperty.Type.FullName());

            IEdmEntitySet customers = Assert.Single(model.EntityContainer.EntitySets());
            Assert.Equal("Customers", customers.Name);
            Assert.Same(customerType, customers.EntityType());
#else
            Action test = () => reader.ReadMetadataDocument();

            ODataException exception = Assert.Throws <ODataException>(test);
            Assert.Equal("The JSON metadata is not supported at this platform. It's only supported at platform implementing .NETStardard 2.0.", exception.Message);
#endif
        }
        public void GetDataServiceVersionWorksForRequest()
        {
            InMemoryMessage simulatedRequestMessage = new InMemoryMessage();

            simulatedRequestMessage.SetHeader(ODataConstants.ODataVersionHeader, "4.0");

            IODataRequestMessage request = new ODataRequestMessage(simulatedRequestMessage, false, false, long.MaxValue);
            ODataVersion         version = request.GetODataVersion(ODataVersion.V4);

            version.Should().Be(ODataUtils.StringToODataVersion(request.GetHeader(ODataConstants.ODataVersionHeader)));
        }
예제 #8
0
        public void GetDataServiceVersionWorksForResponse()
        {
            InMemoryMessage simulatedRequestMessage = new InMemoryMessage();

            simulatedRequestMessage.SetHeader(ODataConstants.ODataVersionHeader, "4.0");

            IODataResponseMessage response = new ODataResponseMessage(simulatedRequestMessage, false, false, long.MaxValue);
            ODataVersion          version  = response.GetODataVersion(ODataVersion.V4);

            Assert.Equal(ODataUtils.StringToODataVersion(response.GetHeader(ODataConstants.ODataVersionHeader)), version);
        }
예제 #9
0
        public void ReadMetadataDocumentShouldIncludeConverterForDefaultUnsignedIntImplementation()
        {
            Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(@"<?xml version=""1.0"" encoding=""utf-8""?>
<!--Remark-->
<edmx:Edmx xmlns:edmx=""http://docs.oasis-open.org/odata/ns/edmx"" Version=""4.0"">
  <edmx:DataServices>
    <Schema xmlns=""http://docs.oasis-open.org/odata/ns/edm"" Namespace=""MyNS"">
      <TypeDefinition Name=""UInt16"" UnderlyingType=""Edm.Int32"" />
      <TypeDefinition Name=""UInt32"" UnderlyingType=""Edm.Decimal"" />
      <TypeDefinition Name=""UInt64"" UnderlyingType=""Edm.Decimal"" />
      <EntityType Name=""Person"">
        <Key>
          <PropertyRef Name=""Id"" />
        </Key>
        <Property Name=""Id"" Type=""Edm.Int32"" Nullable=""false"" />
        <Property Name=""UInt16"" Type=""MyNS.UInt16"" Nullable=""false"" />
        <Property Name=""UInt32"" Type=""MyNS.UInt32"" Nullable=""false"" />
        <Property Name=""UInt64"" Type=""MyNS.UInt64"" Nullable=""false"" />
      </EntityType>
    </Schema>
  </edmx:DataServices>
</edmx:Edmx>"));

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

            responseMessage.SetHeader("Content-Type", "application/xml");
            ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel());
            var model = reader.ReadMetadataDocument();

            var personType = model.FindDeclaredType("MyNS.Person") as IEdmEntityType;

            Assert.NotNull(personType);

            var uint16Type = personType.FindProperty("UInt16").Type;
            var uint32Type = personType.FindProperty("UInt32").Type;
            var uint64Type = personType.FindProperty("UInt64").Type;

            var uint16Converter = model.GetPrimitiveValueConverter(uint16Type.AsTypeDefinition());
            var uint32Converter = model.GetPrimitiveValueConverter(uint32Type.AsTypeDefinition());
            var uint64Converter = model.GetPrimitiveValueConverter(uint64Type.AsTypeDefinition());

            Assert.Equal(Type.GetTypeCode(uint16Converter.ConvertToUnderlyingType((UInt16)123).GetType()), TypeCode.Int32);
            Assert.Equal(Type.GetTypeCode(uint32Converter.ConvertToUnderlyingType((UInt32)123).GetType()), TypeCode.UInt32);
            Assert.Equal(Type.GetTypeCode(uint64Converter.ConvertToUnderlyingType((UInt64)123).GetType()), TypeCode.Decimal);

            Assert.Equal(Type.GetTypeCode(uint16Converter.ConvertFromUnderlyingType(123).GetType()), TypeCode.UInt16);
            Assert.Equal(Type.GetTypeCode(uint32Converter.ConvertFromUnderlyingType((Int64)123).GetType()), TypeCode.Int64);
            Assert.Equal(Type.GetTypeCode(uint64Converter.ConvertFromUnderlyingType((Decimal)123).GetType()), TypeCode.UInt64);
        }
예제 #10
0
        public void GetHeaderGoesToInnerMessageAfterConstruction()
        {
            const string headerName  = "CustomHeaderName";
            const string headerValue = "CustomerHeaderValue";

            var simulatedRequestMessage = new InMemoryMessage();

            simulatedRequestMessage.SetHeader(headerName, headerValue);

            var odataRequestMessage = new ODataRequestMessage(simulatedRequestMessage, false, false, -1);

            odataRequestMessage.GetHeader(headerName).Should().Be(headerValue);
        }
예제 #11
0
        public void EncodingShouldRemainInvariantInReader()
        {
            Stream stream = new MemoryStream(Encoding.GetEncoding("iso-8859-1").GetBytes("{\"@odata.context\":\"http://stuff/#Edm.Int32\",\"value\":4}"));
            IODataResponseMessage responseMessage = new InMemoryMessage()
            {
                StatusCode = 200, Stream = stream
            };

            responseMessage.SetHeader("Content-Type", "application/json;odata.metadata=minimal;");
            ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel());

            reader.ReadProperty();
        }
        public void GetAcceptHeaderWithInnerValueGetsInnerValue()
        {
            const string headerName  = "Accept";
            const string headerValue = "json-rox";

            var simulatedRequestMessage = new InMemoryMessage();

            simulatedRequestMessage.SetHeader(headerName, headerValue);

            var odataRequestMessage = new ODataRequestMessage(simulatedRequestMessage, false, false, -1);

            Assert.Equal(headerValue, odataRequestMessage.GetHeader(headerName));
        }
        public void SetHeaderIsNotAllowedWhenReading()
        {
            const string headerName        = "CustomHeaderName";
            const string headerValueBefore = "CustomerHeaderValueBefore";
            const string headerValueAfter  = "CustomerHeaderValueAfter";

            var simulatedRequestMessage = new InMemoryMessage();

            simulatedRequestMessage.SetHeader(headerName, headerValueBefore);

            var    odataRequestMessage = new ODataRequestMessage(simulatedRequestMessage, false, false, -1);
            Action setHeader           = (() => odataRequestMessage.SetHeader(headerName, headerValueAfter));

            setHeader.Throws <ODataException>(Strings.ODataMessage_MustNotModifyMessage);
        }
        public void GetHeaderOnInnerMessagePicksUpSetHeaderFromOuterCallOnWriting()
        {
            const string headerName        = "CustomHeaderName";
            const string headerValueBefore = "CustomerHeaderValueBefore";
            const string headerValueAfter  = "CustomerHeaderValueAfter";

            var simulatedRequestMessage = new InMemoryMessage {
                Method = "GET", Url = new Uri("http://example.com/Customers")
            };

            simulatedRequestMessage.SetHeader(headerName, headerValueBefore);

            var odataRequestMessage = new ODataRequestMessage(simulatedRequestMessage, true, false, -1);

            odataRequestMessage.SetHeader(headerName, headerValueAfter);

            Assert.Equal(headerValueAfter, simulatedRequestMessage.GetHeader(headerName));
        }
        private Stack <ODataItem> ReadPayload(string payload, IEdmModel edmModel, Func <ODataMessageReader, ODataReader> createReader, ODataVersion version)
        {
            var message = new InMemoryMessage()
            {
                Stream = new MemoryStream(Encoding.UTF8.GetBytes(payload))
            };

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

            ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings()
            {
                BaseUri = new Uri(TestBaseUri + "$metadata"),
                EnableMessageStreamDisposal = true,
                Version = version,
            };

            Stack <ODataItem> items = new Stack <ODataItem>();

            using (var msgReader = new ODataMessageReader((IODataResponseMessage)message, readerSettings, edmModel))
            {
                var reader = createReader(msgReader);
                while (reader.Read())
                {
                    switch (reader.State)
                    {
                    case ODataReaderState.ResourceSetEnd:
                    case ODataReaderState.ResourceEnd:
                    case ODataReaderState.NestedResourceInfoEnd:
                    case ODataReaderState.DeltaResourceSetEnd:
                    case ODataReaderState.DeletedResourceEnd:
                        items.Push(reader.Item);
                        break;
                    }
                }

                Assert.Equal(ODataReaderState.Completed, reader.State);
            }

            return(items);
        }
        private string GetWriterOutput(IEdmModel model, Action <ODataMessageWriter> writeAction)
        {
            MemoryStream          outputStream = new MemoryStream();
            IODataResponseMessage message      = new InMemoryMessage()
            {
                Stream = outputStream
            };

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

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

            string output;

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

            return(output);
        }
        public void ValidateWriteMethodGroup()
        {
            // setup model
            var model       = new EdmModel();
            var complexType = new EdmComplexType("NS", "ComplexType");

            complexType.AddStructuralProperty("PrimitiveProperty1", EdmPrimitiveTypeKind.Int64);
            complexType.AddStructuralProperty("PrimitiveProperty2", EdmPrimitiveTypeKind.Int64);
            var entityType = new EdmEntityType("NS", "EntityType", null, false, true);

            entityType.AddKeys(
                entityType.AddStructuralProperty("PrimitiveProperty", EdmPrimitiveTypeKind.Int64));
            var container = new EdmEntityContainer("NS", "Container");
            var entitySet = container.AddEntitySet("EntitySet", entityType);

            model.AddElements(new IEdmSchemaElement[] { complexType, entityType, container });

            // write payload using new API
            string str1;
            {
                // setup
                var stream  = new MemoryStream();
                var message = new InMemoryMessage {
                    Stream = stream
                };
                message.SetHeader("Content-Type", "application/json;odata.metadata=full");
                var settings = new ODataMessageWriterSettings
                {
                    ODataUri = new ODataUri
                    {
                        ServiceRoot = new Uri("http://svc/")
                    },
                };
                var writer = new ODataMessageWriter((IODataResponseMessage)message, settings, model);

                var entitySetWriter = writer.CreateODataResourceSetWriter(entitySet);
                entitySetWriter.Write(new ODataResourceSet(), () => entitySetWriter
                                      .Write(new ODataResource
                {
                    Properties = new[] { new ODataProperty {
                                             Name = "PrimitiveProperty", Value = 1L
                                         } }
                })
                                      .Write(new ODataResource
                {
                    Properties = new[] { new ODataProperty {
                                             Name = "PrimitiveProperty", Value = 2L
                                         } }
                }, () => entitySetWriter
                                             .Write(new ODataNestedResourceInfo {
                    Name = "DynamicNavProperty"
                })
                                             .Write(new ODataNestedResourceInfo
                {
                    Name         = "DynamicCollectionProperty",
                    IsCollection = true
                }, () => entitySetWriter
                                                    .Write(new ODataResourceSet {
                    TypeName = "Collection(NS.ComplexType)"
                })))
                                      );
                str1 = Encoding.UTF8.GetString(stream.ToArray());
            }
            // write payload using old API
            string str2;

            {
                // setup
                var stream  = new MemoryStream();
                var message = new InMemoryMessage {
                    Stream = stream
                };
                message.SetHeader("Content-Type", "application/json;odata.metadata=full");
                var settings = new ODataMessageWriterSettings
                {
                    ODataUri = new ODataUri
                    {
                        ServiceRoot = new Uri("http://svc/")
                    },
                };
                var writer = new ODataMessageWriter((IODataResponseMessage)message, settings, model);

                var entitySetWriter = writer.CreateODataResourceSetWriter(entitySet);
                entitySetWriter.WriteStart(new ODataResourceSet());
                entitySetWriter.WriteStart(new ODataResource
                {
                    Properties = new[] { new ODataProperty {
                                             Name = "PrimitiveProperty", Value = 1L
                                         } }
                });
                entitySetWriter.WriteEnd();
                entitySetWriter.WriteStart(new ODataResource
                {
                    Properties = new[] { new ODataProperty {
                                             Name = "PrimitiveProperty", Value = 2L
                                         } }
                });
                entitySetWriter.WriteStart(new ODataNestedResourceInfo {
                    Name = "DynamicNavProperty"
                });
                entitySetWriter.WriteEnd();
                entitySetWriter.WriteStart(new ODataNestedResourceInfo
                {
                    Name         = "DynamicCollectionProperty",
                    IsCollection = true
                });
                entitySetWriter.WriteStart(new ODataResourceSet {
                    TypeName = "Collection(NS.ComplexType)"
                });
                entitySetWriter.WriteEnd();
                entitySetWriter.WriteEnd();
                entitySetWriter.WriteEnd();
                entitySetWriter.WriteEnd();
                str2 = Encoding.UTF8.GetString(stream.ToArray());
            }
            Assert.Equal(str1, str2);
        }