示例#1
0
        public void SetCollectionProperty_CollectionTypeCannotBeInstantiated_And_SettableProperty_Throws(string propertyName)
        {
            object       value       = new SampleClassWithSettableCollectionProperties();
            IEdmProperty edmProperty = GetMockEdmProperty(propertyName, EdmPrimitiveTypeKind.Int32);

            Assert.Throws <SerializationException>(
                () => DeserializationHelpers.SetCollectionProperty(value, edmProperty, value: new List <int> {
                1, 2, 3
            }, propertyName: edmProperty.Name),
                String.Format("The property '{0}' on type 'System.Web.OData.Formatter.Deserialization.DeserializationHelpersTest+SampleClassWithSettableCollectionProperties' returned a null value. " +
                              "The input stream contains collection items which cannot be added if the instance is null.", propertyName));
        }
示例#2
0
        public void SetCollectionProperty_CollectionTypeCanBeInstantiated_And_SettableProperty(string propertyName)
        {
            object       value       = new SampleClassWithSettableCollectionProperties();
            IEdmProperty edmProperty = GetMockEdmProperty(propertyName, EdmPrimitiveTypeKind.Int32);

            DeserializationHelpers.SetCollectionProperty(value, edmProperty, value: new List <int> {
                1, 2, 3
            }, propertyName: edmProperty.Name, timeZoneInfo: null);

            Assert.Equal(
                new[] { 1, 2, 3 },
                value.GetType().GetProperty(propertyName).GetValue(value, index: null) as IEnumerable <int>);
        }
示例#3
0
        public void SetCollectionProperty_NonSettableProperty_NonNullValue_NoAdd_Throws(string propertyName)
        {
            object       value        = new SampleClassWithNonSettableCollectionProperties();
            Type         propertyType = typeof(SampleClassWithNonSettableCollectionProperties).GetProperty(propertyName).PropertyType;
            IEdmProperty edmProperty  = GetMockEdmProperty(propertyName, EdmPrimitiveTypeKind.Int32);

            Assert.Throws <SerializationException>(
                () => DeserializationHelpers.SetCollectionProperty(value, edmProperty, value: new List <int> {
                1, 2, 3
            }, propertyName: edmProperty.Name),
                String.Format("The type '{0}' of the property '{1}' on type 'System.Web.OData.Formatter.Deserialization.DeserializationHelpersTest+SampleClassWithNonSettableCollectionProperties' does not have an Add method. " +
                              "Consider using a collection type that does have an Add method - for example IList<T> or ICollection<T>.", propertyType.FullName, propertyName));
        }
示例#4
0
        public void SetCollectionProperty_CanConvertNonStandardEdmTypes()
        {
            SampleClassWithDifferentCollectionProperties value = new SampleClassWithDifferentCollectionProperties();
            IEdmProperty edmProperty = GetMockEdmProperty("UnsignedArray", EdmPrimitiveTypeKind.Int32);

            DeserializationHelpers.SetCollectionProperty(value, edmProperty, value: new List <int> {
                1, 2, 3
            }, propertyName: edmProperty.Name);

            Assert.Equal(
                new uint[] { 1, 2, 3 },
                value.UnsignedArray);
        }
示例#5
0
        public void SetCollectionProperty_NonSettableProperty_ArrayValue_FixedSize_Throws(string propertyName)
        {
            object       value        = new SampleClassWithNonSettableCollectionProperties();
            Type         propertyType = typeof(SampleClassWithNonSettableCollectionProperties).GetProperty(propertyName).PropertyType;
            IEdmProperty edmProperty  = GetMockEdmProperty(propertyName, EdmPrimitiveTypeKind.Int32);

            Assert.Throws <SerializationException>(
                () => DeserializationHelpers.SetCollectionProperty(value, edmProperty, value: new List <int> {
                1, 2, 3
            }, propertyName: edmProperty.Name),
                String.Format("The value of the property '{0}' on type 'System.Web.OData.Formatter.Deserialization.DeserializationHelpersTest+SampleClassWithNonSettableCollectionProperties' is an array. " +
                              "Consider adding a setter for the property.", propertyName));
        }
