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

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

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

            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);
        }
        public ODataFeedSerializerTests()
        {
            _model = SerializationTestsHelpers.SimpleCustomerOrderModel();
            _customerSet = _model.FindDeclaredEntityContainer("Default.Container").FindEntitySet("Customers");
            _customers = new[] {
                new Customer()
                {
                    FirstName = "Foo",
                    LastName = "Bar",
                    ID = 10,
                },
                new Customer()
                {
                    FirstName = "Foo",
                    LastName = "Bar",
                    ID = 42,
                }
            };

            _customersType = new EdmCollectionTypeReference(
                    new EdmCollectionType(
                        new EdmEntityTypeReference(
                            _customerSet.ElementType,
                            isNullable: false)),
                    isNullable: false);

            _writeContext = new ODataSerializerContext() { EntitySet = _customerSet, Model = _model };
        }
        public void Apply_Doesnot_Override_UserConfiguration()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var vehicles = builder.EntitySet<Vehicle>("vehicles");
            var car = builder.AddEntity(typeof(Car));
            var paintAction = vehicles.EntityType.Action("Paint");
            paintAction.HasActionLink(ctxt => new Uri("http://localhost/ActionTestWorks"), followsConventions: false);
            ActionLinkGenerationConvention convention = new ActionLinkGenerationConvention();

            convention.Apply(paintAction, builder);

            IEdmModel model = builder.GetEdmModel();
            var vehiclesEdmSet = model.EntityContainers().Single().FindEntitySet("vehicles");
            var carEdmType = model.FindDeclaredType("System.Web.Http.OData.Builder.TestModels.Car") as IEdmEntityType;
            var paintEdmAction =
                model.GetAvailableProcedures(
                    model.FindDeclaredType("System.Web.Http.OData.Builder.TestModels.Car") as IEdmEntityType).Single()
                as IEdmAction;
            Assert.NotNull(paintEdmAction);

            HttpConfiguration configuration = new HttpConfiguration();
            configuration.Routes.MapODataRoute(model);

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

            ActionLinkBuilder actionLinkBuilder = model.GetActionLinkBuilder(paintEdmAction);

            var serializerContext = new ODataSerializerContext { Model = model, EntitySet = vehiclesEdmSet, Url = request.GetUrlHelper() };
            var entityContext = new EntityInstanceContext(serializerContext, carEdmType.AsReference(), new Car { Model = 2009, Name = "Accord" });

            Uri link = actionLinkBuilder.BuildActionLink(entityContext);
            Assert.Equal("http://localhost/ActionTestWorks", link.AbsoluteUri);
        }
        /// <inheritdoc/>
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

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

            ODataCollectionWriter writer = messageWriter.CreateODataCollectionWriter();
            writer.WriteStart(
                new ODataCollectionStart
                {
                    Name = writeContext.RootElementName
                });

            ODataProperty property = CreateProperty(graph, writeContext.RootElementName, writeContext);
            if (property != null)
            {
                ODataCollectionValue collectionValue = property.Value as ODataCollectionValue;

                foreach (object item in collectionValue.Items)
                {
                    writer.WriteItem(item);
                }

                writer.WriteEnd();
                writer.Flush();
            }
        }
        public void CopyCtor_CopiesAllTheProperties()
        {
            // Arrange
            ODataSerializerContext context = new ODataSerializerContext
            {
                EntitySet = new Mock<IEdmEntitySet>().Object,
                IsNested = true,
                MetadataLevel = ODataMetadataLevel.FullMetadata,
                Model = new Mock<IEdmModel>().Object,
                Path = new ODataPath(),
                Request = new HttpRequestMessage(),
                RootElementName = "somename",
                SelectExpandClause = new SelectExpandClause(new SelectItem[0], allSelected: true),
                SkipExpensiveAvailabilityChecks = true,
                Url = new UrlHelper()
            };

            // Act
            ODataSerializerContext result = new ODataSerializerContext(context);

            // Assert
            // Check each and every property. This test should fail if someone accidentally adds a new property and 
            // forgets to update the copy constructor.
            foreach (PropertyInfo property in typeof(ODataSerializerContext).GetProperties())
            {
                if (property.PropertyType.IsValueType)
                {
                    Assert.Equal(property.GetValue(context), property.GetValue(result));
                }
                else
                {
                    Assert.Same(property.GetValue(context), property.GetValue(result));
                }
            }
        }
        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, EntitySet = productsSet };
            var entityContext = new EntityInstanceContext(serializerContext, productType.AsReference(), productInstance);
            var entitySetLinkBuilderAnnotation = new EntitySetLinkBuilderAnnotation(actor);

            // Act
            var selfLinks = entitySetLinkBuilderAnnotation.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);
        }
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

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

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

            IEdmEntitySet entitySet = writeContext.EntitySet;

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

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

            ODataWriter writer = messageWriter.CreateODataEntryWriter(entitySet, entityType);
            WriteObjectInline(graph, writer, writeContext);
            writer.Flush();
        }
        public void GenerateActionLink_GeneratesLinkWithoutCast_IfEntitySetTypeMatchesActionEntityType()
        {
            // Arrange
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var cars = builder.EntitySet<Car>("cars");
            var paintAction = cars.EntityType.Action("Paint");

            IEdmModel model = builder.GetEdmModel();
            var carsEdmSet = model.EntityContainers().Single().FindEntitySet("cars");

            HttpConfiguration configuration = new HttpConfiguration();
            string routeName = "Route";
            configuration.Routes.MapODataRoute(routeName, null, model);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");
            request.SetConfiguration(configuration);
            request.SetODataRouteName(routeName);

            var serializerContext = new ODataSerializerContext { Model = model, EntitySet = carsEdmSet, Url = request.GetUrlHelper() };
            var entityContext = new EntityInstanceContext(serializerContext, carsEdmSet.ElementType.AsReference(), new Car { Model = 2009, Name = "Accord" });

            // Act
            Uri link = ActionLinkGenerationConvention.GenerateActionLink(entityContext, paintAction);

            Assert.Equal("http://localhost/cars(Model=2009,Name='Accord')/Paint", link.AbsoluteUri);
        }
        public void WriteObject_WritesValueReturnedFrom_CreateODataCollectionValue()
        {
            // Arrange
            MemoryStream stream = new MemoryStream();
            IODataResponseMessage message = new ODataMessageWrapper(stream);
            ODataMessageWriter messageWriter = new ODataMessageWriter(message);
            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("CollectionName", element.Name.LocalName);
            Assert.Equal(3, element.Descendants().Count());
            Assert.Equal(new[] { "0", "1", "2" }, element.Descendants().Select(e => e.Value));
        }
        public void Ctor_ThatBuildsNestedContext_CopiesProperties()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            ODataSerializerContext context = new ODataSerializerContext
            {
                EntitySet = 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);
        }
        public void WriteObject_Calls_CreateODataComplexValue()
        {
            // Arrange
            MemoryStream stream = new MemoryStream();
            IODataResponseMessage message = new ODataMessageWrapper(stream);
            ODataMessageWriter messageWriter = new ODataMessageWriter(message);
            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);
        }
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

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

            IEdmEntitySet entitySet = writeContext.EntitySet;

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

            IEdmNavigationProperty navigationProperty = GetNavigationProperty(writeContext.Path);

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

            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink { Url = graph as Uri }, entitySet,
                navigationProperty);
        }
        /// <inheritdoc />
        public override void WriteObjectInline(object graph, ODataWriter writer, ODataSerializerContext writeContext)
        {
            if (writer == null)
            {
                throw Error.ArgumentNull("writer");
            }

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

            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, writer, writeContext);
        }
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

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

            IEdmEntitySet entitySet = writeContext.EntitySet;

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

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

            ODataWriter writer = messageWriter.CreateODataFeedWriter(entitySet, entityType);
            WriteObjectInline(graph, writer, writeContext);
            writer.Flush();
        }
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (graph == null)
            {
                throw Error.ArgumentNull("graph");
            }

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

            ODataError oDataError = graph as ODataError;
            if (oDataError == null)
            {
                HttpError httpError = graph as HttpError;
                if (httpError == null)
                {
                    string message = Error.Format(SRResources.ErrorTypeMustBeODataErrorOrHttpError, graph.GetType().FullName);
                    throw new SerializationException(message);
                }
                else
                {
                    oDataError = httpError.ToODataError();
                }
            }

            bool includeDebugInformation = oDataError.InnerError != null;
            messageWriter.WriteError(oDataError, includeDebugInformation);
        }
        /// <inheritdoc/>
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

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

            ODataCollectionWriter writer = messageWriter.CreateODataCollectionWriter(_edmItemType);
            writer.WriteStart(
                new ODataCollectionStart
                {
                    Name = writeContext.RootElementName
                });

            ODataValue value = CreateODataValue(graph, writeContext);
            if (value != null)
            {
                ODataCollectionValue collectionValue = value as ODataCollectionValue;
                Contract.Assert(value != null);

                foreach (object item in collectionValue.Items)
                {
                    writer.WriteItem(item);
                }
            }

            writer.WriteEnd();
            writer.Flush();
        }
        public override ODataValue CreateODataValue(object graph, ODataSerializerContext writeContext)
        {
            ODataMetadataLevel metadataLevel = writeContext != null ?
                writeContext.MetadataLevel : ODataMetadataLevel.Default;

            // TODO: Bug 467598: validate the type of the object being passed in here with the underlying primitive type. 
            return CreatePrimitive(graph, metadataLevel);
        }
        /// <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 virtual ODataPrimitiveValue CreateODataPrimitiveValue(object graph, IEdmPrimitiveTypeReference primitiveType,
            ODataSerializerContext writeContext)
        {
            ODataMetadataLevel metadataLevel = writeContext != null ? writeContext.MetadataLevel : ODataMetadataLevel.Default;

            // TODO: Bug 467598: validate the type of the object being passed in here with the underlying primitive type. 
            return CreatePrimitive(graph, primitiveType, metadataLevel);
        }
        public void WriteObject_Throws_EntitySetMissingDuringSerialization()
        {
            ODataEntityReferenceLinksSerializer serializer = new ODataEntityReferenceLinksSerializer();
            ODataSerializerContext writeContext = new ODataSerializerContext();

            Assert.Throws<SerializationException>(
                () => serializer.WriteObject(graph: null, messageWriter: ODataTestUtil.GetMockODataMessageWriter(), writeContext: writeContext),
                "The related entity set could not be found from the OData path. The related entity set is required to serialize the payload.");
        }
        /// <inheritdoc/>
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            messageWriter.WriteValue(ODataPrimitiveSerializer.ConvertUnsupportedPrimitives(graph));
        }
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink { Url = graph as Uri });
        }
        public void WriteObject_Throws_NavigationPropertyMissingDuringSerialization()
        {
            ODataEntityReferenceLinksSerializer serializer = new ODataEntityReferenceLinksSerializer();
            ODataSerializerContext writeContext = new ODataSerializerContext { EntitySet = _customerSet, Path = new ODataPath() };

            Assert.Throws<SerializationException>(
                () => serializer.WriteObject(graph: null, messageWriter: ODataTestUtil.GetMockODataMessageWriter(), writeContext: writeContext),
                "The related navigation property could not be found from the OData path. The related navigation property is required to serialize the payload.");
        }
        public void WriteObject_Throws_ODataPathMissing()
        {
            ODataEntityReferenceLinksSerializer serializer = new ODataEntityReferenceLinksSerializer();
            ODataSerializerContext writeContext = new ODataSerializerContext { EntitySet = _customerSet };

            Assert.Throws<SerializationException>(
                () => serializer.WriteObject(graph: null, messageWriter: ODataTestUtil.GetMockODataMessageWriter(), writeContext: writeContext),
                "The operation cannot be completed because no ODataPath is available for the request.");
        }
 internal ODataProperty CreateProperty(object graph, string elementName, ODataSerializerContext writeContext)
 {
     Contract.Assert(elementName != null);
     return new ODataProperty
     {
         Name = elementName,
         Value = CreateODataValue(graph, writeContext)
     };
 }
        /// <inheritdoc/>
        public sealed override ODataValue CreateODataValue(object graph, ODataSerializerContext writeContext)
        {
            IEnumerable enumerable = graph as IEnumerable;
            if (enumerable == null)
            {
                throw Error.Argument("graph", SRResources.ArgumentMustBeOfType, typeof(IEnumerable).Name);
            }

            return CreateODataCollectionValue(enumerable, writeContext);
        }
        /// <inheritdoc/>
        public sealed override ODataValue CreateODataValue(object graph, ODataSerializerContext writeContext)
        {
            ODataPrimitiveValue value = CreateODataPrimitiveValue(graph, writeContext);
            if (value == null)
            {
                return new ODataNullValue();
            }

            return value;
        }
        public void GenerateSelfLink_GeneratesExpectedSelfLink(bool includeCast, string expectedIdLink)
        {
            HttpRequestMessage request = GetODataRequest(_model.Model);
            var serializerContext = new ODataSerializerContext { Model = _model.Model, EntitySet = _model.Customers, Url = request.GetUrlHelper() };
            var entityContext = new EntityInstanceContext(serializerContext, _model.SpecialCustomer.AsReference(), new { ID = 42 });

            string idLink = entityContext.GenerateSelfLink(includeCast);

            Assert.Equal(expectedIdLink, idLink);
        }
        private EntityInstanceContext(ODataSerializerContext serializerContext, IEdmEntityTypeReference entityType, IEdmStructuredObject edmObject)
        {
            if (serializerContext == null)
            {
                throw Error.ArgumentNull("serializerContext");
            }

            SerializerContext = serializerContext;
            EntityType = entityType.EntityDefinition();
            EdmObject = edmObject;
        }
        public void GenerateNavigationLink_GeneratesExpectedNavigationLink(bool includeCast, string expectedNavigationLink)
        {
            HttpRequestMessage request = GetODataRequest(_model.Model);
            var serializerContext = new ODataSerializerContext { Model = _model.Model, EntitySet = _model.Customers, Url = request.GetUrlHelper() };
            var entityContext = new EntityInstanceContext(serializerContext, _model.SpecialCustomer.AsReference(), new { ID = 42 });
            IEdmNavigationProperty ordersProperty = _model.Customer.NavigationProperties().Single();

            Uri uri = entityContext.GenerateNavigationPropertyLink(ordersProperty, includeCast);

            Assert.Equal(expectedNavigationLink, uri.AbsoluteUri);
        }
