• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Serialization.ODataSerializerContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: ODataEntityReferenceLinkSerializer_Serializes_UrisAndEntityReferenceLinks

        public void ODataEntityReferenceLinkSerializer_Serializes_UrisAndEntityReferenceLinks(object uris)
        {
            // Arrange
            ODataEntityReferenceLinksSerializer serializer = new ODataEntityReferenceLinksSerializer();
            ODataSerializerContext writeContext = new ODataSerializerContext();
            MemoryStream stream = new MemoryStream();
            IODataResponseMessage message = new ODataMessageWrapper(stream);

            ODataMessageWriterSettings settings = new ODataMessageWriterSettings
            {
                ODataUri = new ODataUri { ServiceRoot = new Uri("http://any/") }
            };

            settings.SetContentType(ODataFormat.Json);
            ODataMessageWriter writer = new ODataMessageWriter(message, settings);

            // Act
            serializer.WriteObject(uris, typeof(ODataEntityReferenceLinks), writer, writeContext);
            stream.Seek(0, SeekOrigin.Begin);
            string result = new StreamReader(stream).ReadToEnd();

            // Assert
            Assert.Equal("{\"@odata.context\":\"http://any/$metadata#Collection($ref)\"," +
                "\"value\":[{\"@odata.id\":\"http://uri1/\"},{\"@odata.id\":\"http://uri2/\"}]}",
                result);
        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:26,代码来源:ODataEntityReferenceLinksSerializerTest.cs


示例2: WriteObject_WritesValueReturnedFrom_CreateODataCollectionValue

        public void WriteObject_WritesValueReturnedFrom_CreateODataCollectionValue()
        {
            // Arrange
            MemoryStream stream = new MemoryStream();
            IODataResponseMessage message = new ODataMessageWrapper(stream);
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings();
            settings.SetContentType(ODataFormat.Atom);
            ODataMessageWriter messageWriter = new ODataMessageWriter(message, settings);
            Mock<ODataCollectionSerializer> serializer = new Mock<ODataCollectionSerializer>(new DefaultODataSerializerProvider());
            ODataSerializerContext writeContext = new ODataSerializerContext { RootElementName = "CollectionName", Model = _model };
            IEnumerable enumerable = new object[0];
            ODataCollectionValue collectionValue = new ODataCollectionValue { TypeName = "NS.Name", Items = new[] { 0, 1, 2 } };

            serializer.CallBase = true;
            serializer
                .Setup(s => s.CreateODataCollectionValue(enumerable, It.Is<IEdmTypeReference>(e => e.Definition == _edmIntType.Definition), writeContext))
                .Returns(collectionValue).Verifiable();

            // Act
            serializer.Object.WriteObject(enumerable, typeof(int[]), messageWriter, writeContext);

            // Assert
            serializer.Verify();
            stream.Seek(0, SeekOrigin.Begin);
            XElement element = XElement.Load(stream);
            Assert.Equal("value", element.Name.LocalName);
            Assert.Equal(3, element.Descendants().Count());
            Assert.Equal(new[] { "0", "1", "2" }, element.Descendants().Select(e => e.Value));
        }
开发者ID:nicholaspei,项目名称:aspnetwebstack,代码行数:29,代码来源:ODataCollectionSerializerTests.cs


示例3: SelectExpandNode

        /// <summary>
        /// Creates a new instance of the <see cref="SelectExpandNode"/> class describing the set of structural properties,
        /// navigation properties, and actions to select and expand for the given <paramref name="writeContext"/>.
        /// </summary>
        /// <param name="entityType">The entity type of the entry that would be written.</param>
        /// <param name="writeContext">The serializer context to be used while creating the collection.</param>
        /// <remarks>The default constructor is for unit testing only.</remarks>
        public SelectExpandNode(IEdmEntityType entityType, ODataSerializerContext writeContext)
            : this(writeContext.SelectExpandClause, entityType, writeContext.Model)
        {
            var queryOptionParser = new ODataQueryOptionParser(
                  writeContext.Model,
                  entityType,
                  writeContext.NavigationSource,
                  _extraQueryParameters);

            var selectExpandClause = queryOptionParser.ParseSelectAndExpand();
            if (selectExpandClause != null)
            {
                foreach (SelectItem selectItem in selectExpandClause.SelectedItems)
                {
                    ExpandedNavigationSelectItem expandItem = selectItem as ExpandedNavigationSelectItem;
                    if (expandItem != null)
                    {
                        ValidatePathIsSupported(expandItem.PathToNavigationProperty);
                        NavigationPropertySegment navigationSegment = (NavigationPropertySegment)expandItem.PathToNavigationProperty.LastSegment;
                        IEdmNavigationProperty navigationProperty = navigationSegment.NavigationProperty;
                        if (!ExpandedNavigationProperties.ContainsKey(navigationProperty))
                        {
                            ExpandedNavigationProperties.Add(navigationProperty, expandItem.SelectAndExpand);
                        }
                    }
                }
            }
            SelectedNavigationProperties.ExceptWith(ExpandedNavigationProperties.Keys);
        }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:36,代码来源:SelectExpandNode.cs


示例4: WriteObject

        /// <inheridoc />
        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");
            }

            if (graph != null)
            {
                ODataEntityReferenceLinks entityReferenceLinks = graph as ODataEntityReferenceLinks;
                if (entityReferenceLinks == null)
                {
                    IEnumerable<Uri> uris = graph as IEnumerable<Uri>;
                    if (uris == null)
                    {
                        throw new SerializationException(Error.Format(SRResources.CannotWriteType, GetType().Name, graph.GetType().FullName));
                    }

                    entityReferenceLinks = new ODataEntityReferenceLinks
                    {
                        Links = uris.Select(uri => new ODataEntityReferenceLink { Url = uri })
                    };
                }

                messageWriter.WriteEntityReferenceLinks(entityReferenceLinks);
            }
        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:33,代码来源:ODataEntityReferenceLinksSerializer.cs