示例#6
0
        public void SetCollectionProperty_NonSettableProperty_NonNullValue_WithAddMethod(string propertyName)
        {
            object       value       = new SampleClassWithNonSettableCollectionProperties();
            IEdmProperty edmProperty = GetMockEdmProperty(propertyName, EdmPrimitiveTypeKind.Int32);

            DeserializationHelpers.SetCollectionProperty(value, edmProperty, value: new List <int> {
                1, 2, 3
            }, propertyName: edmProperty.Name);

            Assert.Equal(
                new[] { 1, 2, 3 },
                value.GetType().GetProperty(propertyName).GetValue(value, index: null) as IEnumerable <int>);
        }
        private void ApplyDynamicResourceInNestedProperty(string propertyName, object resource, IEdmStructuredTypeReference resourceStructuredType,
                                                          ODataResourceWrapper resourceWrapper, ODataDeserializerContext readContext)
        {
            Contract.Assert(resource != null);
            Contract.Assert(readContext != null);

            IEdmSchemaType    elementType      = readContext.Model.FindDeclaredType(resourceWrapper.Resource.TypeName);
            IEdmTypeReference edmTypeReference = elementType.ToEdmTypeReference(true);

            object value = ReadNestedResourceInline(resourceWrapper, edmTypeReference, readContext);

            DeserializationHelpers.SetDynamicProperty(resource, propertyName, value,
                                                      resourceStructuredType.StructuredDefinition(), readContext.Model);
        }
示例#8
0
        public void SetCollectionProperty_OnNonCollection_ThrowsSerialization(string propertyName)
        {
            object       value        = new SampleClassWithDifferentCollectionProperties();
            Type         propertyType = typeof(SampleClassWithDifferentCollectionProperties).GetProperty(propertyName).PropertyType;
            IEdmProperty edmProperty  = GetMockEdmProperty(propertyName, EdmPrimitiveTypeKind.Int32);

            Assert.Throws <SerializationException>(
                () => DeserializationHelpers.SetCollectionProperty(value, edmProperty, value: new List <int> {
                1, 2, 3
            }, propertyName: edmProperty.Name),
                Error.Format(
                    "The type '{0}' of the property '{1}' on type 'System.Web.OData.Formatter.Deserialization.DeserializationHelpersTest+SampleClassWithDifferentCollectionProperties' must be a collection.",
                    propertyType.FullName,
                    propertyName));
        }
示例#9
0
        /// <summary>
        /// Deserializes the given <paramref name="structuralProperty"/> into <paramref name="resource"/>.
        /// </summary>
        /// <param name="resource">The object into which the structural property should be read.</param>
        /// <param name="structuralProperty">The structural property.</param>
        /// <param name="structuredType">The type of the resource.</param>
        /// <param name="readContext">The deserializer context.</param>
        public virtual void ApplyStructuralProperty(object resource, ODataProperty structuralProperty,
                                                    IEdmStructuredTypeReference structuredType, ODataDeserializerContext readContext)
        {
            if (resource == null)
            {
                throw Error.ArgumentNull("resource");
            }

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

            DeserializationHelpers.ApplyProperty(structuralProperty, structuredType, resource, DeserializerProvider, readContext);
        }
示例#10
0
        public void SetCollectionProperty_CanConvertEnumCollection()
        {
            SampleClassWithDifferentCollectionProperties value = new SampleClassWithDifferentCollectionProperties();
            IEdmProperty edmProperty = GetMockEdmProperty("FlagsEnum", EdmPrimitiveTypeKind.String);

            DeserializationHelpers.SetCollectionProperty(
                value,
                edmProperty,
                value: new List <FlagsEnum> {
                FlagsEnum.One, FlagsEnum.Four | FlagsEnum.Two | (FlagsEnum)123
            },
                propertyName: edmProperty.Name);

            Assert.Equal(
                new FlagsEnum[] { FlagsEnum.One, FlagsEnum.Four | FlagsEnum.Two | (FlagsEnum)123 },
                value.FlagsEnum);
        }