示例#30
0
        public void Property_Items_IsInitialized()
        {
            ODataSerializerContext context = new ODataSerializerContext();

            Assert.NotNull(context.Items);
        }
示例#31
0
 /// <summary>
 /// Writes the given object specified by the parameter graph as a whole using the given messageWriter and writeContext.
 /// </summary>
 /// <param name="graph">The object to be written</param>
 /// <param name="type">The type of the object to be written.</param>
 /// <param name="messageWriter">The <see cref="ODataMessageWriter"/> to be used for writing.</param>
 /// <param name="writeContext">The <see cref="ODataSerializerContext"/>.</param>
 public virtual void WriteObject(object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
 {
     throw Error.NotSupported(SRResources.WriteObjectNotSupported, GetType().Name);
 }
示例#32
0
 /// <summary>
 /// Writes the given object specified by the parameter graph as a part of an existing OData message using the given
 /// messageWriter and the writeContext.
 /// </summary>
 /// <param name="graph">The object to be written.</param>
 /// <param name="expectedType">The expected EDM type of the object represented by <paramref name="graph"/>.</param>
 /// <param name="writer">The <see cref="ODataWriter" /> to be used for writing.</param>
 /// <param name="writeContext">The <see cref="ODataSerializerContext"/>.</param>
 public virtual void WriteObjectInline(object graph, IEdmTypeReference expectedType, ODataWriter writer,
                                       ODataSerializerContext writeContext)
 {
     throw Error.NotSupported(SRResources.WriteObjectInlineNotSupported, GetType().Name);
 }
        /// <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 (writeContext.Path == null)
            {
                throw new SerializationException(SRResources.ODataPathMissing);
            }

            IEdmEntitySet entitySet = writeContext.Path.GetEntitySet();

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

            IEdmNavigationProperty navigationProperty = writeContext.Path.GetNavigationProperty();

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

            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
                        })
                    };
                    if (writeContext.Request != null)
                    {
                        entityReferenceLinks.Count = writeContext.Request.ODataProperties().TotalCount;
                    }
                }

                messageWriter.WriteEntityReferenceLinks(entityReferenceLinks, entitySet, navigationProperty);
            }
        }
