/// <summary>
        /// Deserializes the given <paramref name="complexValue"/> under the given <paramref name="readContext"/>.
        /// </summary>
        /// <param name="complexValue">The complex value to deserialize.</param>
        /// <param name="complexType">The EDM type of the complex value to read.</param>
        /// <param name="readContext">The deserializer context.</param>
        /// <returns>The deserialized complex value.</returns>
        public virtual object ReadComplexValue(ODataComplexValue complexValue, IEdmComplexTypeReference complexType,
            ODataDeserializerContext readContext)
        {
            if (complexValue == null)
            {
                throw Error.ArgumentNull("complexValue");
            }

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

            if (readContext.Model == null)
            {
                throw Error.Argument("readContext", SRResources.ModelMissingFromReadContext);
            }

            object complexResource = CreateResource(complexType, readContext);
            foreach (ODataProperty complexProperty in complexValue.Properties)
            {
                DeserializationHelpers.ApplyProperty(complexProperty, complexType, complexResource, DeserializerProvider, readContext);
            }
            return complexResource;
        }
        public void ReadJsonLight()
        {
            // Arrange
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage requestMessage = new MockODataRequestMessage();
            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings();
            writerSettings.SetContentType(ODataFormat.Json);
            IEdmModel model = CreateModel();
            ODataMessageWriter messageWriter = new ODataMessageWriter(requestMessage, writerSettings, model);
            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink { Url = new Uri("http://localhost/samplelink") });
            ODataMessageReader messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage),
                new ODataMessageReaderSettings(), model);

            IEdmNavigationProperty navigationProperty = GetNavigationProperty(model);

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

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

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
        /// <inheritdoc />
        public sealed override object ReadInline(object item, IEdmTypeReference edmType, ODataDeserializerContext readContext)
        {
            if (item == null)
            {
                throw Error.ArgumentNull("item");
            }
            if (edmType == null)
            {
                throw Error.ArgumentNull("edmType");
            }
            if (!edmType.IsEntity())
            {
                throw Error.Argument("edmType", SRResources.ArgumentMustBeOfType, EdmTypeKind.Entity);
            }

            ODataEntryWithNavigationLinks entryWrapper = item as ODataEntryWithNavigationLinks;
            if (entryWrapper == null)
            {
                throw Error.Argument("item", SRResources.ArgumentMustBeOfType, typeof(ODataEntry).Name);
            }

            // Recursion guard to avoid stack overflows
            RuntimeHelpers.EnsureSufficientExecutionStack();

            return ReadEntry(entryWrapper, edmType.AsEntity(), readContext);
        }
        internal static void ApplyProperty(ODataProperty property, IEdmStructuredTypeReference resourceType, object resource,
            ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)
        {
            IEdmProperty edmProperty = resourceType.FindProperty(property.Name);

            string propertyName = property.Name;
            IEdmTypeReference propertyType = edmProperty != null ? edmProperty.Type : null; // open properties have null values

            EdmTypeKind propertyKind;
            object value = ConvertValue(property.Value, ref propertyType, deserializerProvider, readContext, out propertyKind);

            if (propertyKind == EdmTypeKind.Collection)
            {
                SetCollectionProperty(resource, edmProperty, value);
            }
            else
            {
                if (propertyKind == EdmTypeKind.Primitive && !readContext.IsUntyped)
                {
                    value = EdmPrimitiveHelpers.ConvertPrimitiveValue(value, GetPropertyType(resource, propertyName));
                }

                SetProperty(resource, propertyName, value);
            }
        }
 internal static void RecurseEnter(ODataDeserializerContext readContext)
 {
     if (!readContext.IncrementCurrentReferenceDepth())
     {
         throw Error.InvalidOperation(SRResources.RecursionLimitExceeded);
     }
 }
        /// <inheritdoc />
        public override object Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext readContext)
        {
            if (messageReader == null)
            {
                throw Error.ArgumentNull("messageReader");
            }

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

            IEdmNavigationProperty navigationProperty = GetNavigationProperty(readContext.Path);

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

            ODataEntityReferenceLink entityReferenceLink = messageReader.ReadEntityReferenceLink(navigationProperty);

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

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

            IEdmTypeReference edmType = readContext.GetEdmType(type);
            Contract.Assert(edmType != null);

            if (!edmType.IsCollection())
            {
                throw Error.Argument("type", SRResources.ArgumentMustBeOfType, EdmTypeKind.Collection);
            }

            IEdmCollectionTypeReference collectionType = edmType.AsCollection();
            IEdmTypeReference elementType = collectionType.ElementType();

            IEnumerable result = ReadInline(ReadCollection(messageReader, elementType), edmType, readContext) as IEnumerable;
            if (result != null && readContext.IsUntyped && elementType.IsComplex())
            {
                EdmComplexObjectCollection complexCollection = new EdmComplexObjectCollection(collectionType);
                foreach (EdmComplexObject complexObject in result)
                {
                    complexCollection.Add(complexObject);
                }
                return complexCollection;
            }

            return result;
        }
        internal static void ApplyProperty(ODataProperty property, IEdmStructuredTypeReference resourceType, object resource, ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)
        {
            IEdmProperty edmProperty = resourceType.FindProperty(property.Name);

            string propertyName = property.Name;
            IEdmTypeReference propertyType = edmProperty != null ? edmProperty.Type : null; // open properties have null values

            // If we are in patch mode and we are deserializing an entity object then we are updating Delta<T> and not T.
            bool isDelta = readContext.IsPatchMode && resourceType.IsEntity();

            EdmTypeKind propertyKind;
            object value = ConvertValue(property.Value, ref propertyType, deserializerProvider, readContext, out propertyKind);

            if (propertyKind == EdmTypeKind.Collection)
            {
                SetCollectionProperty(resource, propertyName, isDelta, value);
            }
            else
            {
                if (propertyKind == EdmTypeKind.Primitive)
                {
                    value = EdmPrimitiveHelpers.ConvertPrimitiveValue(value, GetPropertyType(resource, propertyName, isDelta));
                }

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

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

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

            Assert.NotNull(payload);
            Assert.Same(
                model.EntityContainers().Single().FunctionImports().SingleOrDefault(f => f.Name == "Primitive"),
                ODataActionPayloadDeserializer.GetFunctionImport(context));
            Assert.True(payload.ContainsKey("Quantity"));
            Assert.Equal(quantity, payload["Quantity"]);
            Assert.True(payload.ContainsKey("ProductCode"));
            Assert.Equal(productCode, payload["ProductCode"]);
        }
        /// <inheritdoc />
        public sealed override object ReadInline(object item, IEdmTypeReference edmType, ODataDeserializerContext readContext)
        {
            if (readContext == null)
            {
                throw Error.ArgumentNull("readContext");
            }

            if (item == null)
            {
                return null;
            }

            ODataComplexValue complexValue = item as ODataComplexValue;
            if (complexValue == null)
            {
                throw Error.Argument("item", SRResources.ArgumentMustBeOfType, typeof(ODataComplexValue).Name);
            }

            if (!edmType.IsComplex())
            {
                throw Error.Argument("edmType", SRResources.ArgumentMustBeOfType, EdmTypeKind.Complex);
            }

            // Recursion guard to avoid stack overflows
            RuntimeHelpers.EnsureSufficientExecutionStack();

            return ReadComplexValue(complexValue, edmType.AsComplex(), readContext);
        }
        /// <inheritdoc />
        public sealed override object ReadInline(object item, IEdmTypeReference edmType, ODataDeserializerContext readContext)
        {
            if (item == null)
            {
                return null;
            }
            if (edmType == null)
            {
                throw Error.ArgumentNull("edmType");
            }
            if (!edmType.IsCollection() || !edmType.AsCollection().ElementType().IsEntity())
            {
                throw Error.Argument("edmType", SRResources.TypeMustBeEntityCollection, edmType.ToTraceString(), typeof(IEdmEntityType).Name);
            }

            IEdmEntityTypeReference elementType = edmType.AsCollection().ElementType().AsEntity();

            ODataFeedWithEntries feed = item as ODataFeedWithEntries;
            if (feed == null)
            {
                throw Error.Argument("item", SRResources.ArgumentMustBeOfType, typeof(ODataFeedWithEntries).Name);
            }

            // Recursion guard to avoid stack overflows
            RuntimeHelpers.EnsureSufficientExecutionStack();

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

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

            if (readContext.Path == null)
            {
                throw Error.Argument("readContext", SRResources.ODataPathMissing);
            }

            IEdmEntitySet entitySet = GetEntitySet(readContext.Path);

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

            ODataReader odataReader = messageReader.CreateODataEntryReader(entitySet, EntityType.EntityDefinition());
            ODataEntryWithNavigationLinks topLevelEntry = ReadEntryOrFeed(odataReader) as ODataEntryWithNavigationLinks;
            Contract.Assert(topLevelEntry != null);

            return ReadInline(topLevelEntry, readContext);
        }
 public void Can_find_action(string actionName, string url)
 {
     ODataDeserializerContext context = new ODataDeserializerContext { Request = GetPostRequest(url), Model = GetModel() };
     IEdmFunctionImport action = new ODataActionParameters().GetFunctionImport(context);
     Assert.NotNull(action);
     Assert.Equal(actionName, action.Name);
 }
        /// <summary>
        /// Deserializes the given <paramref name="collectionValue"/> under the given <paramref name="readContext"/>.
        /// </summary>
        /// <param name="collectionValue">The <see cref="ODataCollectionValue"/> to deserialize.</param>
        /// <param name="readContext">The deserializer context.</param>
        /// <returns>The deserialized collection.</returns>
        public virtual IEnumerable ReadCollectionValue(ODataCollectionValue collectionValue, ODataDeserializerContext readContext)
        {
            if (collectionValue == null)
            {
                throw Error.ArgumentNull("collectionValue");
            }

            ODataEdmTypeDeserializer deserializer = DeserializerProvider.GetEdmTypeDeserializer(ElementType);
            if (deserializer == null)
            {
                throw new SerializationException(
                    Error.Format(SRResources.TypeCannotBeDeserialized, ElementType.FullName(), typeof(ODataMediaTypeFormatter).Name));
            }

            foreach (object entry in collectionValue.Items)
            {
                if (ElementType.IsPrimitive())
                {
                    yield return entry;
                }
                else
                {
                    yield return deserializer.ReadInline(entry, readContext);
                }
            }
        }
        public void Can_deserialize_payload_with_complex_parameters()
        {
            string actionName = "Complex";
            string body = @"{ ""Quantity"": 1 , ""Address"": { ""StreetAddress"":""1 Microsoft Way"", ""City"": ""Redmond"", ""State"": ""WA"", ""ZipCode"": 98052 } }";

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

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

            Assert.NotNull(payload);
            Assert.Same(model.EntityContainers().Single().FunctionImports().SingleOrDefault(f => f.Name == "Complex"), payload.GetFunctionImport(context));
            Assert.True(payload.ContainsKey("Quantity"));
            Assert.Equal(1, payload["Quantity"]);
            Assert.True(payload.ContainsKey("Address"));
            MyAddress address = payload["Address"] as MyAddress;
            Assert.NotNull(address);
            Assert.Equal("1 Microsoft Way", address.StreetAddress);
            Assert.Equal("Redmond", address.City);
            Assert.Equal("WA", address.State);
            Assert.Equal(98052, address.ZipCode);
        }
        /// <inheritdoc />
        public sealed override object ReadInline(object item, IEdmTypeReference edmType, ODataDeserializerContext readContext)
        {
            if (item == null)
            {
                return null;
            }
            if (edmType == null)
            {
                throw Error.ArgumentNull("edmType");
            }

            if (!edmType.IsCollection())
            {
                throw new SerializationException(
                    Error.Format(SRResources.TypeCannotBeDeserialized, edmType.ToTraceString(), typeof(ODataMediaTypeFormatter)));
            }

            IEdmCollectionTypeReference collectionType = edmType.AsCollection();
            IEdmTypeReference elementType = collectionType.ElementType();

            ODataCollectionValue collection = item as ODataCollectionValue;

            if (collection == null)
            {
                throw Error.Argument("item", SRResources.ArgumentMustBeOfType, typeof(ODataCollectionValue).Name);
            }

            // Recursion guard to avoid stack overflows
            RuntimeHelpers.EnsureSufficientExecutionStack();

            return ReadCollectionValue(collection, elementType, readContext);
        }
 public void Can_find_action(string actionName, string url)
 {
     IODataActionResolver resolver = new DefaultODataActionResolver();
     ODataDeserializerContext context = new ODataDeserializerContext { Request = GetPostRequest(url), Model = GetModel() };
     IEdmFunctionImport action = resolver.Resolve(context);
     Assert.NotNull(action);
     Assert.Equal(actionName, action.Name);
 }
 public void Throws_Serialization_WhenPathNotFound()
 {
     ODataDeserializerContext context = new ODataDeserializerContext { Path = null };
     Assert.Throws<SerializationException>(() =>
     {
         IEdmFunctionImport action = ODataActionPayloadDeserializer.GetFunctionImport(context);
     }, "The operation cannot be completed because no ODataPath is available for the request.");
 }
 public void Throws_InvalidOperation_when_action_not_found()
 {
     ODataDeserializerContext context = new ODataDeserializerContext { Request = GetPostRequest("http://server/service/MissingOperation"), Model = GetModel() };
     Assert.Throws<InvalidOperationException>(() =>
     {
         IEdmFunctionImport action = new ODataActionParameters().GetFunctionImport(context);
     }, "The request URI 'http://server/service/MissingOperation' was not recognized as an OData path.");
 }
 public void Throws_InvalidOperation_when_multiple_overloads_found()
 {
     ODataDeserializerContext context = new ODataDeserializerContext { Request = GetPostRequest("http://server/service/Vehicles/System.Web.Http.OData.Builder.TestModels.Car(8)/Park"), Model = GetModel() };
     InvalidOperationException ioe = Assert.Throws<InvalidOperationException>(() =>
     {
         IEdmFunctionImport action = new ODataActionParameters().GetFunctionImport(context);
     }, "Action resolution failed. Multiple actions matching the action identifier 'Park' were found. The matching actions are: org.odata.Container.Park, org.odata.Container.Park.");
 }
 public void Throws_InvalidOperation_when_action_not_found()
 {
     IODataActionResolver resolver = new DefaultODataActionResolver();
     ODataDeserializerContext context = new ODataDeserializerContext { Request = GetPostRequest("http://server/service/MissingOperation"), Model = GetModel() };
     Assert.Throws<InvalidOperationException>(() =>
     {
         IEdmFunctionImport action = resolver.Resolve(context);
     },  "Action 'MissingOperation' was not found for RequestUri 'http://server/service/MissingOperation'.");
 }
 public void Throws_InvalidOperation_when_multiple_overloads_found()
 {
     IODataActionResolver resolver = new DefaultODataActionResolver();
     ODataDeserializerContext context = new ODataDeserializerContext { Request = GetPostRequest("http://server/service/Vehicles/Container.Car(8)/Park"), Model = GetModel() };
     InvalidOperationException ioe = Assert.Throws<InvalidOperationException>(() =>
     {
         IEdmFunctionImport action = resolver.Resolve(context);
     }, "Action resolution failed. Multiple actions matching the action identifier 'Park' were found. The matching actions are: org.odata.Container.Park, org.odata.Container.Park.");
 }
        /// <summary>
        /// Deserializes the primitive from the given <paramref name="primitiveProperty"/> under the given <paramref name="readContext"/>.
        /// </summary>
        /// <param name="primitiveProperty">The primitive property to deserialize.</param>
        /// <param name="readContext">The deserializer context.</param>
        /// <returns>The deserialized OData primitive value.</returns>
        public virtual object ReadPrimitive(ODataProperty primitiveProperty, ODataDeserializerContext readContext)
        {
            if (primitiveProperty == null)
            {
                throw Error.ArgumentNull("primitiveProperty");
            }

            return primitiveProperty.Value;
        }
 public void Can_find_action(string actionName, string url)
 {
     IEdmModel model = GetModel();
     ODataPath path = new DefaultODataPathHandler().Parse(model, url);
     Assert.NotNull(path); // Guard
     ODataDeserializerContext context = new ODataDeserializerContext { Path = path, Model = model };
     IEdmFunctionImport action = ODataActionPayloadDeserializer.GetFunctionImport(context);
     Assert.NotNull(action);
     Assert.Equal(actionName, action.Name);
 }
        /// <inheritdoc />
        public override object Read(ODataMessageReader messageReader, ODataDeserializerContext readContext)
        {
            if (messageReader == null)
            {
                throw Error.ArgumentNull("messageReader");
            }

            ODataCollectionValue value = ReadCollection(messageReader);
            return ReadInline(value, readContext);
        }
        /// <inheritdoc />
        public override object Read(ODataMessageReader messageReader, ODataDeserializerContext readContext)
        {
            if (messageReader == null)
            {
                throw Error.ArgumentNull("messageReader");
            }

            ODataProperty property = messageReader.ReadProperty();
            return ReadInline(property, readContext);
        }
        public void ReadThrowsWhenPathIsMissing()
        {
            // Arrange
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            ODataMessageReader reader = new ODataMessageReader(new MockODataRequestMessage());
            ODataDeserializerContext context = new ODataDeserializerContext();

            // Act & Assert
            Assert.Throws<SerializationException>(() => deserializer.Read(reader, context),
                "The operation cannot be completed because no ODataPath is available for the request.");
        }
        public void Can_find_action_overload_using_bindingparameter_type()
        {
            string url = "http://server/service/Vehicles(8)/System.Web.Http.OData.Builder.TestModels.Car/Wash";
            ODataDeserializerContext context = new ODataDeserializerContext { Request = GetPostRequest(url), Model = GetModel() };

            IEdmFunctionImport action = new ODataActionParameters().GetFunctionImport(context);

            Assert.NotNull(action);
            Assert.Equal("Wash", action.Name);

        }
 private object Convert(object value, IEdmTypeReference parameterType, ODataDeserializerContext readContext)
 {
     if (parameterType.IsPrimitive())
     {
         return value;
     }
     else
     {
         ODataEntryDeserializer deserializer = _provider.GetODataDeserializer(parameterType);
         return deserializer.ReadInline(value, readContext);
     }
 }
 public ODataEntityDeserializerTests()
 {
     _edmModel = EdmTestHelpers.GetModel();
     IEdmEntitySet entitySet = _edmModel.EntityContainers().Single().FindEntitySet("Products");
     _readContext = new ODataDeserializerContext
     {
         Path = new ODataPath(new EntitySetPathSegment(entitySet)),
         Model = _edmModel
     };
     _productEdmType = _edmModel.GetEdmTypeReference(typeof(Product)).AsEntity();
     _supplierEdmType = _edmModel.GetEdmTypeReference(typeof(Supplier)).AsEntity();
     _deserializerProvider = new DefaultODataDeserializerProvider();
 }
        private static object ConvertComplexValue(ODataComplexValue complexValue, ref IEdmTypeReference propertyType, ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)
        {
            IEdmComplexTypeReference edmComplexType;

            if (propertyType == null)
            {
                // open complex property
                Contract.Assert(!String.IsNullOrEmpty(complexValue.TypeName), "ODataLib should have verified that open complex value has a type name since we provided metadata.");
                IEdmType edmType = deserializerProvider.EdmModel.FindType(complexValue.TypeName);
                Contract.Assert(edmType.TypeKind == EdmTypeKind.Complex, "ODataLib should have verified that complex value has a complex resource type.");
                edmComplexType = new EdmComplexTypeReference(edmType as IEdmComplexType, isNullable: true);
            }
            else
            {
                edmComplexType = propertyType.AsComplex();
            }

            ODataEntryDeserializer deserializer = deserializerProvider.GetODataDeserializer(edmComplexType);

            return(deserializer.ReadInline(complexValue, readContext));
        }
        private void ApplyEntryInNavigationProperty(IEdmNavigationProperty navigationProperty, object entityResource, ODataEntry entry, ODataDeserializerContext readContext)
        {
            Contract.Assert(navigationProperty != null && navigationProperty.PropertyKind == EdmPropertyKind.Navigation, "navigationProperty != null && navigationProperty.TypeKind == ResourceTypeKind.EntityType");
            Contract.Assert(entityResource != null, "entityResource != null");

            ODataEntryDeserializer deserializer = DeserializerProvider.GetODataDeserializer(navigationProperty.Type);
            object value = deserializer.ReadInline(entry, readContext);

            if (readContext.IsPatchMode)
            {
                throw Error.InvalidOperation(SRResources.CannotPatchNavigationProperties, navigationProperty.Name, navigationProperty.DeclaringEntityType().FullName());
            }

            SetProperty(entityResource, navigationProperty.Name, isDelta: false, value: value);
        }
        /// <summary>
        /// Deserializes the structural properties from <paramref name="entryWrapper"/> into <paramref name="entityResource"/>.
        /// </summary>
        /// <param name="entityResource">The object into which the structural properties should be read.</param>
        /// <param name="entryWrapper">The entry object containing the structural properties.</param>
        /// <param name="entityType">The entity type of the entity resource.</param>
        /// <param name="readContext">The deserializer context.</param>
        public virtual void ApplyStructuralProperties(object entityResource, ODataEntryWithNavigationLinks entryWrapper,
                                                      IEdmEntityTypeReference entityType, ODataDeserializerContext readContext)
        {
            if (entryWrapper == null)
            {
                throw Error.ArgumentNull("entryWrapper");
            }

            foreach (ODataProperty property in entryWrapper.Entry.Properties)
            {
                ApplyStructuralProperty(entityResource, property, entityType, readContext);
            }
        }
        /// <summary>
        /// Deserializes the given <paramref name="structuralProperty"/> into <paramref name="entityResource"/>.
        /// </summary>
        /// <param name="entityResource">The object into which the structural property should be read.</param>
        /// <param name="structuralProperty">The entry object containing the structural properties.</param>
        /// <param name="entityType">The entity type of the entity resource.</param>
        /// <param name="readContext">The deserializer context.</param>
        public virtual void ApplyStructuralProperty(object entityResource, ODataProperty structuralProperty,
                                                    IEdmEntityTypeReference entityType, ODataDeserializerContext readContext)
        {
            if (entityResource == null)
            {
                throw Error.ArgumentNull("entityResource");
            }

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

            DeserializationHelpers.ApplyProperty(structuralProperty, entityType, entityResource, DeserializerProvider, readContext);
        }
 private void ApplyValueProperties(ODataEntry entry, IEdmStructuredTypeReference entityType, object entityResource, ODataDeserializerContext readContext)
 {
     foreach (ODataProperty property in entry.Properties)
     {
         ApplyProperty(property, entityType, entityResource, DeserializerProvider, readContext);
     }
 }
Exemplo n.º 36
0
        internal static void ApplyProperty(ODataProperty property, IEdmStructuredTypeReference resourceType, object resource,
                                           ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)
        {
            IEdmProperty edmProperty = resourceType.FindProperty(property.Name);

            string            propertyName = property.Name;
            IEdmTypeReference propertyType = edmProperty != null ? edmProperty.Type : null; // open properties have null values

            EdmTypeKind propertyKind;
            object      value = ConvertValue(property.Value, ref propertyType, deserializerProvider, readContext, out propertyKind);

            if (propertyKind == EdmTypeKind.Collection)
            {
                SetCollectionProperty(resource, edmProperty, value);
            }
            else
            {
                if (propertyKind == EdmTypeKind.Primitive && !readContext.IsUntyped)
                {
                    value = EdmPrimitiveHelpers.ConvertPrimitiveValue(value, GetPropertyType(resource, propertyName));
                }

                SetProperty(resource, propertyName, value);
            }
        }
Exemplo n.º 37
0
        /// <inheritdoc />
        public sealed override object ReadInline(object item, IEdmTypeReference edmType, ODataDeserializerContext readContext)
        {
            if (item == null)
            {
                return(null);
            }
            if (edmType == null)
            {
                throw Error.ArgumentNull("edmType");
            }
            if (!edmType.IsCollection() || !edmType.AsCollection().ElementType().IsEntity())
            {
                throw Error.Argument("edmType", SRResources.TypeMustBeEntityCollection, edmType.ToTraceString(), typeof(IEdmEntityType).Name);
            }

            IEdmEntityTypeReference elementType = edmType.AsCollection().ElementType().AsEntity();

            ODataFeedWithEntries feed = item as ODataFeedWithEntries;

            if (feed == null)
            {
                throw Error.Argument("item", SRResources.ArgumentMustBeOfType, typeof(ODataFeedWithEntries).Name);
            }

            // Recursion guard to avoid stack overflows
            RuntimeHelpers.EnsureSufficientExecutionStack();

            return(ReadFeed(feed, elementType, readContext));
        }
        /// <inheritdoc />
        public sealed override object ReadInline(object item, IEdmTypeReference edmType, ODataDeserializerContext readContext)
        {
            if (readContext == null)
            {
                throw Error.ArgumentNull("readContext");
            }

            if (item == null)
            {
                return(null);
            }

            ODataComplexValue complexValue = item as ODataComplexValue;

            if (complexValue == null)
            {
                throw Error.Argument("item", SRResources.ArgumentMustBeOfType, typeof(ODataComplexValue).Name);
            }

            if (!edmType.IsComplex())
            {
                throw Error.Argument("edmType", SRResources.ArgumentMustBeOfType, EdmTypeKind.Complex);
            }

            // Recursion guard to avoid stack overflows
            RuntimeHelpers.EnsureSufficientExecutionStack();

            return(ReadComplexValue(complexValue, edmType.AsComplex(), readContext));
        }
        /// <inheritdoc />
        public sealed override object ReadInline(object item, IEdmTypeReference edmType, ODataDeserializerContext readContext)
        {
            if (item == null)
            {
                return(null);
            }
            if (edmType == null)
            {
                throw Error.ArgumentNull("edmType");
            }

            if (!edmType.IsCollection())
            {
                throw new SerializationException(
                          Error.Format(SRResources.TypeCannotBeDeserialized, edmType.ToTraceString(), typeof(ODataMediaTypeFormatter)));
            }

            IEdmCollectionTypeReference collectionType = edmType.AsCollection();
            IEdmTypeReference           elementType    = collectionType.ElementType();

            ODataCollectionValue collection = item as ODataCollectionValue;

            if (collection == null)
            {
                throw Error.Argument("item", SRResources.ArgumentMustBeOfType, typeof(ODataCollectionValue).Name);
            }
            // Recursion guard to avoid stack overflows
            RuntimeHelpers.EnsureSufficientExecutionStack();

            IEnumerable result = ReadCollectionValue(collection, elementType, readContext);

            if (result != null)
            {
                if (readContext.IsUntyped && elementType.IsComplex())
                {
                    EdmComplexObjectCollection complexCollection = new EdmComplexObjectCollection(collectionType);
                    foreach (EdmComplexObject complexObject in result)
                    {
                        complexCollection.Add(complexObject);
                    }
                    return(complexCollection);
                }
                else
                {
                    Type        elementClrType = EdmLibHelpers.GetClrType(elementType, readContext.Model);
                    IEnumerable castedResult   = _castMethodInfo.MakeGenericMethod(elementClrType).Invoke(null, new object[] { result }) as IEnumerable;
                    return(castedResult);
                }
            }
            return(null);
        }
        internal static object ConvertValue(object oDataValue, ref IEdmTypeReference propertyType, ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext, out EdmTypeKind typeKind)
        {
            if (oDataValue == null)
            {
                typeKind = EdmTypeKind.None;
                return(null);
            }

            ODataComplexValue complexValue = oDataValue as ODataComplexValue;

            if (complexValue != null)
            {
                typeKind = EdmTypeKind.Complex;
                return(ConvertComplexValue(complexValue, ref propertyType, deserializerProvider, readContext));
            }

            ODataCollectionValue collection = oDataValue as ODataCollectionValue;

            if (collection != null)
            {
                typeKind = EdmTypeKind.Collection;
                Contract.Assert(propertyType != null, "Open collection properties are not supported.");
                return(ConvertCollectionValue(collection, propertyType, deserializerProvider, readContext));
            }

            typeKind = EdmTypeKind.Primitive;
            return(ConvertPrimitiveValue(oDataValue, ref propertyType));
        }
        internal static void ApplyProperty(ODataProperty property, IEdmStructuredTypeReference resourceType, object resource, ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)
        {
            IEdmProperty edmProperty = resourceType.FindProperty(property.Name);

            string            propertyName = property.Name;
            IEdmTypeReference propertyType = edmProperty != null ? edmProperty.Type : null; // open properties have null values

            bool isDelta = readContext.IsPatchMode && resourceType.IsEntity();

            if (isDelta && resourceType.AsEntity().Key().Select(key => key.Name).Contains(propertyName))
            {
                // we are patching a key property.
                if (readContext.PatchKeyMode == PatchKeyMode.Ignore)
                {
                    return;
                }
                else if (readContext.PatchKeyMode == PatchKeyMode.Throw)
                {
                    throw Error.InvalidOperation(SRResources.CannotPatchKeyProperty, propertyName, resourceType.FullName(), typeof(PatchKeyMode).Name, PatchKeyMode.Throw);
                }
            }

            EdmTypeKind propertyKind;
            object      value = ConvertValue(property.Value, ref propertyType, deserializerProvider, readContext, out propertyKind);

            if (propertyKind == EdmTypeKind.Primitive)
            {
                value = ConvertPrimitiveValue(value, GetPropertyType(resource, propertyName, isDelta), propertyName, resource.GetType().FullName);
            }

            SetProperty(resource, propertyName, isDelta, value);
        }
        /// <inheritdoc />
        public sealed override object ReadInline(object item, IEdmTypeReference edmType, ODataDeserializerContext readContext)
        {
            if (item == null)
            {
                throw Error.ArgumentNull("item");
            }
            if (edmType == null)
            {
                throw Error.ArgumentNull("edmType");
            }
            if (!edmType.IsEntity())
            {
                throw Error.Argument("edmType", SRResources.ArgumentMustBeOfType, EdmTypeKind.Entity);
            }

            ODataEntryWithNavigationLinks entryWrapper = item as ODataEntryWithNavigationLinks;

            if (entryWrapper == null)
            {
                throw Error.Argument("item", SRResources.ArgumentMustBeOfType, typeof(ODataEntry).Name);
            }

            // Recursion guard to avoid stack overflows
            RuntimeHelpers.EnsureSufficientExecutionStack();

            return(ReadEntry(entryWrapper, edmType.AsEntity(), readContext));
        }
        private void ApplyNavigationProperty(ODataNavigationLink navigationLink, IEdmNavigationProperty navigationProperty, object entityResource, ODataDeserializerContext readContext)
        {
            ODataNavigationLinkAnnotation navigationLinkAnnotation = navigationLink.GetAnnotation <ODataNavigationLinkAnnotation>();

            Contract.Assert(navigationLinkAnnotation != null, "navigationLinkAnnotation != null");
            Contract.Assert(navigationLink.IsCollection.HasValue, "We should know the cardinality of the navigation link by now.");

            foreach (ODataItem childItem in navigationLinkAnnotation)
            {
                ODataEntityReferenceLink entityReferenceLink = childItem as ODataEntityReferenceLink;
                if (entityReferenceLink != null)
                {
                    // ignore links.
                    continue;
                }

                ODataFeed feed = childItem as ODataFeed;
                if (feed != null)
                {
                    ApplyFeedInNavigationProperty(navigationProperty, entityResource, feed, readContext);
                    continue;
                }

                // It must be entry by now.
                ODataEntry entry = (ODataEntry)childItem;
                if (entry != null)
                {
                    ApplyEntryInNavigationProperty(navigationProperty, entityResource, entry, readContext);
                }
            }
        }
        /// <summary>
        /// Deserializes the navigation properties from <paramref name="entryWrapper"/> into <paramref name="entityResource"/>.
        /// </summary>
        /// <param name="entityResource">The object into which the navigation properties should be read.</param>
        /// <param name="entryWrapper">The entry object containing the navigation properties.</param>
        /// <param name="entityType">The entity type of the entity resource.</param>
        /// <param name="readContext">The deserializer context.</param>
        public virtual void ApplyNavigationProperties(object entityResource, ODataEntryWithNavigationLinks entryWrapper,
                                                      IEdmEntityTypeReference entityType, ODataDeserializerContext readContext)
        {
            if (entryWrapper == null)
            {
                throw Error.ArgumentNull("entryWrapper");
            }

            foreach (ODataNavigationLinkWithItems navigationLink in entryWrapper.NavigationLinks)
            {
                ApplyNavigationProperty(entityResource, navigationLink, entityType, readContext);
            }
        }
Exemplo n.º 45
0
 /// <summary>
 /// Reads an <see cref="IODataRequestMessage"/> using messageReader.
 /// </summary>
 /// <param name="messageReader">The messageReader to use.</param>
 /// <param name="readContext">The read context.</param>
 /// <returns>The deserialized object.</returns>
 public virtual object Read(ODataMessageReader messageReader, ODataDeserializerContext readContext)
 {
     throw Error.NotSupported(SRResources.DeserializerDoesNotSupportRead, GetType().Name);
 }
        private static object ConvertCollectionValue(ODataCollectionValue collection, IEdmTypeReference propertyType, ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)
        {
            IEdmCollectionTypeReference collectionType = propertyType as IEdmCollectionTypeReference;

            Contract.Assert(collectionType != null, "The type for collection must be a IEdmCollectionType.");

            IList collectionList = CreateNewCollection(EdmLibHelpers.GetClrType(collectionType.ElementType(), deserializerProvider.EdmModel));

            RecurseEnter(readContext);

            Contract.Assert(collection.Items != null, "The ODataLib reader should always populate the ODataCollectionValue.Items collection.");
            foreach (object odataItem in collection.Items)
            {
                IEdmTypeReference itemType = collectionType.ElementType();
                EdmTypeKind       propertyKind;
                collectionList.Add(ConvertValue(odataItem, ref itemType, deserializerProvider, readContext, out propertyKind));
                Contract.Assert(propertyKind != EdmTypeKind.Primitive, "no collection property support yet.");
            }

            RecurseLeave(readContext);

            return(collectionList);
        }
Exemplo n.º 47
0
        private static object ConvertCollectionValue(ODataCollectionValue collection, IEdmTypeReference propertyType,
                                                     ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)
        {
            IEdmCollectionTypeReference collectionType = propertyType as IEdmCollectionTypeReference;

            Contract.Assert(collectionType != null, "The type for collection must be a IEdmCollectionType.");

            ODataEdmTypeDeserializer deserializer = deserializerProvider.GetEdmTypeDeserializer(collectionType);

            return(deserializer.ReadInline(collection, collectionType, readContext));
        }
 /// <summary>
 /// Deserializes the item into a new object of type corresponding to <see cref="EdmType"/>.
 /// </summary>
 /// <param name="item">The item to deserialize.</param>
 /// <param name="readContext">The <see cref="ODataDeserializerContext"/></param>
 /// <returns>The deserialized object.</returns>
 public virtual object ReadInline(object item, ODataDeserializerContext readContext)
 {
     throw Error.NotSupported(SRResources.DoesNotSupportReadInLine, GetType().Name);
 }
Exemplo n.º 49
0
        /// <summary>
        /// Deserializes the given <paramref name="feed"/> under the given <paramref name="readContext"/>.
        /// </summary>
        /// <param name="feed">The feed to deserialize.</param>
        /// <param name="readContext">The deserializer context.</param>
        /// <param name="elementType">The element type of the feed being read.</param>
        /// <returns>The deserialized feed object.</returns>
        public virtual IEnumerable ReadFeed(ODataFeedWithEntries feed, IEdmEntityTypeReference elementType, ODataDeserializerContext readContext)
        {
            ODataEdmTypeDeserializer deserializer = DeserializerProvider.GetEdmTypeDeserializer(elementType);

            if (deserializer == null)
            {
                throw new SerializationException(
                          Error.Format(SRResources.TypeCannotBeDeserialized, elementType.FullName(), typeof(ODataMediaTypeFormatter).Name));
            }

            foreach (ODataEntryWithNavigationLinks entry in feed.Entries)
            {
                yield return(deserializer.ReadInline(entry, elementType, readContext));
            }
        }
 internal static void RecurseLeave(ODataDeserializerContext readContext)
 {
     readContext.DecrementCurrentReferenceDepth();
 }
        /// <inheritdoc />
        public sealed override object ReadInline(object item, IEdmTypeReference edmType, ODataDeserializerContext readContext)
        {
            if (item == null)
            {
                return(null);
            }
            if (edmType == null)
            {
                throw Error.ArgumentNull("edmType");
            }

            if (!edmType.IsCollection())
            {
                throw new SerializationException(
                          Error.Format(SRResources.TypeCannotBeDeserialized, edmType.ToTraceString(), typeof(ODataMediaTypeFormatter)));
            }

            IEdmCollectionTypeReference collectionType = edmType.AsCollection();
            IEdmTypeReference           elementType    = collectionType.ElementType();

            ODataCollectionValue collection = item as ODataCollectionValue;

            if (collection == null)
            {
                throw Error.Argument("item", SRResources.ArgumentMustBeOfType, typeof(ODataCollectionValue).Name);
            }

            // Recursion guard to avoid stack overflows
            RuntimeHelpers.EnsureSufficientExecutionStack();

            return(ReadCollectionValue(collection, elementType, readContext));
        }
        /// <summary>
        /// Creates a new instance of the backing CLR object for the given entity type.
        /// </summary>
        /// <param name="entityType">The EDM type of the entity to create.</param>
        /// <param name="readContext">The deserializer context.</param>
        /// <returns>The created CLR object.</returns>
        public virtual object CreateEntityResource(IEdmEntityTypeReference entityType, ODataDeserializerContext readContext)
        {
            if (readContext == null)
            {
                throw Error.ArgumentNull("readContext");
            }
            if (entityType == null)
            {
                throw Error.ArgumentNull("entityType");
            }

            IEdmModel model = readContext.Model;

            if (model == null)
            {
                throw Error.Argument("readContext", SRResources.ModelMissingFromReadContext);
            }

            if (readContext.IsUntyped)
            {
                return(new EdmEntityObject(entityType));
            }
            else
            {
                Type clrType = EdmLibHelpers.GetClrType(entityType, model);
                if (clrType == null)
                {
                    throw new ODataException(
                              Error.Format(SRResources.MappingDoesNotContainEntityType, entityType.FullName()));
                }

                if (readContext.IsDeltaOfT)
                {
                    IEnumerable <string> structuralProperties = entityType.StructuralProperties().Select(p => p.Name);
                    return(Activator.CreateInstance(readContext.ResourceType, clrType, structuralProperties));
                }
                else
                {
                    return(Activator.CreateInstance(clrType));
                }
            }
        }
        internal static ODataItem ReadEntryOrFeed(ODataReader odataReader, ODataDeserializerContext readContext)
        {
            ODataItem         topLevelItem = null;
            Stack <ODataItem> itemsStack   = new Stack <ODataItem>();

            while (odataReader.Read())
            {
                switch (odataReader.State)
                {
                case ODataReaderState.EntryStart:
                    ODataEntry           entry           = (ODataEntry)odataReader.Item;
                    ODataEntryAnnotation entryAnnotation = null;
                    if (entry != null)
                    {
                        entryAnnotation = new ODataEntryAnnotation();
                        entry.SetAnnotation(entryAnnotation);
                    }

                    if (itemsStack.Count == 0)
                    {
                        Contract.Assert(entry != null, "The top-level entry can never be null.");
                        topLevelItem = entry;
                    }
                    else
                    {
                        ODataItem parentItem = itemsStack.Peek();
                        ODataFeed parentFeed = parentItem as ODataFeed;
                        if (parentFeed != null)
                        {
                            ODataFeedAnnotation parentFeedAnnotation = parentFeed.GetAnnotation <ODataFeedAnnotation>();
                            Contract.Assert(parentFeedAnnotation != null, "Every feed we added to the stack should have the feed annotation on it.");
                            parentFeedAnnotation.Add(entry);
                        }
                        else
                        {
                            ODataNavigationLink           parentNavigationLink           = (ODataNavigationLink)parentItem;
                            ODataNavigationLinkAnnotation parentNavigationLinkAnnotation = parentNavigationLink.GetAnnotation <ODataNavigationLinkAnnotation>();
                            Contract.Assert(parentNavigationLinkAnnotation != null, "Every navigation link we added to the stack should have the navigation link annotation on it.");

                            Contract.Assert(parentNavigationLink.IsCollection == false, "Only singleton navigation properties can contain entry as their child.");
                            Contract.Assert(parentNavigationLinkAnnotation.Count == 0, "Each navigation property can contain only one entry as its direct child.");
                            parentNavigationLinkAnnotation.Add(entry);
                        }
                    }
                    itemsStack.Push(entry);
                    RecurseEnter(readContext);
                    break;

                case ODataReaderState.EntryEnd:
                    Contract.Assert(itemsStack.Count > 0 && itemsStack.Peek() == odataReader.Item, "The entry which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    RecurseLeave(readContext);
                    break;

                case ODataReaderState.NavigationLinkStart:
                    ODataNavigationLink navigationLink = (ODataNavigationLink)odataReader.Item;
                    Contract.Assert(navigationLink != null, "Navigation link should never be null.");

                    navigationLink.SetAnnotation(new ODataNavigationLinkAnnotation());
                    Contract.Assert(itemsStack.Count > 0, "Navigation link can't appear as top-level item.");
                    {
                        ODataEntry           parentEntry           = (ODataEntry)itemsStack.Peek();
                        ODataEntryAnnotation parentEntryAnnotation = parentEntry.GetAnnotation <ODataEntryAnnotation>();
                        Contract.Assert(parentEntryAnnotation != null, "Every entry we added to the stack should have the entry annotation on it.");
                        parentEntryAnnotation.Add(navigationLink);
                    }

                    itemsStack.Push(navigationLink);
                    RecurseEnter(readContext);
                    break;

                case ODataReaderState.NavigationLinkEnd:
                    Contract.Assert(itemsStack.Count > 0 && itemsStack.Peek() == odataReader.Item, "The navigation link which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    RecurseLeave(readContext);
                    break;

                case ODataReaderState.FeedStart:
                    ODataFeed feed = (ODataFeed)odataReader.Item;
                    Contract.Assert(feed != null, "Feed should never be null.");

                    feed.SetAnnotation(new ODataFeedAnnotation());
                    if (itemsStack.Count > 0)
                    {
                        ODataNavigationLink parentNavigationLink = (ODataNavigationLink)itemsStack.Peek();
                        Contract.Assert(parentNavigationLink != null, "this has to be an inner feed. inner feeds always have a navigation link.");
                        ODataNavigationLinkAnnotation parentNavigationLinkAnnotation = parentNavigationLink.GetAnnotation <ODataNavigationLinkAnnotation>();
                        Contract.Assert(parentNavigationLinkAnnotation != null, "Every navigation link we added to the stack should have the navigation link annotation on it.");

                        Contract.Assert(parentNavigationLink.IsCollection == true, "Only collection navigation properties can contain feed as their child.");
                        parentNavigationLinkAnnotation.Add(feed);
                    }
                    else
                    {
                        topLevelItem = feed;
                    }

                    itemsStack.Push(feed);
                    RecurseEnter(readContext);
                    break;

                case ODataReaderState.FeedEnd:
                    Contract.Assert(itemsStack.Count > 0 && itemsStack.Peek() == odataReader.Item, "The feed which is ending should be on the top of the items stack.");
                    itemsStack.Pop();
                    RecurseLeave(readContext);
                    break;

                case ODataReaderState.EntityReferenceLink:
                    ODataEntityReferenceLink entityReferenceLink = (ODataEntityReferenceLink)odataReader.Item;
                    Contract.Assert(entityReferenceLink != null, "Entity reference link should never be null.");

                    Contract.Assert(itemsStack.Count > 0, "Entity reference link should never be reported as top-level item.");
                    {
                        ODataNavigationLink           parentNavigationLink           = (ODataNavigationLink)itemsStack.Peek();
                        ODataNavigationLinkAnnotation parentNavigationLinkAnnotation = parentNavigationLink.GetAnnotation <ODataNavigationLinkAnnotation>();
                        Contract.Assert(parentNavigationLinkAnnotation != null, "Every navigation link we added to the stack should have the navigation link annotation on it.");

                        parentNavigationLinkAnnotation.Add(entityReferenceLink);
                    }

                    break;

                default:
                    Contract.Assert(false, "We should never get here, it means the ODataReader reported a wrong state.");
                    break;
                }
            }

            Contract.Assert(odataReader.State == ODataReaderState.Completed, "We should have consumed all of the input by now.");
            Contract.Assert(topLevelItem != null, "A top level entry or feed should have been read by now.");
            return(topLevelItem);
        }
Exemplo n.º 54
0
        /// <inheritdoc />
        public override object Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext readContext)
        {
            if (messageReader == null)
            {
                throw Error.ArgumentNull("messageReader");
            }

            IEdmFunctionImport action = GetFunctionImport(readContext);

            // Create the correct resource type;
            Dictionary <string, object> payload;

            if (type == typeof(ODataActionParameters))
            {
                payload = new ODataActionParameters();
            }
            else
            {
                payload = new ODataUntypedActionParameters(action);
            }

            ODataParameterReader reader = messageReader.CreateODataParameterReader(action);

            while (reader.Read())
            {
                string parameterName            = null;
                IEdmFunctionParameter parameter = null;

                switch (reader.State)
                {
                case ODataParameterReaderState.Value:
                    parameterName = reader.Name;
                    parameter     = action.Parameters.SingleOrDefault(p => p.Name == parameterName);
                    // ODataLib protects against this but asserting just in case.
                    Contract.Assert(parameter != null, String.Format(CultureInfo.InvariantCulture, "Parameter '{0}' not found.", parameterName));
                    if (parameter.Type.IsPrimitive())
                    {
                        payload[parameterName] = reader.Value;
                    }
                    else
                    {
                        ODataEdmTypeDeserializer deserializer = DeserializerProvider.GetEdmTypeDeserializer(parameter.Type);
                        payload[parameterName] = deserializer.ReadInline(reader.Value, parameter.Type, readContext);
                    }
                    break;

                case ODataParameterReaderState.Collection:
                    parameterName = reader.Name;
                    parameter     = action.Parameters.SingleOrDefault(p => p.Name == parameterName);
                    // ODataLib protects against this but asserting just in case.
                    Contract.Assert(parameter != null, String.Format(CultureInfo.InvariantCulture, "Parameter '{0}' not found.", parameterName));
                    IEdmCollectionTypeReference collectionType = parameter.Type as IEdmCollectionTypeReference;
                    Contract.Assert(collectionType != null);
                    ODataCollectionValue        value = ODataCollectionDeserializer.ReadCollection(reader.CreateCollectionReader());
                    ODataCollectionDeserializer collectionDeserializer = DeserializerProvider.GetEdmTypeDeserializer(collectionType) as ODataCollectionDeserializer;
                    payload[parameterName] = collectionDeserializer.ReadInline(value, collectionType, readContext);
                    break;

                default:
                    break;
                }
            }

            return(payload);
        }
        private void ApplyFeedInNavigationProperty(IEdmNavigationProperty navigationProperty, object entityResource, ODataFeed feed, ODataDeserializerContext readContext)
        {
            ODataFeedAnnotation feedAnnotation = feed.GetAnnotation <ODataFeedAnnotation>();

            Contract.Assert(feedAnnotation != null, "Each feed we create should gave annotation on it.");

            ODataEntryDeserializer deserializer = DeserializerProvider.GetODataDeserializer(navigationProperty.Type);
            object value = deserializer.ReadInline(feed, readContext);

            if (readContext.IsPatchMode)
            {
                throw Error.InvalidOperation(SRResources.CannotPatchNavigationProperties, navigationProperty.Name, navigationProperty.DeclaringEntityType().FullName());
            }

            SetCollectionProperty(entityResource, navigationProperty.Name, isDelta: false, value: value);
        }
        internal static object CreateResource(IEdmComplexTypeReference edmComplexType, ODataDeserializerContext readContext)
        {
            Contract.Assert(edmComplexType != null);

            if (readContext.IsUntyped)
            {
                return(new EdmComplexObject(edmComplexType));
            }
            else
            {
                Type clrType = EdmLibHelpers.GetClrType(edmComplexType, readContext.Model);
                if (clrType == null)
                {
                    throw Error.InvalidOperation(SRResources.MappingDoesNotContainEntityType, edmComplexType.FullName());
                }

                return(Activator.CreateInstance(clrType));
            }
        }
        private void ApplyFeedInNavigationProperty(IEdmNavigationProperty navigationProperty, object entityResource, ODataFeedWithEntries feed, ODataDeserializerContext readContext)
        {
            Contract.Assert(navigationProperty != null && navigationProperty.PropertyKind == EdmPropertyKind.Navigation, "navigationProperty != null && navigationProperty.TypeKind == ResourceTypeKind.EntityType");
            Contract.Assert(entityResource != null, "entityResource != null");

            if (readContext.IsDeltaOfT)
            {
                string message = Error.Format(SRResources.CannotPatchNavigationProperties, navigationProperty.Name, navigationProperty.DeclaringEntityType().FullName());
                throw new ODataException(message);
            }

            ODataEdmTypeDeserializer deserializer = DeserializerProvider.GetEdmTypeDeserializer(navigationProperty.Type);

            if (deserializer == null)
            {
                throw new SerializationException(Error.Format(SRResources.TypeCannotBeDeserialized, navigationProperty.Type.FullName(), typeof(ODataMediaTypeFormatter)));
            }
            object value = deserializer.ReadInline(feed, navigationProperty.Type, readContext);

            DeserializationHelpers.SetCollectionProperty(entityResource, navigationProperty, value);
        }
        /// <summary>
        /// Deserializes the navigation property from <paramref name="navigationLinkWrapper"/> into <paramref name="entityResource"/>.
        /// </summary>
        /// <param name="entityResource">The object into which the navigation property should be read.</param>
        /// <param name="navigationLinkWrapper">The navigation link.</param>
        /// <param name="entityType">The entity type of the entity resource.</param>
        /// <param name="readContext">The deserializer context.</param>
        public virtual void ApplyNavigationProperty(object entityResource, ODataNavigationLinkWithItems navigationLinkWrapper,
                                                    IEdmEntityTypeReference entityType, ODataDeserializerContext readContext)
        {
            if (navigationLinkWrapper == null)
            {
                throw Error.ArgumentNull("navigationLinkWrapper");
            }

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

            IEdmNavigationProperty navigationProperty = entityType.FindProperty(navigationLinkWrapper.NavigationLink.Name) as IEdmNavigationProperty;

            if (navigationProperty == null)
            {
                throw new ODataException(
                          Error.Format(SRResources.NavigationPropertyNotfound, navigationLinkWrapper.NavigationLink.Name, entityType.FullName()));
            }

            foreach (ODataItemBase childItem in navigationLinkWrapper.NestedItems)
            {
                ODataEntityReferenceLinkBase entityReferenceLink = childItem as ODataEntityReferenceLinkBase;
                if (entityReferenceLink != null)
                {
                    // ignore links.
                    continue;
                }

                ODataFeedWithEntries feed = childItem as ODataFeedWithEntries;
                if (feed != null)
                {
                    ApplyFeedInNavigationProperty(navigationProperty, entityResource, feed, readContext);
                    continue;
                }

                // It must be entry by now.
                ODataEntryWithNavigationLinks entry = (ODataEntryWithNavigationLinks)childItem;
                if (entry != null)
                {
                    ApplyEntryInNavigationProperty(navigationProperty, entityResource, entry, readContext);
                }
            }
        }
 private void ApplyEntityProperties(object entityResource, ODataEntryWithNavigationLinks entryWrapper,
                                    IEdmEntityTypeReference entityType, ODataDeserializerContext readContext)
 {
     ApplyStructuralProperties(entityResource, entryWrapper, entityType, readContext);
     ApplyNavigationProperties(entityResource, entryWrapper, entityType, readContext);
 }
        private void ApplyNavigationProperties(ODataEntryAnnotation entryAnnotation, IEdmEntityTypeReference entityType, object entityResource, ODataDeserializerContext readContext)
        {
            Contract.Assert(entityType.TypeKind() == EdmTypeKind.Entity, "Only entity types can be specified for entities.");

            foreach (ODataNavigationLink navigationLink in entryAnnotation)
            {
                IEdmNavigationProperty navigationProperty = entityType.FindProperty(navigationLink.Name) as IEdmNavigationProperty;
                Contract.Assert(navigationProperty != null, "ODataLib reader should have already validated that all navigation properties are declared and none is open.");

                ApplyNavigationProperty(navigationLink, navigationProperty, entityResource, readContext);
            }
        }