private static void AddToCollectionCore(this IEnumerable items, IEnumerable collection, Type elementType, IList list, MethodInfo addMethod, TimeZoneInfo timeZoneInfo = null)
        {
            bool isNonstandardEdmPrimitiveCollection;

            elementType.IsNonstandardEdmPrimitive(out isNonstandardEdmPrimitiveCollection);

            foreach (object item in items)
            {
                object element = item;

                if (isNonstandardEdmPrimitiveCollection && element != null)
                {
                    // convert non-standard edm primitives if required.
                    element = EdmPrimitiveHelper.ConvertPrimitiveValue(element, elementType, timeZoneInfo);
                }

                if (list != null)
                {
                    list.Add(element);
                }
                else
                {
                    Contract.Assert(addMethod != null);
                    addMethod.Invoke(collection, new object[] { element });
                }
            }
        }
        private static void AddToCollectionCore(this IEnumerable items, IEnumerable collection, Type elementType, IList list, MethodInfo addMethod, ODataDeserializerContext context = null)
        {
            IEdmModel model = context?.Model;
            bool      isNonstandardEdmPrimitiveCollection;

            model.IsNonstandardEdmPrimitive(elementType, out isNonstandardEdmPrimitiveCollection);

            foreach (object item in items)
            {
                object element = item;

                if (isNonstandardEdmPrimitiveCollection && element != null)
                {
                    // convert non-standard edm primitives if required.
                    element = EdmPrimitiveHelper.ConvertPrimitiveValue(element, elementType, context?.TimeZone);
                }

                if (list != null)
                {
                    list.Add(element);
                }
                else
                {
                    Contract.Assert(addMethod != null);
                    addMethod.Invoke(collection, new object[] { element });
                }
            }
        }
 public void ConvertPrimitiveValue_Throws(object valueToConvert, Type conversionType, string exception)
 {
     // Arrange & Act & Assert
     ExceptionAssert.Throws <ValidationException>(
         () => EdmPrimitiveHelper.ConvertPrimitiveValue(valueToConvert, conversionType),
         exception);
 }
Beispiel #4
0
        public static Expression DateTimeOffsetToDateTime(Expression expression, TimeZoneInfo timeZoneInfo, ODataQuerySettings settings)
        {
            var unaryExpression = expression as UnaryExpression;

            if (unaryExpression != null)
            {
                if (Nullable.GetUnderlyingType(unaryExpression.Type) == unaryExpression.Operand.Type)
                {
                    // this is a cast from T to Nullable<T> which is redundant.
                    expression = unaryExpression.Operand;
                }
            }
            var parameterizedConstantValue = ExtractParameterizedConstant(expression);
            var dto = parameterizedConstantValue as DateTimeOffset?;

            if (dto != null)
            {
                if (settings.EnableConstantParameterization)
                {
                    return(LinqParameterContainer.Parameterize(typeof(DateTime), EdmPrimitiveHelper.ConvertPrimitiveValue(dto.Value, typeof(DateTime), timeZoneInfo)));
                }
                else
                {
                    return(Expression.Constant(EdmPrimitiveHelper.ConvertPrimitiveValue(dto.Value, typeof(DateTime), timeZoneInfo), typeof(DateTime)));
                }
            }
            return(expression);
        }
 public void ConvertPrimitiveValueToChar_Throws(string input)
 {
     // Arrange & Act & Assert
     ExceptionAssert.Throws <ValidationException>(
         () => EdmPrimitiveHelper.ConvertPrimitiveValue(input, typeof(char)),
         "The value must be a string with a length of 1.");
 }
 public void ConvertPrimitiveValueToXElement_Throws_IfInputIsNotString()
 {
     // Arrange & Act & Assert
     ExceptionAssert.Throws <ValidationException>(
         () => EdmPrimitiveHelper.ConvertPrimitiveValue(123, typeof(XElement)),
         "The value must be a string.");
 }
 public void ConvertPrimitiveValueToNullableChar_Throws()
 {
     // Arrange & Act & Assert
     ExceptionAssert.Throws <ValidationException>(
         () => EdmPrimitiveHelper.ConvertPrimitiveValue("123", typeof(char?)),
         "The value must be a string with a maximum length of 1.");
 }
        public void ConvertPrimitiveValue_NonStandardPrimitives(object valueToConvert, object result, Type conversionType)
        {
            // Arrange & Act
            object actual = EdmPrimitiveHelper.ConvertPrimitiveValue(valueToConvert, conversionType);

            // Assert
            Assert.Equal(result.GetType(), actual.GetType());
            Assert.Equal(result.ToString(), actual.ToString());
        }
        public void ConvertDateTimeValue_NonStandardPrimitives_DefaultTimeZoneInfo(DateTimeOffset valueToConvert)
        {
            // Arrange & Act
            object actual = EdmPrimitiveHelper.ConvertPrimitiveValue(valueToConvert, typeof(DateTime));

            // Assert
            DateTime dt = Assert.IsType <DateTime>(actual);

            Assert.Equal(valueToConvert.LocalDateTime, dt);
        }
        public void ConvertDateTimeValue_NonStandardPrimitives_CustomTimeZoneInfo(DateTimeOffset valueToConvert)
        {
            // Arrange & Act
            var    timeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
            object actual   = EdmPrimitiveHelper.ConvertPrimitiveValue(valueToConvert, typeof(DateTime), timeZone);

            // Assert
            DateTime dt = Assert.IsType <DateTime>(actual);

            Assert.Equal(TimeZoneInfo.ConvertTime(valueToConvert, timeZone).DateTime, dt);
        }
