当前位置: 首页>>代码示例>>C#>>正文


C# ODataMessageReader类代码示例

本文整理汇总了C#中ODataMessageReader的典型用法代码示例。如果您正苦于以下问题:C# ODataMessageReader类的具体用法?C# ODataMessageReader怎么用?C# ODataMessageReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ODataMessageReader类属于命名空间,在下文中一共展示了ODataMessageReader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ReadCompletedAsyncResponse

        public void ReadCompletedAsyncResponse()
        {
            string payload = "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}";

            var asyncReader = this.CreateAsyncReader(payload);
            var asyncResponse = asyncReader.CreateResponseMessage();

            Assert.Equal(200, asyncResponse.StatusCode);
            Assert.Equal("application/json", asyncResponse.GetHeader("Content-Type"));
            Assert.Equal("4.0", asyncResponse.GetHeader("OData-Version"));

            using (var innerMessageReader = new ODataMessageReader(asyncResponse, new ODataMessageReaderSettings(), userModel))
            {
                var reader = innerMessageReader.CreateODataEntryReader();

                while (reader.Read())
                {
                    if (reader.State == ODataReaderState.EntryEnd)
                    {
                        ODataEntry entry = reader.Item as ODataEntry;
                        Assert.Equal(1, entry.Properties.Single(p => p.Name == "Id").Value);
                    }
                }
            }
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:25,代码来源:ODataAsynchronousReaderTests.cs

示例2: Can_deserialize_payload_with_complex_parameters

        public void Can_deserialize_payload_with_complex_parameters()
        {
            string actionName = "Complex";
            string body = @"{ ""Quantity"": 1 , ""Address"": { ""StreetAddress"":""1 Microsoft Way"", ""City"": ""Redmond"", ""State"": ""WA"", ""ZipCode"": 98052 } }";

            ODataMessageWrapper message = new ODataMessageWrapper(GetStringAsStream(body));
            message.SetHeader("Content-Type", "application/json;odata=verbose");
            IEdmModel model = GetModel();
            ODataMessageReader reader = new ODataMessageReader(message as IODataRequestMessage, new ODataMessageReaderSettings(), model);

            ODataActionPayloadDeserializer deserializer = new ODataActionPayloadDeserializer(typeof(ODataActionParameters), new DefaultODataDeserializerProvider(model));
            string url = "http://server/service/Customers(10)/" + actionName;
            HttpRequestMessage request = GetPostRequest(url);
            ODataDeserializerContext context = new ODataDeserializerContext { Request = request, Model = model };
            ODataActionParameters payload = deserializer.Read(reader, context) as ODataActionParameters;

            Assert.NotNull(payload);
            Assert.Same(model.EntityContainers().Single().FunctionImports().SingleOrDefault(f => f.Name == "Complex"), payload.GetFunctionImport(context));
            Assert.True(payload.ContainsKey("Quantity"));
            Assert.Equal(1, payload["Quantity"]);
            Assert.True(payload.ContainsKey("Address"));
            MyAddress address = payload["Address"] as MyAddress;
            Assert.NotNull(address);
            Assert.Equal("1 Microsoft Way", address.StreetAddress);
            Assert.Equal("Redmond", address.City);
            Assert.Equal("WA", address.State);
            Assert.Equal(98052, address.ZipCode);
        }
开发者ID:Swethach,项目名称:aspnetwebstack,代码行数:28,代码来源:ODataActionPayloadDeserializerTest.cs

示例3: Read

        /// <inheritdoc />
        public override object Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext readContext)
        {
            if (messageReader == null)
            {
                throw Error.ArgumentNull("messageReader");
            }

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

            IEdmNavigationProperty navigationProperty = GetNavigationProperty(readContext.Path);

            if (navigationProperty == null)
            {
                throw new SerializationException(SRResources.NavigationPropertyMissingDuringDeserialization);
            }

            ODataEntityReferenceLink entityReferenceLink = messageReader.ReadEntityReferenceLink(navigationProperty);

            if (entityReferenceLink != null)
            {
                return ResolveContentId(entityReferenceLink.Url, readContext);
            }

            return null;
        }
开发者ID:quentez,项目名称:aspnetwebstack,代码行数:29,代码来源:ODataEntityReferenceLinkDeserializer.cs