示例5: WriteObjectInline

        /// <inheritdoc />
        public override void WriteObjectInline(object graph, IEdmTypeReference expectedType, ODataWriter writer,
            ODataSerializerContext writeContext)
        {
            if (writer == null)
            {
                throw Error.ArgumentNull("writer");
            }
            if (writeContext == null)
            {
                throw Error.ArgumentNull("writeContext");
            }
            if (expectedType == null)
            {
                throw Error.ArgumentNull("expectedType");
            }
            if (graph == null)
            {
                throw new SerializationException(Error.Format(SRResources.CannotSerializerNull, Feed));
            }

            IEnumerable enumerable = graph as IEnumerable; // Data to serialize
            if (enumerable == null)
            {
                throw new SerializationException(
                    Error.Format(SRResources.CannotWriteType, GetType().Name, graph.GetType().FullName));
            }

            WriteFeed(enumerable, expectedType, writer, writeContext);
        }
开发者ID:Gebov,项目名称:WebApi,代码行数:30,代码来源:ODataFeedSerializer.cs


示例6: CreateODataEnumValue

        /// <summary>
        /// Creates an <see cref="ODataEnumValue"/> for the object represented by <paramref name="graph"/>.
        /// </summary>
        /// <param name="graph">The enum value.</param>
        /// <param name="enumType">The EDM enum type of the value.</param>
        /// <param name="writeContext">The serializer write context.</param>
        /// <returns>The created <see cref="ODataEnumValue"/>.</returns>
        public virtual ODataEnumValue CreateODataEnumValue(object graph, IEdmEnumTypeReference enumType,
            ODataSerializerContext writeContext)
        {
            if (graph == null)
            {
                return null;
            }

            string value = null;
            if (graph.GetType().IsEnum)
            {
                value = graph.ToString();
            }
            else
            {
                if (graph.GetType() == typeof(EdmEnumObject))
                {
                    value = ((EdmEnumObject)graph).Value;
                }
            }

            ODataEnumValue enumValue = new ODataEnumValue(value, enumType.FullName());

            ODataMetadataLevel metadataLevel = writeContext != null
                ? writeContext.MetadataLevel
                : ODataMetadataLevel.MinimalMetadata;
            AddTypeNameAnnotationAsNeeded(enumValue, enumType, metadataLevel);

            return enumValue;
        }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:37,代码来源:ODataEnumSerializer.cs