Beispiel #11
0
        /// <summary>
        /// Convert an OData value into a CLR object.
        /// </summary>
        /// <param name="graph">The given object.</param>
        /// <param name="edmTypeReference">The EDM type of the given object.</param>
        /// <param name="clrType">The CLR type of the given object.</param>
        /// <param name="parameterName">The parameter name of the given object.</param>
        /// <param name="readContext">The <see cref="ODataDeserializerContext"/> use to convert.</param>
        /// <param name="requestContainer">The dependency injection container for the request.</param>
        /// <returns>The converted object.</returns>
        public static object Convert(object graph, IEdmTypeReference edmTypeReference,
                                     Type clrType, string parameterName, ODataDeserializerContext readContext,
                                     IServiceProvider requestContainer)
        {
            if (graph == null || graph is ODataNullValue)
            {
                return(null);
            }

            // collection of primitive, enum
            ODataCollectionValue collectionValue = graph as ODataCollectionValue;

            if (collectionValue != null)
            {
                return(ConvertCollection(collectionValue, edmTypeReference, clrType, parameterName, readContext,
                                         requestContainer));
            }

            // enum value
            ODataEnumValue enumValue = graph as ODataEnumValue;

            if (enumValue != null)
            {
                IEdmEnumTypeReference edmEnumType = edmTypeReference.AsEnum();
                Contract.Assert(edmEnumType != null);

                ODataDeserializerProvider deserializerProvider =
                    requestContainer.GetRequiredService <ODataDeserializerProvider>();

                ODataEnumDeserializer deserializer =
                    (ODataEnumDeserializer)deserializerProvider.GetEdmTypeDeserializer(edmEnumType);

                return(deserializer.ReadInline(enumValue, edmEnumType, readContext));
            }

            // primitive value
            if (edmTypeReference.IsPrimitive())
            {
                ConstantNode node = graph as ConstantNode;
                return(EdmPrimitiveHelper.ConvertPrimitiveValue(node != null ? node.Value : graph, clrType, readContext.TimeZone));
            }

            // Resource, ResourceSet, Entity Reference or collection of entity reference
            return(ConvertResourceOrResourceSet(graph, edmTypeReference, readContext));
        }
        /// <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");
            }

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

            //Try and change the value appropriately if type is specified
            if (readContext.ResourceType != null && primitiveProperty.Value != null)
            {
                return(EdmPrimitiveHelper.ConvertPrimitiveValue(primitiveProperty.Value, readContext.ResourceType, readContext.TimeZone));
            }

            return(primitiveProperty.Value);
        }
