コード例 #1
0
        private void CreateMessageReader(string payloadBody, bool forEntry, bool isResponse, bool enableReadingODataAnnotationWithoutPrefix)
        {
            string       payloadPrefix = @"{
  ""@odata.context"":""http://example.com/$metadata#EntitySet" + (forEntry ? "/$entity" : string.Empty) + "\",";
            const string payloadSuffix = "}";
            string       payload       = payloadPrefix + payloadBody + payloadSuffix;

            var container = ContainerBuilderHelper.BuildContainer(null);

            container.GetRequiredService <ODataSimplifiedOptions>().EnableReadingODataAnnotationWithoutPrefix = enableReadingODataAnnotationWithoutPrefix;

            var message = new InMemoryMessage()
            {
                Container = container
            };

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

            if (isResponse)
            {
                this.messageReader = new ODataMessageReader((IODataResponseMessage)message, messageSettings, this.model);
            }
            else
            {
                this.messageReader = new ODataMessageReader((IODataRequestMessage)message, messageSettings, this.model);
            }
        }
コード例 #2
0
        private ODataResource ReadSingleton(string payload, bool odataSimplified = false)
        {
            var settings = new ODataMessageReaderSettings();

            var messageInfo = new ODataMessageInfo
            {
                IsResponse = true,
                MediaType  = new ODataMediaType("application", "json"),
                IsAsync    = false,
                Model      = this.userModel,
                Container  = ContainerBuilderHelper.BuildContainer(null)
            };

            using (var inputContext = new ODataJsonLightInputContext(
                       new StringReader(payload), messageInfo, settings))
            {
                inputContext.Container.GetRequiredService <ODataSimplifiedOptions>()
                .EnableReadingODataAnnotationWithoutPrefix = odataSimplified;
                var jsonLightReader = new ODataJsonLightReader(inputContext, singleton, webType, /*readingFeed*/ false);
                while (jsonLightReader.Read())
                {
                    if (jsonLightReader.State == ODataReaderState.ResourceEnd)
                    {
                        ODataResource entry = jsonLightReader.Item as ODataResource;
                        return(entry);
                    }
                }
            }
            return(null);
        }
コード例 #3
0
        public void ParseDynamicPathSegmentFunc_ReturnDynamicPathSegment_FollowedByDynamicPathSegmentsAndProp()
        {
            var container = ContainerBuilderHelper.BuildContainer(builder => builder.AddService <UriPathParser, MultipleSegmentUriPathParser>(ServiceLifetime.Scoped));
            Uri fullUri   = new Uri("https://serviceRoot/drives('b!3195njZm9ECS0rQfW5QyZ0iJh-jL7uZGn60CTehSbIwT3VAIax8sRKiyg_aD0HNV')/root:/OData/Doc/OData%20Client%20for%20.NET.pptx:/folder/childCount");
            var uriParser = new ODataUriParser(oneDriveModel, ServiceRoot, fullUri, container);

            var childCountProp = folderType.FindProperty("childCount");

            uriParser.ParseDynamicPathSegmentFunc = (previous, identifier, parenthesisExpression) =>
            {
                switch (identifier)
                {
                case "root":
                case "OData":
                case "Doc":
                case "OData Client for .NET.pptx":
                    return(new List <ODataPathSegment> {
                        new DynamicPathSegment(identifier, itemType, containedItemsNav, true)
                    });

                default:
                    throw new Exception("Not supported Type");
                }
            };
            var path = uriParser.ParsePath();

            path.ElementAt(2).ShouldBeDynamicPathSegment("root");
            path.ElementAt(3).ShouldBeDynamicPathSegment("OData");
            path.ElementAt(4).ShouldBeDynamicPathSegment("Doc");
            path.ElementAt(5).ShouldBeDynamicPathSegment("OData Client for .NET.pptx");
            path.LastSegment.ShouldBePropertySegment(childCountProp);
        }