示例4: ProcessUpdateEntityReference

        private void ProcessUpdateEntityReference(IODataRequestMessage requestMessage, IODataResponseMessage responseMessage, ODataPath odataPath)
        {
            // This is for change the reference in single-valued navigation property
            // PUT ~/Person(0)/Parent/$ref
            // {
            //     "@odata.context": "http://host/service/$metadata#$ref",
            //     "@odata.id": "Orders(10643)"
            // }

            if (this.HttpMethod == HttpMethod.PATCH)
            {
                throw Utility.BuildException(HttpStatusCode.MethodNotAllowed, "PATCH on a reference link is not supported.", null);
            }

            // Get the parent first
            var level = this.QueryContext.QueryPath.Count - 2;
            var parent = this.QueryContext.ResolveQuery(this.DataSource, level);

            var navigationPropertyName = ((NavigationPropertyLinkSegment)odataPath.LastSegment).NavigationProperty.Name;

            using (var messageReader = new ODataMessageReader(requestMessage, this.GetReaderSettings(), this.DataSource.Model))
            {
                var referenceLink = messageReader.ReadEntityReferenceLink();
                var queryContext = new QueryContext(this.ServiceRootUri, referenceLink.Url, this.DataSource.Model);
                var target = queryContext.ResolveQuery(this.DataSource);

                this.DataSource.UpdateProvider.UpdateLink(parent, navigationPropertyName, target);
                this.DataSource.UpdateProvider.SaveChanges();
            }

            ResponseWriter.WriteEmptyResponse(responseMessage);
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:32,代码来源:UpdateHandler.cs

示例5: ReadFromMessageReader

 protected override void ReadFromMessageReader(ODataMessageReader reader, IEdmTypeReference expectedType)
 {
     ODataProperty collectionProperty = reader.ReadProperty(expectedType);
     Type type = Nullable.GetUnderlyingType(base.ExpectedType) ?? base.ExpectedType;
     object obj2 = collectionProperty.Value;
     if (expectedType.IsCollection())
     {
         object obj3;
         Type collectionItemType = type;
         Type implementationType = ClientTypeUtil.GetImplementationType(type, typeof(ICollection<>));
         if (implementationType != null)
         {
             collectionItemType = implementationType.GetGenericArguments()[0];
             obj3 = ODataMaterializer.CreateCollectionInstance(collectionProperty, type, base.ResponseInfo);
         }
         else
         {
             implementationType = typeof(ICollection<>).MakeGenericType(new Type[] { collectionItemType });
             obj3 = ODataMaterializer.CreateCollectionInstance(collectionProperty, implementationType, base.ResponseInfo);
         }
         ODataMaterializer.ApplyCollectionDataValues(collectionProperty, base.ResponseInfo.IgnoreMissingProperties, base.ResponseInfo, obj3, collectionItemType, ODataMaterializer.GetAddToCollectionDelegate(implementationType));
         this.currentValue = obj3;
     }
     else if (expectedType.IsComplex())
     {
         ODataComplexValue complexValue = obj2 as ODataComplexValue;
         ODataMaterializer.MaterializeComplexTypeProperty(type, complexValue, base.ResponseInfo.IgnoreMissingProperties, base.ResponseInfo);
         this.currentValue = complexValue.GetMaterializedValue();
     }
     else
     {
         ODataMaterializer.MaterializePrimitiveDataValue(base.ExpectedType, collectionProperty);
         this.currentValue = collectionProperty.GetMaterializedValue();
     }
 }
开发者ID:nickchal,项目名称:pash,代码行数:35,代码来源:ODataPropertyMaterializer.cs

示例6: ModelBuilderTest

        public async Task ModelBuilderTest()
        {
            string requestUri = string.Format("{0}/odata/$metadata", this.BaseAddress);

            HttpResponseMessage response = await this.Client.GetAsync(requestUri);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var stream = await response.Content.ReadAsStreamAsync();

            IODataResponseMessage message = new ODataMessageWrapper(stream, response.Content.Headers);
            var reader = new ODataMessageReader(message);
            var edmModel = reader.ReadMetadataDocument();

            var container = edmModel.EntityContainer;
            Assert.Equal("Container", container.Name);

            var employeeType = edmModel.SchemaElements.Single(e => e.Name == "Employee") as IEdmEntityType;
            employeeType.Properties().All(p => this.IsCamelCase(p.Name));

            var managerType = edmModel.SchemaElements.Single(e => e.Name == "Manager") as IEdmEntityType;
            Assert.Equal(7, managerType.Properties().Count());
            managerType.Properties().All(p => this.IsCamelCase(p.Name));

            var addressType = edmModel.SchemaElements.Single(e => e.Name == "Address") as IEdmComplexType;
            addressType.Properties().All(p => this.IsCamelCase(p.Name));
        }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:25,代码来源:LowerCamelCaseTest.cs

示例7: ReadJsonLight

        public void ReadJsonLight()
        {
            // Arrange
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage requestMessage = new MockODataRequestMessage();
            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings();
            writerSettings.SetContentType(ODataFormat.Json);
            IEdmModel model = CreateModel();
            ODataMessageWriter messageWriter = new ODataMessageWriter(requestMessage, writerSettings, model);
            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink { Url = new Uri("http://localhost/samplelink") });
            ODataMessageReader messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage),
                new ODataMessageReaderSettings(), model);

            IEdmNavigationProperty navigationProperty = GetNavigationProperty(model);

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

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

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
开发者ID:nicholaspei,项目名称:aspnetwebstack,代码行数:28,代码来源:ODataEntityReferenceLinkDeserializerTests.cs