示例#11
0
        private void ApplyDynamicResourceSetInNestedProperty(string propertyName, object resource, IEdmStructuredTypeReference structuredType,
                                                             ODataResourceSetWrapper resourceSetWrapper, ODataDeserializerContext readContext)
        {
            Contract.Assert(resource != null);
            Contract.Assert(readContext != null);

            if (String.IsNullOrEmpty(resourceSetWrapper.ResourceSet.TypeName))
            {
                string message = Error.Format(SRResources.DynamicResourceSetTypeNameIsRequired, propertyName);
                throw new ODataException(message);
            }

            string elementTypeName =
                DeserializationHelpers.GetCollectionElementTypeName(resourceSetWrapper.ResourceSet.TypeName,
                                                                    isNested: false);
            IEdmSchemaType elementType = readContext.Model.FindDeclaredType(elementTypeName);

            IEdmTypeReference          edmTypeReference = elementType.ToEdmTypeReference(true);
            EdmCollectionTypeReference collectionType   = new EdmCollectionTypeReference(new EdmCollectionType(edmTypeReference));

            ODataEdmTypeDeserializer deserializer = DeserializerProvider.GetEdmTypeDeserializer(collectionType);

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

            IEnumerable value  = ReadNestedResourceSetInline(resourceSetWrapper, collectionType, readContext) as IEnumerable;
            object      result = value;

            if (value != null)
            {
                if (readContext.IsUntyped)
                {
                    result = value.ConvertToEdmObject(collectionType);
                }
            }

            DeserializationHelpers.SetDynamicProperty(resource, structuredType, EdmTypeKind.Collection, propertyName,
                                                      result, collectionType, readContext.Model);
        }
示例#12
0
        public void SetCollectionProperty_ClearsCollection_IfClearCollectionIsTrue(string propertyName)
        {
            // Arrange
            IEnumerable <int> value    = new int[] { 1, 2, 3 };
            object            resource = new SampleClassWithNonSettableCollectionProperties
            {
                ICollection = { 42 },
                IList       = { 42 },
                Collection  = { 42 },
                List        = { 42 },
                CustomCollectionWithNoEmptyCtor = { 42 },
                CustomCollection = { 42 }
            };

            // Act
            DeserializationHelpers.SetCollectionProperty(resource, propertyName, null, value, clearCollection: true);

            // Assert
            Assert.Equal(
                value,
                resource.GetType().GetProperty(propertyName).GetValue(resource, index: null) as IEnumerable <int>);
        }
        public void SetCollectionProperty_CanConvertDataTime_ByDefault()
        {
            // Arrange
            SampleClassWithDifferentCollectionProperties source = new SampleClassWithDifferentCollectionProperties();
            IEdmProperty edmProperty = GetMockEdmProperty("DateTimeList", EdmPrimitiveTypeKind.DateTimeOffset);

            TimeZoneInfoHelper.TimeZone = null;
            DateTime dt = new DateTime(2014, 11, 15, 1, 2, 3);
            IList <DateTimeOffset> dtos = new List <DateTimeOffset>
            {
                new DateTimeOffset(dt, TimeSpan.Zero),
                new DateTimeOffset(dt, new TimeSpan(+7, 0, 0)),
                new DateTimeOffset(dt, new TimeSpan(-8, 0, 0))
            };

            IEnumerable <DateTime> expects = dtos.Select(e => e.LocalDateTime);

            // Act
            DeserializationHelpers.SetCollectionProperty(source, edmProperty, dtos, edmProperty.Name);

            // Assert
            Assert.Equal(expects, source.DateTimeList);
        }
示例#14
0
        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);

            string propertyName = EdmLibHelpers.GetClrPropertyName(navigationProperty, readContext.Model);

            DeserializationHelpers.SetCollectionProperty(entityResource, navigationProperty, value, propertyName, readContext.TimeZoneInfo);
        }
示例#15
0
        public void SetCollectionProperty_CanConvertDataTime_ByTimeZoneInfo()
        {
            // Arrange
            SampleClassWithDifferentCollectionProperties source = new SampleClassWithDifferentCollectionProperties();
            IEdmProperty edmProperty = GetMockEdmProperty("DateTimeList", EdmPrimitiveTypeKind.DateTimeOffset);

            TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");

            DateTime dt = new DateTime(2014, 11, 15, 1, 2, 3);
            IList <DateTimeOffset> dtos = new List <DateTimeOffset>
            {
                new DateTimeOffset(dt, TimeSpan.Zero),
                new DateTimeOffset(dt, new TimeSpan(+7, 0, 0)),
                new DateTimeOffset(dt, new TimeSpan(-8, 0, 0))
            };

            // Act
            DeserializationHelpers.SetCollectionProperty(source, edmProperty, dtos, edmProperty.Name, tzi);

            // Assert
            Assert.Equal(new List <DateTime> {
                dt.AddHours(-8), dt.AddHours(-15), dt
            }, source.DateTimeList);
        }