示例7: WriteObject

        /// <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");
            }

            IEdmEntitySetBase entitySet = writeContext.NavigationSource as IEdmEntitySetBase;
            if (entitySet == null)
            {
                throw new SerializationException(SRResources.EntitySetMissingDuringSerialization);
            }

            IEdmTypeReference feedType = writeContext.GetEdmType(graph, type);
            Contract.Assert(feedType != null);

            IEdmEntityTypeReference entityType = GetEntityType(feedType);
            ODataWriter writer = messageWriter.CreateODataFeedWriter(entitySet, entityType.EntityDefinition());
            WriteObjectInline(graph, feedType, writer, writeContext);
        }
开发者ID:Gebov,项目名称:WebApi,代码行数:26,代码来源:ODataFeedSerializer.cs


示例8: WriteObjectInline

 public override void WriteObjectInline(object graph, IEdmTypeReference expectedType, ODataWriter writer, ODataSerializerContext writeContext)
 {
     if (graph != null)
     {
         base.WriteObjectInline(graph, expectedType, writer, writeContext);
     }
 }
开发者ID:MCornel,项目名称:OWIN_ODATA_ORDERS_API,代码行数:7,代码来源:NullSerializerProvider.cs


示例9: WriteObject

        /// <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);
        }
开发者ID:BarclayII,项目名称:WebApi,代码行数:29,代码来源:ODataEntityTypeSerializer.cs


示例10: WriteObject

        /// <summary>
        /// Writes the entity result to the response message.
        /// </summary>
        /// <param name="graph">The entity result to write.</param>
        /// <param name="type">The type of the entity.</param>
        /// <param name="messageWriter">The message writer.</param>
        /// <param name="writeContext">The writing context.</param>
        public override void WriteObject(
            object graph,
            Type type,
            ODataMessageWriter messageWriter,
            ODataSerializerContext writeContext)
        {
            RawResult rawResult = graph as RawResult;
            if (rawResult != null)
            {
                graph = rawResult.Result;
                type = rawResult.Type;
            }

            if (writeContext != null)
            {
                graph = RestierPrimitiveSerializer.ConvertToPayloadValue(graph, writeContext);
            }

            if (graph == null)
            {
                // This is to make ODataRawValueSerializer happily serialize null value.
                graph = string.Empty;
            }

            base.WriteObject(graph, type, messageWriter, writeContext);
        }
开发者ID:cinaradem,项目名称:RESTier,代码行数:33,代码来源:RestierRawSerializer.cs


示例11: CanSerializerSingleton

        public void CanSerializerSingleton()
        {
            // Arrange
            const string expect = "{" +
                "\"@odata.context\":\"http://localhost/odata/$metadata#Boss\"," +
                "\"@odata.id\":\"http://localhost/odata/Boss\"," +
                "\"@odata.editLink\":\"http://localhost/odata/Boss\"," +
                "\"EmployeeId\":987,\"EmployeeName\":\"John Mountain\"}";

            IEdmModel model = GetEdmModel();
            IEdmSingleton singleton = model.EntityContainer.FindSingleton("Boss");
            HttpRequestMessage request = GetRequest(model, singleton);
            ODataSerializerContext readContext = new ODataSerializerContext()
            {
                Url = new UrlHelper(request),
                Path = request.ODataProperties().Path,
                Model = model,
                NavigationSource = singleton
            };

            ODataSerializerProvider serializerProvider = new DefaultODataSerializerProvider();
            EmployeeModel boss = new EmployeeModel {EmployeeId = 987, EmployeeName = "John Mountain"};
            MemoryStream bufferedStream = new MemoryStream();

            // Act
            ODataEntityTypeSerializer serializer = new ODataEntityTypeSerializer(serializerProvider);
            serializer.WriteObject(boss, typeof(EmployeeModel), GetODataMessageWriter(model, bufferedStream), readContext);

            // Assert
            string result = Encoding.UTF8.GetString(bufferedStream.ToArray());
            Assert.Equal(expect, result);
        }