Beispiel #13
0
        internal static void SetDeclaredProperty(object resource, EdmTypeKind propertyKind, string propertyName,
                                                 object propertyValue, IEdmProperty edmProperty, ODataDeserializerContext readContext)
        {
            if (propertyKind == EdmTypeKind.Collection)
            {
                SetCollectionProperty(resource, edmProperty, propertyValue, propertyName);
            }
            else
            {
                if (!readContext.IsNoClrType)
                {
                    if (propertyKind == EdmTypeKind.Primitive)
                    {
                        propertyValue = EdmPrimitiveHelper.ConvertPrimitiveValue(propertyValue,
                                                                                 GetPropertyType(resource, propertyName), readContext.TimeZone);
                    }
                }

                SetProperty(resource, propertyName, propertyValue);
            }
        }
Beispiel #14
0
        internal static object ConvertTo(string valueString, Type type, TimeZoneInfo timeZone)
        {
            if (valueString == null)
            {
                return(null);
            }

            if (TypeHelper.IsNullable(type) && String.Equals(valueString, "null", StringComparison.Ordinal))
            {
                return(null);
            }

            // TODO 1668: ODL beta1's ODataUriUtils.ConvertFromUriLiteral does not support converting uri literal
            // to ODataEnumValue, but beta1's ODataUriUtils.ConvertToUriLiteral supports converting ODataEnumValue
            // to uri literal.
            if (TypeHelper.IsEnum(type))
            {
                string[] values = valueString.Split(new[] { '\'' }, StringSplitOptions.None);
                if (values.Length == 3 && String.IsNullOrEmpty(values[2]))
                {
                    // Remove the type name if the enum value is a fully qualified literal.
                    valueString = values[1];
                }

                Type     enumType     = TypeHelper.GetUnderlyingTypeOrSelf(type);
                object[] parameters   = new[] { valueString, Enum.ToObject(enumType, 0) };
                bool     isSuccessful = (bool)EnumTryParseMethod.MakeGenericMethod(enumType).Invoke(null, parameters);

                if (!isSuccessful)
                {
                    throw Error.InvalidOperation(SRResources.ModelBinderUtil_ValueCannotBeEnum, valueString, type.Name);
                }

                return(parameters[1]);
            }

            // The logic of "public static object ConvertFromUriLiteral(string value, ODataVersion version);" treats
            // the date value string (for example: 2015-01-02) as DateTimeOffset literal, and return a DateTimeOffset
            // object. However, the logic of
            // "object ConvertFromUriLiteral(string value, ODataVersion version, IEdmModel model, IEdmTypeReference typeReference);"
            // can return the correct Date object.
            if (type == typeof(Date) || type == typeof(Date?))
            {
                EdmCoreModel model = EdmCoreModel.Instance;
                IEdmPrimitiveTypeReference dateTypeReference = type.GetEdmPrimitiveTypeReference();
                return(ODataUriUtils.ConvertFromUriLiteral(valueString, ODataVersion.V4, model, dateTypeReference));
            }

            object value;

            try
            {
                value = ODataUriUtils.ConvertFromUriLiteral(valueString, ODataVersion.V4);
            }
            catch
            {
                if (type == typeof(string))
                {
                    return(valueString);
                }

                throw;
            }

            bool isNonStandardEdmPrimitive;

            type.IsNonstandardEdmPrimitive(out isNonStandardEdmPrimitive);

            if (isNonStandardEdmPrimitive)
            {
                // shall we get the timezone?
                return(EdmPrimitiveHelper.ConvertPrimitiveValue(value, type, timeZone));
            }
            else
            {
                type = Nullable.GetUnderlyingType(type) ?? type;
                return(System.Convert.ChangeType(value, type, CultureInfo.InvariantCulture));
            }
        }