コード例 #4
0
        private IEnumerable <Tuple <ODataItem, ODataDeltaReaderState, ODataReaderState> > ReadItem(string payload, IEdmModel model = null, IEdmNavigationSource navigationSource = null, IEdmEntityType entityType = null, bool enableReadingODataAnnotationWithoutPrefix = false)
        {
            var settings = new ODataMessageReaderSettings
            {
                ShouldIncludeAnnotation = s => true,
            };

            var messageInfo = new ODataMessageInfo
            {
                IsResponse = true,
                MediaType  = new ODataMediaType("application", "json"),
                IsAsync    = false,
                Model      = model ?? new EdmModel(),
                Container  = ContainerBuilderHelper.BuildContainer(null)
            };

            using (var inputContext = new ODataJsonLightInputContext(
                       new StringReader(payload), messageInfo, settings))
            {
                inputContext.Container.GetRequiredService <ODataSimplifiedOptions>()
                .EnableReadingODataAnnotationWithoutPrefix = enableReadingODataAnnotationWithoutPrefix;
                var jsonLightReader = new ODataJsonLightDeltaReader(inputContext, navigationSource, entityType);
                while (jsonLightReader.Read())
                {
                    yield return(new Tuple <ODataItem, ODataDeltaReaderState, ODataReaderState>(jsonLightReader.Item, jsonLightReader.State, jsonLightReader.SubState));
                }
            }
        }
コード例 #5
0
        public void ParseDynamicPathSegmentFunc_ReturnOperationSegment_WithCollectionReturnType_WithCount()
        {
            var container = ContainerBuilderHelper.BuildContainer(builder => builder.AddService <UriPathParser, SingleSegmentUriPathParser>(ServiceLifetime.Scoped));
            Uri fullUri   = new Uri("https://serviceRoot/drives('b!3195njZm9ECS0rQfW5QyZ0iJh-jL7uZGn60CTehSbIwT3VAIax8sRKiyg_aD0HNV')/recent/$count");
            var uriParser = new ODataUriParser(oneDriveModel, ServiceRoot, fullUri, container);

            var operation = oneDriveModel.SchemaElements.OfType <IEdmOperation>().FirstOrDefault(o => o.Name == "recent");

            uriParser.ParseDynamicPathSegmentFunc = (previous, identifier, parenthesisExpression) =>
            {
                switch (identifier)
                {
                case "recent":
                    var operationSegment = new OperationSegment(operation, containedItemsNav as IEdmEntitySetBase)
                    {
                        Identifier = identifier
                    };
                    return(new List <ODataPathSegment>
                    {
                        operationSegment
                    });

                default:
                    throw new Exception("Not supported Type");
                }
            };

            var path = uriParser.ParsePath();

            path.ElementAt(2).ShouldBeOperationSegment(operation);
            path.LastSegment.ShouldBeCountSegment();
        }
コード例 #6
0
        static ODataAvroScenarioTests()
        {
            var type = new EdmEntityType("Microsoft.Test.OData.PluggableFormat.Avro.Test", "Product");

            type.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false);
            type.AddStructuralProperty("Weight", EdmPrimitiveTypeKind.Single, false);

            EntryType = type;

            var cpx = new EdmComplexType("Microsoft.Test.OData.PluggableFormat.Avro.Test", "Address");

            cpx.AddStructuralProperty("Road", EdmPrimitiveTypeKind.String, false);
            cpx.AddStructuralProperty("ZipCode", EdmPrimitiveTypeKind.String, false);
            ComplexType = cpx;

            var action = new EdmAction("Microsoft.Test.OData.PluggableFormat.Avro.Test", "AddProduct", null);

            action.AddParameter("Product", new EdmEntityTypeReference(EntryType, false));
            action.AddParameter("Location", new EdmComplexTypeReference(ComplexType, false));
            AddProduct = action;

            action = new EdmAction("Microsoft.Test.OData.PluggableFormat.Avro.Test", "GetMaxId", EdmCoreModel.Instance.GetInt32(false));
            action.AddParameter("Products", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(EntryType, false))));
            GetMaxId = action;

            container = ContainerBuilderHelper.BuildContainer(builder =>
                                                              builder.AddService <ODataMediaTypeResolver, AvroMediaTypeResolver>(ServiceLifetime.Singleton));
        }