开发者ID:nicholaspei,项目名称:aspnetwebstack,代码行数:32,代码来源:ODataSingletonSerializerTest.cs


示例12: CreateODataPrimitiveValue

        /// <summary>
        /// Creates an <see cref="ODataPrimitiveValue"/> for the object represented by <paramref name="graph"/>.
        /// </summary>
        /// <param name="graph">The primitive value.</param>
        /// <param name="primitiveType">The EDM primitive type of the value.</param>
        /// <param name="writeContext">The serializer write context.</param>
        /// <returns>The created <see cref="ODataPrimitiveValue"/>.</returns>
        public override ODataPrimitiveValue CreateODataPrimitiveValue(
            object graph,
            IEdmPrimitiveTypeReference primitiveType,
            ODataSerializerContext writeContext)
        {
            // The EDM type of the "graph" would override the EDM type of the property when
            // OData Web API infers the primitiveType. Thus for "graph" of System.DateTime,
            // the primitiveType is always Edm.DateTimeOffset.
            //
            // In EF, System.DateTime is used for SqlDate, SqlDateTime and SqlDateTime2.
            // All of them have no time zone information thus it is safe to clear the time
            // zone when converting the "graph" to a DateTimeOffset.
            if (primitiveType != null && primitiveType.IsDateTimeOffset() && graph is DateTime)
            {
                // If DateTime.Kind equals Local, offset should equal the offset of the system's local time zone
                if (((DateTime)graph).Kind == DateTimeKind.Local)
                {
                    graph = new DateTimeOffset((DateTime)graph, TimeZoneInfo.Local.GetUtcOffset((DateTime)graph));
                }
                else
                {
                    graph = new DateTimeOffset((DateTime)graph, TimeSpan.Zero);
                }
            }

            return base.CreateODataPrimitiveValue(graph, primitiveType, writeContext);
        }
开发者ID:chinadragon0515,项目名称:RESTier,代码行数:34,代码来源:RestierPrimitiveSerializer.cs


示例13: WriteObject_WritesValueReturnedFrom_CreateODataCollectionValue

        public void WriteObject_WritesValueReturnedFrom_CreateODataCollectionValue()
        {
            // Arrange
            MemoryStream stream = new MemoryStream();
            IODataResponseMessage message = new ODataMessageWrapper(stream);
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings()
            {
                ODataUri = new ODataUri { ServiceRoot = new Uri("http://any/") }
            };

            settings.SetContentType(ODataFormat.Json);

            ODataMessageWriter messageWriter = new ODataMessageWriter(message, settings);
            Mock<ODataCollectionSerializer> serializer = new Mock<ODataCollectionSerializer>(new DefaultODataSerializerProvider());
            ODataSerializerContext writeContext = new ODataSerializerContext { RootElementName = "CollectionName", Model = _model };
            IEnumerable enumerable = new object[0];
            ODataCollectionValue collectionValue = new ODataCollectionValue { TypeName = "NS.Name", Items = new[] { 0, 1, 2 } };

            serializer.CallBase = true;
            serializer
                .Setup(s => s.CreateODataCollectionValue(enumerable, It.Is<IEdmTypeReference>(e => e.Definition == _edmIntType.Definition), writeContext))
                .Returns(collectionValue).Verifiable();

            // Act
            serializer.Object.WriteObject(enumerable, typeof(int[]), messageWriter, writeContext);

            // Assert
            serializer.Verify();
            stream.Seek(0, SeekOrigin.Begin);
            string result = new StreamReader(stream).ReadToEnd();
            Assert.Equal("{\"@odata.context\":\"http://any/$metadata#Collection(Edm.Int32)\",\"value\":[0,1,2]}", result);
        }