示例#34
0
        /// <inheritdoc />
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

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

            IEdmEntitySet entitySet = writeContext.EntitySet;

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

            IEdmEntityType entityType = EntityType.EntityDefinition();
            ODataWriter    writer     = messageWriter.CreateODataEntryWriter(entitySet, entityType);

            WriteObjectInline(graph, writer, writeContext);
        }
示例#35
0
        /// <inheritdoc/>
        public override void WriteObject(object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (graph == null)
            {
                throw Error.ArgumentNull("graph");
            }
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            ODataError oDataError = graph as ODataError;

            if (oDataError == null)
            {
                HttpError httpError = graph as HttpError;
                if (httpError == null)
                {
                    string message = Error.Format(SRResources.ErrorTypeMustBeODataErrorOrHttpError, graph.GetType().FullName);
                    throw new SerializationException(message);
                }
                else
                {
                    oDataError = httpError.CreateODataError();
                }
            }

            bool includeDebugInformation = oDataError.InnerError != null;

            messageWriter.WriteError(oDataError, includeDebugInformation);
        }
示例#36
0
        /// <inheritdoc/>
        public override void WriteObject(object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }
            if (graph == null)
            {
                throw Error.ArgumentNull("graph");
            }

            messageWriter.WriteValue(ODataPrimitiveSerializer.ConvertUnsupportedPrimitives(graph));
        }
        /// <inheritdoc/>
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

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

            ODataCollectionWriter writer = messageWriter.CreateODataCollectionWriter();

            writer.WriteStart(
                new ODataCollectionStart
            {
                Name = writeContext.RootElementName
            });

            ODataProperty property = CreateProperty(graph, writeContext.RootElementName, writeContext);

            if (property != null)
            {
                ODataCollectionValue collectionValue = property.Value as ODataCollectionValue;

                foreach (object item in collectionValue.Items)
                {
                    writer.WriteItem(item);
                }

                writer.WriteEnd();
                writer.Flush();
            }
        }
        /// <inheritdoc/>
        public override ODataProperty CreateProperty(object graph, string elementName, ODataSerializerContext writeContext)
        {
            if (String.IsNullOrWhiteSpace(elementName))
            {
                throw Error.ArgumentNullOrEmpty("elementName");
            }

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

            IEnumerable enumerable = graph as IEnumerable;

            if (enumerable == null)
            {
                return(new ODataProperty()
                {
                    Name = elementName, Value = null
                });
            }
            else
            {
                ArrayList valueCollection = new ArrayList();

                IEdmTypeReference itemType       = _edmCollectionType.ElementType();
                ODataSerializer   itemSerializer = SerializerProvider.GetEdmTypeSerializer(itemType);
                if (itemSerializer == null)
                {
                    throw Error.NotSupported(SRResources.TypeCannotBeSerialized, itemType.FullName(), typeof(ODataMediaTypeFormatter).Name);
                }

                foreach (object item in enumerable)
                {
                    valueCollection.Add(itemSerializer.CreateProperty(item, ODataFormatterConstants.Element, writeContext).Value);
                }

                // ODataCollectionValue is only a V3 property, arrays inside Complex Types or Entity types are only supported in V3
                // if a V1 or V2 Client requests a type that has a collection within it ODataLIb will throw.
                // Also, note that TypeName is an optional property for ODataCollectionValue
                return(new ODataProperty()
                {
                    Name = elementName, Value = new ODataCollectionValue {
                        Items = valueCollection
                    }
                });
            }
        }
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            ODataWriter writer = messageWriter.CreateODataFeedWriter();

            WriteObjectInline(graph, writer, writeContext);
            writer.Flush();
        }