コード例 #7
0
        private ODataJsonLightOutputContext CreateJsonLightOutputContext(MemoryStream stream, IEdmModel model, IJsonWriter jsonWriter, ODataMessageWriterSettings settings = null)
        {
            if (settings == null)
            {
                settings = new ODataMessageWriterSettings {
                    Version = ODataVersion.V4
                };
                settings.SetServiceDocumentUri(new Uri("http://example.com/"));
                settings.ShouldIncludeAnnotation = ODataUtils.CreateAnnotationFilter("*");
            }

            var messageInfo = new ODataMessageInfo
            {
                MessageStream = new NonDisposingStream(stream),
                MediaType     = new ODataMediaType("application", "json"),
                Encoding      = Encoding.UTF8,
                IsResponse    = true,
                IsAsync       = false,
                Model         = model,
                Container     =
                    ContainerBuilderHelper.BuildContainer(
                        builder =>
                        builder.AddService <IJsonWriterFactory>(ServiceLifetime.Singleton, sp => new MockJsonWriterFactory(jsonWriter))),
            };

            return(new ODataJsonLightOutputContext(messageInfo, settings));
        }
コード例 #8
0
        private ODataUriParser ParseDynamicPathSegmentFunc_ReturnDynamicPathSegment_WithCollectionReturnType(Uri fullUri, out ODataPath odataPath, ODataUrlKeyDelimiter uriConventions = null)
        {
            var container = ContainerBuilderHelper.BuildContainer(builder => builder.AddService <UriPathParser, SingleSegmentUriPathParser>(ServiceLifetime.Scoped));
            var uriParser = new ODataUriParser(oneDriveModel, ServiceRoot, fullUri, container);

            if (uriConventions != null)
            {
                uriParser.UrlKeyDelimiter = uriConventions;
            }

            var operation = oneDriveModel.SchemaElements.OfType <IEdmOperation>().FirstOrDefault(o => o.Name == "recent");

            uriParser.ParseDynamicPathSegmentFunc = (previous, identifier, parenthesisExpression) =>
            {
                var dynamicPathSeg = new DynamicPathSegment(identifier, operation.ReturnType.Definition, containedItemsNav, false);

                var segments = new List <ODataPathSegment>
                {
                    dynamicPathSeg
                };

                if (parenthesisExpression != null)
                {
                    segments.Add(new KeySegment(dynamicPathSeg, new Dictionary <string, object>()
                    {
                        { "id", parenthesisExpression.Trim('\'') }
                    }, itemType, null));
                }

                return(segments);
            };

            odataPath = uriParser.ParsePath();
            return(uriParser);
        }
        private string SerializeEntryInFullMetadataJson(
            bool useKeyAsSegment,
            IEdmModel edmModel,
            IEdmEntityType entityType = null,
            IEdmEntitySet entitySet   = null)
        {
            var settings = new ODataMessageWriterSettings {
            };

            settings.SetServiceDocumentUri(new Uri("http://example.com/"));
            var outputStream = new MemoryStream();
            var container    = ContainerBuilderHelper.BuildContainer(null);

            container.GetRequiredService <ODataSimplifiedOptions>().EnableWritingKeyAsSegment = useKeyAsSegment;
            var responseMessage = new InMemoryMessage {
                Stream = outputStream, Container = container
            };

            responseMessage.SetHeader("Content-Type", "application/json;odata.metadata=full");
            string output;

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

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

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

                    entry.SetSerializationInfo(new ODataResourceSerializationInfo
                    {
                        NavigationSourceEntityTypeName = "Namespace.Person",
                        NavigationSourceName           = "People",
                        ExpectedTypeName     = "Namespace.Person",
                        NavigationSourceKind = EdmNavigationSourceKind.EntitySet
                    });
                }

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

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

            return(output);
        }