开发者ID:ahmetgoktas,项目名称:aspnetwebstack,代码行数:32,代码来源:ODataCollectionSerializerTests.cs


示例14: Singleton_CanOnlyConfigureIdLinkViaIdLinkFactory

        public void Singleton_CanOnlyConfigureIdLinkViaIdLinkFactory()
        {
            // Arrange
            ODataModelBuilder builder = GetSingletonModel();
            const string ExpectedEditLink = "http://server/service/Exchange";

            var product = builder.Singleton<SingletonProduct>("Exchange");
            product.HasIdLink(c => new Uri("http://server/service/Exchange"),
                followsConventions: false);

            var exchange = builder.Singletons.Single();
            var model = builder.GetEdmModel();
            var productType = model.SchemaElements.OfType<IEdmEntityType>().Single();
            var singleton = model.SchemaElements.OfType<IEdmEntityContainer>().Single().FindSingleton("Exchange");
            var singletonInstance = new SingletonProduct { ID = 15 };
            var serializerContext = new ODataSerializerContext { Model = model, NavigationSource = singleton };
            var entityContext = new EntityInstanceContext(serializerContext, productType.AsReference(), singletonInstance);
            var linkBuilderAnnotation = new NavigationSourceLinkBuilderAnnotation(exchange);

            // Act
            var selfLinks = linkBuilderAnnotation.BuildEntitySelfLinks(entityContext, ODataMetadataLevel.FullMetadata);

            // Assert
            Assert.NotNull(selfLinks.IdLink);
            Assert.Equal(ExpectedEditLink, selfLinks.IdLink.ToString());
            Assert.Null(selfLinks.ReadLink);
            Assert.Null(selfLinks.EditLink);
        }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:28,代码来源:SingletonLinkConfigurationTest.cs


示例15: Ctor_ThatBuildsNestedContext_CopiesProperties

        public void Ctor_ThatBuildsNestedContext_CopiesProperties()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            ODataSerializerContext context = new ODataSerializerContext
            {
                NavigationSource = model.Customers,
                MetadataLevel = ODataMetadataLevel.FullMetadata,
                Model = model.Model,
                Path = new ODataPath(),
                Request = new HttpRequestMessage(),
                RootElementName = "somename",
                SelectExpandClause = new SelectExpandClause(new SelectItem[0], allSelected: true),
                SkipExpensiveAvailabilityChecks = true,
                Url = new UrlHelper()
            };
            EntityInstanceContext entity = new EntityInstanceContext { SerializerContext = context };
            SelectExpandClause selectExpand = new SelectExpandClause(new SelectItem[0], allSelected: true);
            IEdmNavigationProperty navProp = model.Customer.NavigationProperties().First();

            // Act
            ODataSerializerContext nestedContext = new ODataSerializerContext(entity, selectExpand, navProp);

            // Assert
            Assert.Equal(context.MetadataLevel, nestedContext.MetadataLevel);
            Assert.Same(context.Model, nestedContext.Model);
            Assert.Same(context.Path, nestedContext.Path);
            Assert.Same(context.Request, nestedContext.Request);
            Assert.Equal(context.RootElementName, nestedContext.RootElementName);
            Assert.Equal(context.SkipExpensiveAvailabilityChecks, nestedContext.SkipExpensiveAvailabilityChecks);
            Assert.Same(context.Url, nestedContext.Url);
        }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:32,代码来源:ODataSerializerContextTest.cs