示例#16
0
        private void ApplyResourceSetInNestedProperty(IEdmProperty nestedProperty, object resource,
                                                      ODataResourceSetWrapper resourceSetWrapper, ODataDeserializerContext readContext)
        {
            Contract.Assert(nestedProperty != null);
            Contract.Assert(resource != null);
            Contract.Assert(readContext != null);

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

            object value = ReadNestedResourceSetInline(resourceSetWrapper, nestedProperty.Type, readContext);

            string propertyName = EdmLibHelpers.GetClrPropertyName(nestedProperty, readContext.Model);

            DeserializationHelpers.SetCollectionProperty(resource, nestedProperty, value, propertyName);
        }
        public void ApplyProperty_DoesNotIgnoreKeyProperty()
        {
            // Arrange
            ODataProperty property = new ODataProperty {
                Name = "Key1", Value = "Value1"
            };
            EdmEntityType entityType = new EdmEntityType("namespace", "name");

            entityType.AddKeys(new EdmStructuralProperty(entityType, "Key1", EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(typeof(string))));
            EdmEntityTypeReference    entityTypeReference = new EdmEntityTypeReference(entityType, isNullable: false);
            ODataDeserializerProvider provider            = new DefaultODataDeserializerProvider();

            var  resource     = new Mock <IDelta>(MockBehavior.Strict);
            Type propertyType = typeof(string);

            resource.Setup(r => r.TryGetPropertyType("Key1", out propertyType)).Returns(true).Verifiable();
            resource.Setup(r => r.TrySetPropertyValue("Key1", "Value1")).Returns(true).Verifiable();

            // Act
            DeserializationHelpers.ApplyProperty(property, entityTypeReference, resource.Object, provider, new ODataDeserializerContext());

            // Assert
            resource.Verify();
        }
示例#18
0
        /// <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);
            }

            if (!String.IsNullOrEmpty(complexValue.TypeName) && complexType.FullName() != complexValue.TypeName)
            {
                // received a derived complex type in a base type deserializer.
                IEdmModel model = readContext.Model;
                if (model == null)
                {
                    throw Error.Argument("readContext", SRResources.ModelMissingFromReadContext);
                }

                IEdmComplexType actualType = model.FindType(complexValue.TypeName) as IEdmComplexType;
                if (actualType == null)
                {
                    throw new ODataException(Error.Format(SRResources.ComplexTypeNotInModel, complexValue.TypeName));
                }

                if (actualType.IsAbstract)
                {
                    string message = Error.Format(SRResources.CannotInstantiateAbstractComplexType,
                                                  complexValue.TypeName);
                    throw new ODataException(message);
                }

                IEdmTypeReference        actualComplexType = new EdmComplexTypeReference(actualType, isNullable: false);
                ODataEdmTypeDeserializer deserializer      = DeserializerProvider.GetEdmTypeDeserializer(actualComplexType);
                if (deserializer == null)
                {
                    throw new SerializationException(
                              Error.Format(SRResources.TypeCannotBeDeserialized, actualComplexType.FullName(),
                                           typeof(ODataMediaTypeFormatter).Name));
                }

                object resource = deserializer.ReadInline(complexValue, actualComplexType, readContext);

                EdmStructuredObject structuredObject = resource as EdmStructuredObject;
                if (structuredObject != null)
                {
                    structuredObject.ExpectedEdmType = complexType.ComplexDefinition();
                }

                return(resource);
            }
            else
            {
                object complexResource = CreateResource(complexType, readContext);

                foreach (ODataProperty complexProperty in complexValue.Properties)
                {
                    DeserializationHelpers.ApplyProperty(complexProperty, complexType, complexResource,
                                                         DeserializerProvider, readContext);
                }
                return(complexResource);
            }
        }