コード例 #10
0
        static ODataVCardScenarioTests()
        {
            VCardModel = TestHelper.GetModel(ResModel);
            VCardType  = (IEdmComplexType)VCardModel.FindType("VCard21.VCard");

            container = ContainerBuilderHelper.BuildContainer(builder =>
                                                              builder.AddService <ODataMediaTypeResolver, VCardMediaTypeResolver>(ServiceLifetime.Singleton));
        }
        private void WriteAnnotationsAndValidatePayload(Action <ODataWriter> action, IEdmNavigationSource navigationSource, ODataFormat format, string expectedPayload, bool request, bool createFeedWriter, bool enableWritingODataAnnotationWithoutPrefix = false, IEdmStructuredType resourceType = null)
        {
            var writerSettings = new ODataMessageWriterSettings {
                EnableMessageStreamDisposal = false
            };

            writerSettings.SetContentType(format);
            writerSettings.SetServiceDocumentUri(new Uri("http://www.example.com/"));

            var container = ContainerBuilderHelper.BuildContainer(null);

            container.GetRequiredService <ODataSimplifiedOptions>().SetOmitODataPrefix(
                enableWritingODataAnnotationWithoutPrefix);

            MemoryStream stream = new MemoryStream();

            if (request)
            {
                IODataRequestMessage requestMessageToWrite = new InMemoryMessage
                {
                    Method    = "GET",
                    Stream    = stream,
                    Container = container
                };
                using (var messageWriter = new ODataMessageWriter(requestMessageToWrite, writerSettings, Model))
                {
                    ODataWriter odataWriter = (createFeedWriter && !(navigationSource is EdmSingleton))
                        ? messageWriter.CreateODataResourceSetWriter(navigationSource as EdmEntitySet, EntityType)
                        : messageWriter.CreateODataResourceWriter(navigationSource, resourceType ?? EntityType);
                    action(odataWriter);
                }
            }
            else
            {
                IODataResponseMessage responseMessageToWrite = new InMemoryMessage
                {
                    StatusCode = 200,
                    Stream     = stream,
                    Container  = container
                };
                responseMessageToWrite.PreferenceAppliedHeader().AnnotationFilter = "*";
                using (var messageWriter = new ODataMessageWriter(responseMessageToWrite, writerSettings, Model))
                {
                    ODataWriter odataWriter = (createFeedWriter && !(navigationSource is EdmSingleton))
                        ? messageWriter.CreateODataResourceSetWriter(navigationSource as EdmEntitySet, EntityType)
                        : messageWriter.CreateODataResourceWriter(navigationSource, resourceType ?? EntityType);
                    action(odataWriter);
                }
            }

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

            Assert.Equal(expectedPayload, payload);
        }
コード例 #12
0
        public void CustomizedUriPathParserTest()
        {
            var container = ContainerBuilderHelper.BuildContainer(builder => builder.AddService <UriPathParser, MultipleSegmentUriPathParser>(ServiceLifetime.Scoped));
            Uri fullUri   = new Uri("https://serviceRoot/drives('b!3195njZm9ECS0rQfW5QyZ0iJh-jL7uZGn60CTehSbIwT3VAIax8sRKiyg_aD0HNV'):/items('01VL3Q7L36JOJUAPXGDNAZ4FVIGCTMLL46')/folder/childCount");
            var uriParser = new ODataUriParser(oneDriveModel, ServiceRoot, fullUri, container);

            var path = uriParser.ParsePath();

            var childCountProp = folderType.FindProperty("childCount");

            path.LastSegment.ShouldBePropertySegment(childCountProp);
        }
コード例 #13
0
        public void WritingDateTimeOffsetWithCustomFormat()
        {
            var df = EdmCoreModel.Instance.GetDateTimeOffset(false);

            var result = this.SetupSerializerAndRunTest(serializer =>
            {
                var value = new DateTimeOffset(2012, 4, 13, 2, 43, 10, TimeSpan.FromHours(8));
                serializer.WritePrimitiveValue(value, df);
            },
                                                        ContainerBuilderHelper.BuildContainer(
                                                            builder => builder.AddService <ODataPayloadValueConverter, DateTimeOffsetCustomFormatPrimitivePayloadValueConverter>(ServiceLifetime.Singleton)));

            Assert.Equal("\"Thu, 12 Apr 2012 18:43:10 GMT\"", result);
        }