示例16: Convention_GeneratesUri_ForActionBoundToEntity

        public void Convention_GeneratesUri_ForActionBoundToEntity()
        {
            // Arrange
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<Customer>("Customers");
            var action = builder.EntityType<Customer>().Action("MyAction");
            action.Parameter<string>("param");
            IEdmModel model = builder.GetEdmModel();

            // Act
            HttpConfiguration configuration = new HttpConfiguration();
            configuration.MapODataServiceRoute("odata", "odata", model);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:123");
            request.SetConfiguration(configuration);
            request.ODataProperties().RouteName = "odata";

            IEdmEntitySet customers = model.EntityContainer.FindEntitySet("Customers");
            var edmType = model.SchemaElements.OfType<IEdmEntityType>().First(e => e.Name == "Customer");
            var serializerContext = new ODataSerializerContext { Model = model, NavigationSource = customers, Url = request.GetUrlHelper() };
            var entityContext = new EntityInstanceContext(serializerContext, edmType.AsReference(), new Customer { Id = 109 });

            // Assert
            var edmAction = model.SchemaElements.OfType<IEdmAction>().First(f => f.Name == "MyAction");
            Assert.NotNull(edmAction);

            ActionLinkBuilder actionLinkBuilder = model.GetActionLinkBuilder(edmAction);
            Uri link = actionLinkBuilder.BuildActionLink(entityContext);

            Assert.Equal("http://localhost:123/odata/Customers(109)/Default.MyAction", link.AbsoluteUri);
        }
开发者ID:chinadragon0515,项目名称:WebApi,代码行数:31,代码来源:ActionLinkGenerationConventionTest.cs


示例17: ODataDeltaFeedSerializerTests

        public ODataDeltaFeedSerializerTests()
        {
            _model = SerializationTestsHelpers.SimpleCustomerOrderModel();
            _customerSet = _model.EntityContainer.FindEntitySet("Customers");
            _model.SetAnnotationValue(_customerSet.EntityType(), new ClrTypeAnnotation(typeof(Customer)));
            _path = new ODataPath(new EntitySetPathSegment(_customerSet));
            _customers = new[] {
                new Customer()
                {
                    FirstName = "Foo",
                    LastName = "Bar",
                    ID = 10,
                },
                new Customer()
                {
                    FirstName = "Foo",
                    LastName = "Bar",
                    ID = 42,
                }
            };

            _deltaFeedCustomers = new EdmChangedObjectCollection(_customerSet.EntityType());
            EdmDeltaEntityObject newCustomer = new EdmDeltaEntityObject(_customerSet.EntityType());
            newCustomer.TrySetPropertyValue("ID", 10);
            newCustomer.TrySetPropertyValue("FirstName", "Foo");
            _deltaFeedCustomers.Add(newCustomer);

             _customersType = _model.GetEdmTypeReference(typeof(Customer[])).AsCollection();

            _writeContext = new ODataSerializerContext() { NavigationSource = _customerSet, Model = _model, Path = _path };
        }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:31,代码来源:ODataDeltaFeedSerializerTests.cs


示例18: WriteObject

        /// <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");
            }

            if (graph != null)
            {
                ODataEntityReferenceLink entityReferenceLink = graph as ODataEntityReferenceLink;
                if (entityReferenceLink == null)
                {
                    Uri uri = graph as Uri;
                    if (uri == null)
                    {
                        throw new SerializationException(Error.Format(SRResources.CannotWriteType, GetType().Name, graph.GetType().FullName));
                    }

                    entityReferenceLink = new ODataEntityReferenceLink { Url = uri };
                }

                messageWriter.WriteEntityReferenceLink(entityReferenceLink);
            }
        }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:30,代码来源:ODataEntityReferenceLinkSerializer.cs