示例8: Can_deserialize_payload_with_primitive_parameters

        public void Can_deserialize_payload_with_primitive_parameters()
        {
            string actionName = "Primitive";
            int quantity = 1;
            string productCode = "PCode";
            string body = "{" + string.Format(@" ""Quantity"": {0} , ""ProductCode"": ""{1}"" ", quantity, productCode) + "}";

            ODataMessageWrapper message = new ODataMessageWrapper(GetStringAsStream(body));
            message.SetHeader("Content-Type", "application/json;odata=verbose");

            IEdmModel model = GetModel();
            ODataMessageReader reader = new ODataMessageReader(message as IODataRequestMessage, new ODataMessageReaderSettings(), model);
            ODataActionPayloadDeserializer deserializer = new ODataActionPayloadDeserializer(new DefaultODataDeserializerProvider());
            ODataPath path = CreatePath(model, actionName);
            ODataDeserializerContext context = new ODataDeserializerContext { Path = path, Model = model };
            ODataActionParameters payload = deserializer.Read(reader, context) as ODataActionParameters;

            Assert.NotNull(payload);
            Assert.Same(
                model.EntityContainers().Single().FunctionImports().SingleOrDefault(f => f.Name == "Primitive"),
                ODataActionPayloadDeserializer.GetFunctionImport(context));
            Assert.True(payload.ContainsKey("Quantity"));
            Assert.Equal(quantity, payload["Quantity"]);
            Assert.True(payload.ContainsKey("ProductCode"));
            Assert.Equal(productCode, payload["ProductCode"]);
        }
开发者ID:brianly,项目名称:aspnetwebstack,代码行数:26,代码来源:ODataActionPayloadDeserializerTest.cs

示例9: QueryEntries

        /// <summary>
        /// Specifically use to query single entry or multi entries(query with $expand)
        /// </summary>
        /// <param name="requestUri"></param>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public List<ODataEntry> QueryEntries(string requestUri, string mimeType)
        {
            List<ODataEntry> entries = new List<ODataEntry>();

            ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = baseUri };
            var requestMessage = new HttpWebRequestMessage(new Uri(baseUri.AbsoluteUri + requestUri, UriKind.Absolute));
            requestMessage.SetHeader("Accept", mimeType);
            var responseMessage = requestMessage.GetResponse();
            Assert.AreEqual(200, responseMessage.StatusCode);

            if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
            {
                using (var messageReader = new ODataMessageReader(responseMessage, readerSettings, model))
                {
                    var reader = messageReader.CreateODataEntryReader();

                    while (reader.Read())
                    {
                        if (reader.State == ODataReaderState.EntryEnd)
                        {
                            entries.Add(reader.Item as ODataEntry);
                        }
                    }
                    Assert.AreEqual(ODataReaderState.Completed, reader.State);
                }
            }
            return entries;
        }
开发者ID:rossjempson,项目名称:odata.net,代码行数:34,代码来源:QueryOptionTestsHelper.cs