コード例 #14
0
        private static void RunReaderTest(Action <IContainerBuilder> action, string messageContent)
        {
            var model      = BuildModel();
            var entitySet  = model.FindDeclaredEntitySet("People");
            var entityType = model.GetEntityType("NS.Person");
            var container  = ContainerBuilderHelper.BuildContainer(action);

            container.GetRequiredService <ODataSimplifiedOptions>().EnableReadingODataAnnotationWithoutPrefix = true;
            var resource     = GetReadedResource(messageContent, model, entitySet, entityType, container);
            var propertyList = resource.Properties.ToList();

            Assert.Equal("PersonId", propertyList[0].Name);
            Assert.Equal(999, propertyList[0].Value);
            Assert.Equal("Name", propertyList[1].Name);
            Assert.Equal("Jack", propertyList[1].Value);
        }
コード例 #15
0
        public async Task WriteSpatialCollectionPropertyForInjectedJsonWriterFactoryAsync()
        {
            var messageInfo = CreateMessageInfo(this.model, /*synchronous*/ true, /*writingResponse*/ true);

            messageInfo.Container = ContainerBuilderHelper.BuildContainer(builder =>
            {
                builder.AddService <IJsonWriterFactory>(ServiceLifetime.Singleton, _ => new DefaultJsonWriterFactory());
                builder.AddService <IJsonWriterFactoryAsync>(ServiceLifetime.Singleton, _ => new DefaultJsonWriterFactory());
            });

            var jsonLightOutputContext = new ODataJsonLightOutputContext(messageInfo, this.messageWriterSettings);
            var geographyCollection    = new object[]
            {
                GeographyFactory.Point(33.1, -110.0).Build(),
                GeographyFactory.LineString(33.1, -110.0).LineTo(35.97, -110).Build(),
                GeographyFactory.MultiPoint().Point(10.2, 11.2).Point(11.9, 11.6).Build()
            };

            var geographyCollectionProperty = new ODataProperty
            {
                Name  = "GeographyCollectionProperty",
                Value = new ODataCollectionValue
                {
                    TypeName = "Collection(Edm.Geography)",
                    Items    = geographyCollection
                }
            };

            await jsonLightOutputContext.WritePropertyAsync(geographyCollectionProperty);

            await jsonLightOutputContext.FlushAsync();

            this.stream.Position = 0;
            var result = await new StreamReader(this.stream).ReadToEndAsync();

            Assert.Equal(
                "{\"@odata.context\":\"http://tempuri.org/$metadata#Collection(Edm.Geography)\"," +
                "\"value\":[" +
                "{\"type\":\"Point\",\"coordinates\":[-110.0,33.1],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:4326\"}}}," +
                "{\"type\":\"LineString\",\"coordinates\":[[-110.0,33.1],[-110.0,35.97]],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:4326\"}}}," +
                "{\"type\":\"MultiPoint\",\"coordinates\":[[11.2,10.2],[11.6,11.9]],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:4326\"}}}" +
                "]}",
                result);
        }
コード例 #16
0
        private static Dictionary <string, IEnumerable <ODataProperty> > RunComplexReaderTest(Action <IContainerBuilder> action, string messageContent)
        {
            var model      = GetModel();
            var entitySet  = model.FindDeclaredEntitySet("People");
            var entityType = model.GetEntityType("DefaultNs.Person");
            var container  = ContainerBuilderHelper.BuildContainer(action);

            container.GetRequiredService <ODataSimplifiedOptions>().EnableReadingODataAnnotationWithoutPrefix = true;
            var resource = GetReadedResourceWithNestedInfo(messageContent, model, entitySet, entityType, container);

            var resourceDict = new Dictionary <string, IEnumerable <ODataProperty> >();

            foreach (var res in resource)
            {
                resourceDict.Add(res.TypeName, res.Properties);
            }

            return(resourceDict);
        }
コード例 #17
0
        public void BinaryPayloadAsStringRoundtripJsonLightTest()
        {
            var values = new byte[][]
            {
                new byte[0],
                new byte[] { 0 },
                new byte[] { 42, Byte.MinValue, Byte.MaxValue },
            };

            var expectedValues = new string[]
            {
                Convert.ToBase64String(values[0]),
                Convert.ToBase64String(values[1]),
                Convert.ToBase64String(values[2])
            };

            this.container = ContainerBuilderHelper.BuildContainer(
                builder => builder.AddService <ODataPayloadValueConverter, BinaryFieldAsStringPrimitivePayloadValueConverter>(ServiceLifetime.Singleton));

            this.VerifyPrimitiveValuesRoundtripWithTypeInformationAndWithExpectedValues(values, "Edm.Binary", expectedValues);
            this.VerifyPrimitiveValuesRoundtripWithTypeInformation(expectedValues, "Edm.Binary");
        }
コード例 #18
0
        private static void RunWriterTest(Action <IContainerBuilder> action, string expectedOutput)
        {
            var resource = new ODataResource
            {
                Properties = new[]
                {
                    new ODataProperty {
                        Name = "PersonId", Value = 999
                    },
                    new ODataProperty {
                        Name = "Name", Value = "Jack"
                    }
                }
            };
            var model      = BuildModel();
            var entitySet  = model.FindDeclaredEntitySet("People");
            var entityType = model.GetEntityType("NS.Person");
            var container  = ContainerBuilderHelper.BuildContainer(action);
            var output     = GetWriterOutput(resource, model, entitySet, entityType, container);

            Assert.Equal(expectedOutput, output);
        }
コード例 #19
0
        private ODataPath ParseDynamicPathSegmentFunc_ReturnNavAndSegment(Uri fullUri)
        {
            var container = ContainerBuilderHelper.BuildContainer(builder => builder.AddService <UriPathParser, SingleSegmentUriPathParser>(ServiceLifetime.Scoped));
            var uriParser = new ODataUriParser(oneDriveModel, ServiceRoot, fullUri, container);

            uriParser.ParseDynamicPathSegmentFunc = (previous, identifier, parenthesisExpression) =>
            {
                switch (identifier)
                {
                case "customizedDrive":
                    return(new List <ODataPathSegment>
                    {
                        new SingletonSegment(driveSingleton)
                        {
                            Identifier = identifier
                        }
                    });

                case "root:/OData/Doc/OData Client for .NET.pptx:":
                    var navPropSeg = new NavigationPropertySegment(itemsNavProp, containedItemsNav);
                    var keySegment = new KeySegment(navPropSeg, new Dictionary <string, object>()
                    {
                        { "id", "test" }
                    }, itemType, containedItemsNav);
                    return(new List <ODataPathSegment>
                    {
                        navPropSeg,
                        keySegment
                    });

                default:
                    throw new Exception("Not supported Type");
                }
            };

            return(uriParser.ParsePath());
        }