示例#40
0
 /// <summary>
 /// Creates an <see cref="ODataValue"/> for the object represented by <paramref name="graph"/>.
 /// </summary>
 /// <param name="graph">The value of the <see cref="ODataValue"/> to be created.</param>
 /// <param name="expectedType">The expected EDM type of the object represented by <paramref name="graph"/>.</param>
 /// <param name="writeContext">The <see cref="ODataSerializerContext"/>.</param>
 /// <returns>The <see cref="ODataValue"/> created.</returns>
 public virtual ODataValue CreateODataValue(object graph, IEdmTypeReference expectedType, ODataSerializerContext writeContext)
 {
     throw Error.NotSupported(SRResources.CreateODataValueNotSupported, GetType().Name);
 }
        /// <inheritdoc/>
        /// <remarks>The metadata written is from the model set on the <paramref name="messageWriter"/>. The <paramref name="graph" />
        /// is not used.</remarks>
        public override void WriteObject(object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            // NOTE: ODataMessageWriter doesn't have a way to set the IEdmModel. So, there is an underlying assumption here that
            // the model received by this method and the model passed(from configuration) while building ODataMessageWriter is the same (clr object).
            messageWriter.WriteMetadataDocument();
        }
示例#42
0
        public override void WriteObject(object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            messageWriter.WriteServiceDocument(graph as ODataWorkspace);
        }