示例10: ReadValueOfTypeDefinitionShouldWork

 public void ReadValueOfTypeDefinitionShouldWork()
 {
     Stream stream = new MemoryStream(Encoding.Default.GetBytes("123"));
     IODataResponseMessage responseMessage = new InMemoryMessage() { StatusCode = 200, Stream = stream };
     ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel());
     reader.ReadValue(new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "Length", EdmPrimitiveTypeKind.Int32), true)).Should().Be(123);
 }
开发者ID:rossjempson,项目名称:odata.net,代码行数:7,代码来源:ODataMessageReaderTests.cs

示例11: ReadValueOfAbbreviativeDateShouldWork

 public void ReadValueOfAbbreviativeDateShouldWork()
 {
     Stream stream = new MemoryStream(Encoding.Default.GetBytes("2014-1-3"));
     IODataResponseMessage responseMessage = new InMemoryMessage() { StatusCode = 200, Stream = stream };
     ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings(), new EdmModel());
     reader.ReadValue(new EdmTypeDefinitionReference(new EdmTypeDefinition("NS", "DateValue", EdmPrimitiveTypeKind.Date), true)).Should().Be(new Date(2014, 1, 3));
 }
开发者ID:rossjempson,项目名称:odata.net,代码行数:7,代码来源:ODataMessageReaderTests.cs

示例12: EntryMetadataUrlRoundTrip

        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>();
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:32,代码来源:MetadataUriRoundTripTests.cs

示例13: ModelBuilderTest

        public async Task ModelBuilderTest(string modelMode)
        {
            string requestUri = string.Format("{0}/{1}/$metadata", this.BaseAddress, modelMode);

            HttpResponseMessage response = await this.Client.GetAsync(requestUri);
            var stream = await response.Content.ReadAsStreamAsync();
            IODataResponseMessage message = new ODataMessageWrapper(stream, response.Content.Headers);
            var reader = new ODataMessageReader(message);
            var edmModel = reader.ReadMetadataDocument();

            var fileType = edmModel.SchemaElements.OfType<IEdmEntityType>().Single(et => et.Name == "File");
            Assert.Equal(5, fileType.Properties().Count());

            var createdDateProperty = fileType.DeclaredProperties.Single(p => p.Name == "CreatedDate");
            Assert.Equal(EdmTypeKind.Primitive, createdDateProperty.Type.TypeKind());
            Assert.Equal("Edm.DateTimeOffset", createdDateProperty.Type.Definition.FullTypeName());
            Assert.False(createdDateProperty.Type.IsNullable);

            var deleteDateProperty = fileType.DeclaredProperties.Single(p => p.Name == "DeleteDate");
            Assert.Equal(EdmTypeKind.Primitive, deleteDateProperty.Type.TypeKind());
            Assert.Equal("Edm.DateTimeOffset", deleteDateProperty.Type.Definition.FullTypeName());
            Assert.True(deleteDateProperty.Type.IsNullable);

            var modifiedDates = fileType.DeclaredProperties.Single(p => p.Name == "ModifiedDates");
            Assert.Equal(EdmTypeKind.Collection, modifiedDates.Type.TypeKind());
            Assert.Equal("Collection(Edm.DateTimeOffset)", modifiedDates.Type.Definition.FullTypeName());
            Assert.False(modifiedDates.Type.IsNullable);
        }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:28,代码来源:DateTimeTest.cs

示例14: CreateMessageReaderShouldSetAnnotationFilterWhenODataAnnotationIsSetOnPreferenceAppliedHeader

 public void CreateMessageReaderShouldSetAnnotationFilterWhenODataAnnotationIsSetOnPreferenceAppliedHeader()
 {
     IODataResponseMessage responseMessage = new InMemoryMessage();
     responseMessage.PreferenceAppliedHeader().AnnotationFilter = "*";
     ODataMessageReader reader = new ODataMessageReader(responseMessage, new ODataMessageReaderSettings());
     reader.Settings.ShouldIncludeAnnotation.Should().NotBeNull();
 }
开发者ID:rossjempson,项目名称:odata.net,代码行数:7,代码来源:ODataMessageReaderTests.cs

示例15: Read

 /// <inheritdoc />
 public override object Read(
     ODataMessageReader messageReader,
     Type type,
     ODataDeserializerContext readContext)
 {
     return enumDeserializer.Read(messageReader, type, readContext);
 }
开发者ID:adestis-mh,项目名称:RESTier,代码行数:8,代码来源:RestierEnumDeserializer.cs


注:本文中的ODataMessageReader类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。