コード例 #20
0
        private static ODataMessageReader CreateODataMessageReader(string payload, string contentType, bool isResponse, bool shouldReadAndValidateCustomInstanceAnnotations, bool enableReadingODataAnnotationWithoutPrefix = false)
        {
            var stream         = new MemoryStream(Encoding.UTF8.GetBytes(payload));
            var readerSettings = new ODataMessageReaderSettings {
                EnableMessageStreamDisposal = false
            };
            var container = ContainerBuilderHelper.BuildContainer(null);

            container.GetRequiredService <ODataSimplifiedOptions>().EnableReadingODataAnnotationWithoutPrefix =
                enableReadingODataAnnotationWithoutPrefix;
            ODataMessageReader messageReader;

            if (isResponse)
            {
                IODataResponseMessage responseMessage = new InMemoryMessage {
                    StatusCode = 200, Stream = stream, Container = container
                };
                responseMessage.SetHeader("Content-Type", contentType);
                if (shouldReadAndValidateCustomInstanceAnnotations)
                {
                    responseMessage.PreferenceAppliedHeader().AnnotationFilter = "*";
                }

                messageReader = new ODataMessageReader(responseMessage, readerSettings, Model);
            }
            else
            {
                IODataRequestMessage requestMessage = new InMemoryMessage {
                    Method = "GET", Stream = stream, Container = container
                };
                requestMessage.SetHeader("Content-Type", contentType);
                readerSettings.ShouldIncludeAnnotation = shouldReadAndValidateCustomInstanceAnnotations ? ODataUtils.CreateAnnotationFilter("*") : null;
                messageReader = new ODataMessageReader(requestMessage, readerSettings, Model);
            }

            return(messageReader);
        }
コード例 #21
0
        private ODataUriParser ParseDynamicPathSegmentFunc_ReturnDynamicPathSegment(Uri fullUri, out ODataPath odataPath)
        {
            var container = ContainerBuilderHelper.BuildContainer(builder => builder.AddService <UriPathParser, SingleSegmentUriPathParser>(ServiceLifetime.Scoped));

            var uriParser = new ODataUriParser(oneDriveModel, ServiceRoot, fullUri, container);

            uriParser.ParseDynamicPathSegmentFunc = (previous, identifier, parenthesisExpression) =>
            {
                switch (identifier)
                {
                case "root:/OData/Doc/OData Client for .NET.pptx":
                case "root:/OData/Doc/OData Client for .NET.pptx:":
                    return(new List <ODataPathSegment> {
                        new DynamicPathSegment(identifier, itemType, containedItemsNav, true)
                    });

                default:
                    throw new Exception("Not supported Type");
                }
            };
            odataPath = uriParser.ParsePath();

            return(uriParser);
        }
        public void ReadDateTimeOffsetWithCustomFormat()
        {
            EdmModel model = new EdmModel();

            EdmEntityType entityType = new EdmEntityType("NS", "Person");

            model.AddElement(entityType);
            entityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);
            entityType.AddStructuralProperty("Birthday", EdmPrimitiveTypeKind.DateTimeOffset);

            EdmEntityContainer container = new EdmEntityContainer("EntityNs", "MyContainer");
            EdmEntitySet       entitySet = container.AddEntitySet("People", entityType);

            model.AddElement(container);

            const string payload =
                "{" +
                "\"@odata.context\":\"http://www.example.com/$metadata#EntityNs.MyContainer.People/$entity\"," +
                "\"@odata.id\":\"http://mytest\"," +
                "\"Id\":0," +
                "\"Birthday\":\"Thu, 12 Apr 2012 18:43:10 GMT\"" +
                "}";

            ODataResource entry       = null;
            var           diContainer = ContainerBuilderHelper.BuildContainer(
                builder => builder.AddService <ODataPayloadValueConverter, DateTimeOffsetCustomFormatPrimitivePayloadValueConverter>(ServiceLifetime.Singleton));

            this.ReadEntryPayload(model, payload, entitySet, entityType, reader => { entry = entry ?? reader.Item as ODataResource; }, container: diContainer);
            Assert.NotNull(entry);

            IList <ODataProperty> propertyList = entry.Properties.ToList();
            var birthday = propertyList[1].Value as DateTimeOffset?;

            birthday.HasValue.Should().BeTrue();
            birthday.Value.Should().Be(new DateTimeOffset(2012, 4, 12, 18, 43, 10, TimeSpan.Zero));
        }
コード例 #23
0
 private static void SetVCardMediaTypeResolver(HttpWebRequestMessage requestMessage)
 {
     requestMessage.Container = ContainerBuilderHelper.BuildContainer(builder =>
                                                                      builder.AddService <ODataMediaTypeResolver, VCardMediaTypeResolver>(ServiceLifetime.Singleton));
 }