示例19: WriteObject_Calls_CreateODataComplexValue

        public void WriteObject_Calls_CreateODataComplexValue()
        {
            // Arrange
            MemoryStream stream = new MemoryStream();
            IODataResponseMessage message = new ODataMessageWrapper(stream);
            ODataMessageWriterSettings settings = new ODataMessageWriterSettings();
            settings.SetServiceDocumentUri(new Uri("http://any/"));
            settings.SetContentType(ODataFormat.Atom);
            ODataMessageWriter messageWriter = new ODataMessageWriter(message, settings);
            Mock<ODataComplexTypeSerializer> serializer = new Mock<ODataComplexTypeSerializer>(new DefaultODataSerializerProvider());
            ODataSerializerContext writeContext = new ODataSerializerContext { RootElementName = "ComplexPropertyName", Model = _model };
            object graph = new object();
            ODataComplexValue complexValue = new ODataComplexValue
            {
                TypeName = "NS.Name",
                Properties = new[] { new ODataProperty { Name = "Property1", Value = 42 } }
            };

            serializer.CallBase = true;
            serializer.Setup(s => s.CreateODataComplexValue(graph, It.Is<IEdmComplexTypeReference>(e => e.Definition == _addressType), writeContext))
                .Returns(complexValue).Verifiable();

            // Act
            serializer.Object.WriteObject(graph, typeof(Address), messageWriter, writeContext);

            // Assert
            serializer.Verify();
            stream.Seek(0, SeekOrigin.Begin);
            XElement element = XElement.Load(stream);
            Assert.Equal("value", element.Name.LocalName);
            Assert.Equal("#NS.Name", element.Attributes().Single(a => a.Name.LocalName == "type").Value);
            Assert.Equal(1, element.Descendants().Count());
            Assert.Equal("42", element.Descendants().Single().Value);
            Assert.Equal("Property1", element.Descendants().Single().Name.LocalName);
        }
开发者ID:tlycken,项目名称:aspnetwebstack,代码行数:35,代码来源:ODataComplexTypeSerializerTests.cs


示例20: CanConfigureAllLinksViaIdLink

        public void CanConfigureAllLinksViaIdLink()
        {
            // Arrange
            ODataModelBuilder builder = GetCommonModel();
            var expectedEditLink = "http://server/service/Products(15)";

            var products = builder.EntitySet<EntitySetLinkConfigurationTest_Product>("Products");
            products.HasIdLink(c =>
                string.Format(
                    "http://server/service/Products({0})",
                    c.GetPropertyValue("ID")
                ),
                followsConventions: false);

            var actor = builder.EntitySets.Single();
            var model = builder.GetEdmModel();
            var productType = model.SchemaElements.OfType<IEdmEntityType>().Single();
            var productsSet = model.SchemaElements.OfType<IEdmEntityContainer>().Single().EntitySets().Single();
            var productInstance = new EntitySetLinkConfigurationTest_Product { ID = 15 };
            var serializerContext = new ODataSerializerContext { Model = model, NavigationSource = productsSet };
            var entityContext = new EntityInstanceContext(serializerContext, productType.AsReference(), productInstance);
            var linkBuilderAnnotation = new NavigationSourceLinkBuilderAnnotation(actor);

            // Act
            var selfLinks = linkBuilderAnnotation.BuildEntitySelfLinks(entityContext, ODataMetadataLevel.Default);

            // Assert
            Assert.NotNull(selfLinks.EditLink);
            Assert.Equal(expectedEditLink, selfLinks.EditLink.ToString());
            Assert.NotNull(selfLinks.ReadLink);
            Assert.Equal(expectedEditLink, selfLinks.ReadLink.ToString());
            Assert.NotNull(selfLinks.IdLink);
            Assert.Equal(expectedEditLink, selfLinks.IdLink);
        }
开发者ID:nicholaspei,项目名称:aspnetwebstack,代码行数:34,代码来源:EntitySetLinkConfigurationTest.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Serialization.SelectExpandNode类代码示例发布时间:2022-05-26
下一篇:
C# Deserialization.ODataEntityDeserializer类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap