예제 #1
0
        /// <summary>
        /// Translate KeySegment to linq expression.
        /// </summary>
        /// <param name="segment">The KeySegment</param>
        /// <returns>The linq expression</returns>
        public override Expression Translate(KeySegment segment)
        {
            // translate to be ResultExpressionFromEntitySetSegment.Where(id -> id == keyVale).Single()

            Type instanceType = null;

            if (segment.EdmType.TypeKind == EdmTypeKind.Primitive)
            {
                instanceType = EdmLibraryExtensions.GetPrimitiveClrType((IEdmPrimitiveTypeReference)segment.EdmType.ToTypeReference(false));
            }

            ParameterExpression parameter = Expression.Parameter(instanceType, "it");
            Expression          body      = null;

            foreach (var key in segment.Keys)
            {
                var        propertyAccessExpression = Expression.Property(parameter, instanceType, key.Key);
                Expression keyPredicate             = Expression.Equal(propertyAccessExpression, Expression.Constant(key.Value));
                if (body == null)
                {
                    body = keyPredicate;
                }
                else
                {
                    body = Expression.AndAlso(body, keyPredicate);
                }
            }

            Expression whereResult = Expression.Call(typeof(Queryable), WhereMethodName, new Type[] { instanceType }, this.ResultExpression, Expression.Quote(Expression.Lambda(body, parameter)));

            this.ResultExpression = Expression.Call(typeof(Queryable), SingleMethodName, new Type[] { instanceType }, whereResult);
            return(this.ResultExpression);
        }
예제 #2
0
        public void GetPrimitiveClrTypeForBuiltInTypesShouldBeExpect(EdmPrimitiveTypeKind kind, bool nullable, Type expect)
        {
            IEdmPrimitiveType primitiveType = EdmCoreModel.Instance.GetPrimitiveType(kind);
            Type actual = EdmLibraryExtensions.GetPrimitiveClrType(primitiveType, nullable);

            actual.Should().Be(expect);
        }
예제 #3
0
        /// <summary>
        /// Try to convert a value into an EDM primitive type, if template parsing enabled, the <paramref name="valueText"/> matching
        /// template would be converted into corresponding UriTemplateExpression.
        /// </summary>
        /// <param name="typeReference">the type to convert to (primitive or enum type)</param>
        /// <param name="valueText">the value to convert</param>
        /// <param name="convertedValue">The converted value, if conversion succeeded.</param>
        /// <returns>true if the conversion was successful.</returns>
        private bool TryConvertValue(IEdmTypeReference typeReference, string valueText, out object convertedValue)
        {
            if (typeReference.IsEnum())
            {
                QueryNode enumNode = null;
                if (EnumBinder.TryBindIdentifier(valueText, typeReference.AsEnum(), null, out enumNode))
                {
                    convertedValue = enumNode;
                    return(true);
                }

                convertedValue = null;
                return(false);
            }

            IEdmPrimitiveTypeReference primitiveType = typeReference.AsPrimitive();
            UriTemplateExpression      expression;

            if (this.enableUriTemplateParsing && UriTemplateParser.TryParseLiteral(valueText, primitiveType, out expression))
            {
                convertedValue = expression;
                return(true);
            }

            Type          primitiveClrType = EdmLibraryExtensions.GetPrimitiveClrType((IEdmPrimitiveType)primitiveType.Definition, primitiveType.IsNullable);
            LiteralParser literalParser    = LiteralParser.ForKeys(this.keysAsSegment);

            return(literalParser.TryParseLiteral(primitiveClrType, valueText, out convertedValue));
        }
예제 #4
0
        /// <summary>
        /// Try to convert a value into an EDM primitive type
        /// </summary>
        /// <param name="primitiveType">the type to convert to</param>
        /// <param name="valueText">the value to convert</param>
        /// <param name="convertedValue">The converted value, if conversion succeeded.</param>
        /// <returns>true if the conversion was successful.</returns>
        private bool TryConvertValue(IEdmPrimitiveTypeReference primitiveType, string valueText, out object convertedValue)
        {
            Type          primitiveClrType = EdmLibraryExtensions.GetPrimitiveClrType((IEdmPrimitiveType)primitiveType.Definition, primitiveType.IsNullable);
            LiteralParser literalParser    = LiteralParser.ForKeys(this.keysAsSegments);

            return(literalParser.TryParseLiteral(primitiveClrType, valueText, out convertedValue));
        }
예제 #5
0
        /// <summary>
        /// Verifies that the given <paramref name="primitiveValue"/> is or can be coerced to <paramref name="expectedTypeReference"/>, and coerces it if necessary.
        /// </summary>
        /// <param name="primitiveValue">An EDM primitive value to verify.</param>
        /// <param name="model">Model to verify against.</param>
        /// <param name="expectedTypeReference">Expected type reference.</param>
        /// <param name="version">The version to use for reading.</param>
        /// <returns>Coerced version of the <paramref name="primitiveValue"/>.</returns>
        internal static object VerifyAndCoerceUriPrimitiveLiteral(object primitiveValue, IEdmModel model, IEdmTypeReference expectedTypeReference, ODataVersion version)
        {
            DebugUtils.CheckNoExternalCallers();
            ExceptionUtils.CheckArgumentNotNull(primitiveValue, "primitiveValue");
            ExceptionUtils.CheckArgumentNotNull(model, "model");
            ExceptionUtils.CheckArgumentNotNull(expectedTypeReference, "expectedTypeReference");

            // First deal with null literal
            ODataUriNullValue nullValue = primitiveValue as ODataUriNullValue;

            if (nullValue != null)
            {
                if (!expectedTypeReference.IsNullable)
                {
                    throw new ODataException(o.Strings.ODataUriUtils_ConvertFromUriLiteralNullOnNonNullableType(expectedTypeReference.ODataFullName()));
                }

                IEdmType actualResolvedType = ValidationUtils.ValidateValueTypeName(model, nullValue.TypeName, expectedTypeReference.Definition.TypeKind);
                Debug.Assert(actualResolvedType != null, "This is a primitive-only codepath so actualResolvedType != null.");

                if (actualResolvedType.IsSpatial())
                {
                    ODataVersionChecker.CheckSpatialValue(version);
                }

                if (TypePromotionUtils.CanConvertTo(actualResolvedType.ToTypeReference(), expectedTypeReference))
                {
                    nullValue.TypeName = expectedTypeReference.ODataFullName();
                    return(nullValue);
                }

                throw new ODataException(o.Strings.ODataUriUtils_ConvertFromUriLiteralNullTypeVerificationFailure(expectedTypeReference.ODataFullName(), nullValue.TypeName));
            }

            // Only other positive case is a numeric primitive that needs to be coerced
            IEdmPrimitiveTypeReference expectedPrimitiveTypeReference = expectedTypeReference.AsPrimitiveOrNull();

            if (expectedPrimitiveTypeReference == null)
            {
                throw new ODataException(o.Strings.ODataUriUtils_ConvertFromUriLiteralTypeVerificationFailure(expectedTypeReference.ODataFullName(), primitiveValue));
            }

            object coercedResult = CoerceNumericType(primitiveValue, expectedPrimitiveTypeReference.PrimitiveDefinition());

            if (coercedResult != null)
            {
                return(coercedResult);
            }

            Type actualType = primitiveValue.GetType();
            Type targetType = TypeUtils.GetNonNullableType(EdmLibraryExtensions.GetPrimitiveClrType(expectedPrimitiveTypeReference));

            // If target type is assignable from actual type, we're OK
            if (targetType.IsAssignableFrom(actualType))
            {
                return(primitiveValue);
            }

            throw new ODataException(o.Strings.ODataUriUtils_ConvertFromUriLiteralTypeVerificationFailure(expectedPrimitiveTypeReference.ODataFullName(), primitiveValue));
        }
예제 #6
0
        /// <summary>
        /// Verifies that the given <paramref name="primitiveValue"/> is or can be coerced to <paramref name="expectedTypeReference"/>, and coerces it if necessary.
        /// </summary>
        /// <param name="primitiveValue">An EDM primitive value to verify.</param>
        /// <param name="literalValue">The literal value that was parsed as this primitiveValue.</param>
        /// <param name="model">Model to verify against.</param>
        /// <param name="expectedTypeReference">Expected type reference.</param>
        /// <returns>Coerced version of the <paramref name="primitiveValue"/>.</returns>
        internal static object VerifyAndCoerceUriPrimitiveLiteral(
            object primitiveValue,
            string literalValue,
            IEdmModel model,
            IEdmTypeReference expectedTypeReference)
        {
            ExceptionUtils.CheckArgumentNotNull(primitiveValue, "primitiveValue");
            ExceptionUtils.CheckArgumentNotNull(literalValue, "literalValue");
            ExceptionUtils.CheckArgumentNotNull(model, "model");
            ExceptionUtils.CheckArgumentNotNull(expectedTypeReference, "expectedTypeReference");

            // First deal with null literal
            ODataNullValue nullValue = primitiveValue as ODataNullValue;

            if (nullValue != null)
            {
                if (!expectedTypeReference.IsNullable)
                {
                    throw new ODataException(ODataErrorStrings.ODataUriUtils_ConvertFromUriLiteralNullOnNonNullableType(expectedTypeReference.FullName()));
                }

                return(nullValue);
            }

            // Only other positive case is a numeric primitive that needs to be coerced
            IEdmPrimitiveTypeReference expectedPrimitiveTypeReference = expectedTypeReference.AsPrimitiveOrNull();

            if (expectedPrimitiveTypeReference == null)
            {
                throw new ODataException(ODataErrorStrings.ODataUriUtils_ConvertFromUriLiteralTypeVerificationFailure(expectedTypeReference.FullName(), literalValue));
            }

            object coercedResult = CoerceNumericType(primitiveValue, expectedPrimitiveTypeReference.PrimitiveDefinition());

            if (coercedResult != null)
            {
                return(coercedResult);
            }

            // if expectedTypeReference is set, need to coerce cast
            coercedResult = CoerceTemporalType(primitiveValue, expectedPrimitiveTypeReference.PrimitiveDefinition());
            if (coercedResult != null)
            {
                return(coercedResult);
            }

            Type actualType = primitiveValue.GetType();
            Type targetType = TypeUtils.GetNonNullableType(EdmLibraryExtensions.GetPrimitiveClrType(expectedPrimitiveTypeReference));

            // If target type is assignable from actual type, we're OK
            if (targetType.IsAssignableFrom(actualType))
            {
                return(primitiveValue);
            }

            throw new ODataException(ODataErrorStrings.ODataUriUtils_ConvertFromUriLiteralTypeVerificationFailure(expectedPrimitiveTypeReference.FullName(), literalValue));
        }
예제 #7
0
        internal static object ReadPrimitiveValue(XmlReader reader, IEdmPrimitiveTypeReference primitiveTypeReference)
        {
            object obj2;

            if (!PrimitiveConverter.Instance.TryTokenizeFromXml(reader, EdmLibraryExtensions.GetPrimitiveClrType(primitiveTypeReference), out obj2))
            {
                return(ConvertStringToPrimitive(reader.ReadElementContentValue(), primitiveTypeReference));
            }
            return(obj2);
        }
예제 #8
0
        /// <summary>
        /// Reads a value of an XML element and converts it to the target primitive value.
        /// </summary>
        /// <param name="reader">The XML reader to read the value from.</param>
        /// <param name="primitiveTypeReference">The primitive type reference to convert the value to.</param>
        /// <returns>The primitive value read.</returns>
        /// <remarks>This method does not read null values, it only reads the actual element value (not its attributes).</remarks>
        /// <remarks>
        /// Pre-Condition:   XmlNodeType.Element   - the element to read the value for.
        ///                  XmlNodeType.Attribute - an attribute on the element to read the value for.
        /// Post-Condition:  XmlNodeType.Element    - the element was empty.
        ///                  XmlNodeType.EndElement - the element had some value.
        /// </remarks>
        internal static object ReadPrimitiveValue(XmlReader reader, IEdmPrimitiveTypeReference primitiveTypeReference)
        {
            Debug.Assert(reader != null, "reader != null");

            object spatialValue;

            if (!PrimitiveConverter.Instance.TryTokenizeFromXml(reader, EdmLibraryExtensions.GetPrimitiveClrType(primitiveTypeReference), out spatialValue))
            {
                string stringValue = reader.ReadElementContentValue();
                return(ConvertStringToPrimitive(stringValue, primitiveTypeReference));
            }

            return(spatialValue);
        }
예제 #9
0
        /// <summary>
        /// Returns the instance type for the specified <paramref name="type"/> or null if none exists.
        /// </summary>
        /// <param name="type">The type to get the instance type for.</param>
        /// <param name="model">The model containing annotations.</param>
        /// <returns>The instance type for the <paramref name="type"/> or null if no instance type exists.</returns>
        public static Type GetInstanceType(this IEdmType type, IEdmModel model)
        {
            ExceptionUtils.CheckArgumentNotNull(type, "type");
            ExceptionUtils.CheckArgumentNotNull(model, "model");

            if (type.TypeKind == EdmTypeKind.Primitive)
            {
                return(EdmLibraryExtensions.GetPrimitiveClrType((IEdmPrimitiveTypeReference)type.ToTypeReference(false)));
            }

            ODataQueryEdmTypeAnnotation annotation = model.GetAnnotationValue <ODataQueryEdmTypeAnnotation>(type);

            return(annotation == null ? null : annotation.InstanceType);
        }
        /// <summary>
        /// Try to convert a value into an EDM primitive type, if template parsing enabled, the <paramref name="valueText"/> matching
        /// template would be converted into corresponding UriTemplateExpression.
        /// </summary>
        /// <param name="primitiveType">the type to convert to</param>
        /// <param name="valueText">the value to convert</param>
        /// <param name="convertedValue">The converted value, if conversion succeeded.</param>
        /// <returns>true if the conversion was successful.</returns>
        private bool TryConvertValue(IEdmPrimitiveTypeReference primitiveType, string valueText, out object convertedValue)
        {
            UriTemplateExpression expression;

            if (this.enableUriTemplateParsing && UriTemplateParser.TryParseLiteral(valueText, primitiveType, out expression))
            {
                convertedValue = expression;
                return(true);
            }

            Type          primitiveClrType = EdmLibraryExtensions.GetPrimitiveClrType((IEdmPrimitiveType)primitiveType.Definition, primitiveType.IsNullable);
            LiteralParser literalParser    = LiteralParser.ForKeys(this.keysAsSegments);

            return(literalParser.TryParseLiteral(primitiveClrType, valueText, out convertedValue));
        }
예제 #11
0
 internal static object VerifyAndCoerceUriPrimitiveLiteral(object primitiveValue, IEdmModel model, IEdmTypeReference expectedTypeReference, ODataVersion version)
 {
     ExceptionUtils.CheckArgumentNotNull<object>(primitiveValue, "primitiveValue");
     ExceptionUtils.CheckArgumentNotNull<IEdmModel>(model, "model");
     ExceptionUtils.CheckArgumentNotNull<IEdmTypeReference>(expectedTypeReference, "expectedTypeReference");
     ODataUriNullValue value2 = primitiveValue as ODataUriNullValue;
     if (value2 != null)
     {
         if (!expectedTypeReference.IsNullable)
         {
             throw new ODataException(Microsoft.Data.OData.Strings.ODataUriUtils_ConvertFromUriLiteralNullOnNonNullableType(expectedTypeReference.ODataFullName()));
         }
         IEdmType type = ValidationUtils.ValidateValueTypeName(model, value2.TypeName, expectedTypeReference.Definition.TypeKind);
         if (type.IsSpatial())
         {
             ODataVersionChecker.CheckSpatialValue(version);
         }
         if (!TypePromotionUtils.CanConvertTo(type.ToTypeReference(), expectedTypeReference))
         {
             throw new ODataException(Microsoft.Data.OData.Strings.ODataUriUtils_ConvertFromUriLiteralNullTypeVerificationFailure(expectedTypeReference.ODataFullName(), value2.TypeName));
         }
         value2.TypeName = expectedTypeReference.ODataFullName();
         return value2;
     }
     IEdmPrimitiveTypeReference reference = expectedTypeReference.AsPrimitiveOrNull();
     if (reference == null)
     {
         throw new ODataException(Microsoft.Data.OData.Strings.ODataUriUtils_ConvertFromUriLiteralTypeVerificationFailure(expectedTypeReference.ODataFullName(), primitiveValue));
     }
     object obj2 = CoerceNumericType(primitiveValue, reference.PrimitiveDefinition());
     if (obj2 != null)
     {
         return obj2;
     }
     Type c = primitiveValue.GetType();
     if (!TypeUtils.GetNonNullableType(EdmLibraryExtensions.GetPrimitiveClrType(reference)).IsAssignableFrom(c))
     {
         throw new ODataException(Microsoft.Data.OData.Strings.ODataUriUtils_ConvertFromUriLiteralTypeVerificationFailure(reference.ODataFullName(), primitiveValue));
     }
     return primitiveValue;
 }
        internal static object ConvertValue(
            object value,
            IEdmPrimitiveTypeReference primitiveTypeReference,
            ODataMessageReaderSettings messageReaderSettings,
            ODataVersion version,
            bool validateNullValue,
            string propertyName)
        {
            Debug.Assert(primitiveTypeReference != null, "primitiveTypeReference != null");

            if (value == null)
            {
                // Only primitive type references are validated. Core model is sufficient.
                ReaderValidationUtils.ValidateNullValue(
                    EdmCoreModel.Instance,
                    primitiveTypeReference,
                    messageReaderSettings,
                    validateNullValue,
                    version,
                    propertyName);
                return(null);
            }

            try
            {
                Type targetType = EdmLibraryExtensions.GetPrimitiveClrType(primitiveTypeReference.PrimitiveDefinition(), false);

                string stringValue = value as string;
                if (stringValue != null)
                {
                    return(ConvertStringValue(stringValue, targetType));
                }
                else if (value is Int32)
                {
                    return(ConvertInt32Value((int)value, targetType, primitiveTypeReference));
                }
                else if (value is Decimal)
                {
                    Decimal decimalValue = (Decimal)value;
                    if (targetType == typeof(Int64))
                    {
                        return(Convert.ToInt64(decimalValue));
                    }

                    if (targetType == typeof(Double))
                    {
                        return(Convert.ToDouble(decimalValue));
                    }

                    if (targetType == typeof(Single))
                    {
                        return(Convert.ToSingle(decimalValue));
                    }

                    if (targetType != typeof(Decimal))
                    {
                        throw new ODataException(ODataErrorStrings.ODataJsonReaderUtils_CannotConvertDecimal(primitiveTypeReference.ODataFullName()));
                    }
                }
                else if (value is Double)
                {
                    Double doubleValue = (Double)value;
                    if (targetType == typeof(Single))
                    {
                        return(Convert.ToSingle(doubleValue));
                    }

                    if (targetType != typeof(Double))
                    {
                        throw new ODataException(ODataErrorStrings.ODataJsonReaderUtils_CannotConvertDouble(primitiveTypeReference.ODataFullName()));
                    }
                }
                else if (value is bool)
                {
                    if (targetType != typeof(bool))
                    {
                        throw new ODataException(ODataErrorStrings.ODataJsonReaderUtils_CannotConvertBoolean(primitiveTypeReference.ODataFullName()));
                    }
                }
                else if (value is DateTime)
                {
                    if (targetType != typeof(DateTime))
                    {
                        throw new ODataException(ODataErrorStrings.ODataJsonReaderUtils_CannotConvertDateTime(primitiveTypeReference.ODataFullName()));
                    }
                }
                else if (value is DateTimeOffset)
                {
                    if (targetType != typeof(DateTimeOffset))
                    {
                        throw new ODataException(ODataErrorStrings.ODataJsonReaderUtils_CannotConvertDateTimeOffset(primitiveTypeReference.ODataFullName()));
                    }
                }
            }
            catch (Exception e)
            {
                if (!ExceptionUtils.IsCatchableExceptionType(e))
                {
                    throw;
                }

                throw ReaderValidationUtils.GetPrimitiveTypeConversionException(primitiveTypeReference, e, value.ToString());
            }

            // otherwise just return the value without doing any conversion
            return(value);
        }
예제 #13
0
        /// <summary>
        /// Converts the given JSON value to the expected type as per OData conversion rules for JSON values.
        /// </summary>
        /// <param name="value">Value to the converted.</param>
        /// <param name="primitiveTypeReference">Type reference to which the value needs to be converted.</param>
        /// <param name="messageReaderSettings">The message reader settings used for reading.</param>
        /// <param name="version">The version of the OData protocol used for reading.</param>
        /// <param name="validateNullValue">true to validate null values; otherwise false.</param>
        /// <returns>Object which is in sync with the property type (modulo the V1 exception of converting numbers to non-compatible target types).</returns>
        internal static object ConvertValue(
            object value,
            IEdmPrimitiveTypeReference primitiveTypeReference,
            ODataMessageReaderSettings messageReaderSettings,
            ODataVersion version,
            bool validateNullValue)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(primitiveTypeReference != null, "primitiveTypeReference != null");

            //// NOTE: this method was copied from WCF DS (and changed to take a type reference instead of a CLR target type)

            if (value == null)
            {
                // Only primitive type references are validated. Core model is sufficient.
                ReaderValidationUtils.ValidateNullValue(EdmCoreModel.Instance, primitiveTypeReference, messageReaderSettings, validateNullValue, version);
                return(null);
            }

            try
            {
                Type targetType = EdmLibraryExtensions.GetPrimitiveClrType(primitiveTypeReference.PrimitiveDefinition(), false);
                ODataReaderBehavior readerBehavior = messageReaderSettings.ReaderBehavior;

                string stringValue = value as string;
                if (stringValue != null)
                {
                    return(ConvertStringValue(stringValue, targetType, version));
                }
                else if (value is Int32)
                {
                    return(ConvertInt32Value((int)value, targetType, primitiveTypeReference, readerBehavior == null ? false : readerBehavior.UseV1ProviderBehavior));
                }
                else if (value is Double)
                {
                    Double doubleValue = (Double)value;
                    if (targetType == typeof(Single))
                    {
                        return(Convert.ToSingle(doubleValue));
                    }

                    if (!IsV1PrimitiveType(targetType) || (targetType != typeof(Double) && (readerBehavior == null || !readerBehavior.UseV1ProviderBehavior)))
                    {
                        throw new ODataException(o.Strings.ODataJsonReaderUtils_CannotConvertDouble(primitiveTypeReference.ODataFullName()));
                    }
                }
                else if (value is bool)
                {
                    if (targetType != typeof(bool) && (readerBehavior == null || readerBehavior.FormatBehaviorKind != ODataBehaviorKind.WcfDataServicesServer))
                    {
                        throw new ODataException(o.Strings.ODataJsonReaderUtils_CannotConvertBoolean(primitiveTypeReference.ODataFullName()));
                    }
                }
                else if (value is DateTime)
                {
                    if (targetType != typeof(DateTime) && (readerBehavior == null || readerBehavior.FormatBehaviorKind != ODataBehaviorKind.WcfDataServicesServer))
                    {
                        throw new ODataException(o.Strings.ODataJsonReaderUtils_CannotConvertDateTime(primitiveTypeReference.ODataFullName()));
                    }
                }
                else if (value is DateTimeOffset)
                {
                    // Currently, we do not support any conversion for DateTimeOffset date type. Hence failing if the target
                    // type is not DateTimeOffset.
                    if (targetType != typeof(DateTimeOffset))
                    {
                        throw new ODataException(o.Strings.ODataJsonReaderUtils_CannotConvertDateTimeOffset(primitiveTypeReference.ODataFullName()));
                    }
                }
            }
            catch (Exception e)
            {
                if (!ExceptionUtils.IsCatchableExceptionType(e))
                {
                    throw;
                }

                throw ReaderValidationUtils.GetPrimitiveTypeConversionException(primitiveTypeReference, e);
            }

            // otherwise just return the value without doing any conversion
            return(value);
        }
예제 #14
0
 internal static object ConvertValue(object value, IEdmPrimitiveTypeReference primitiveTypeReference, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, bool validateNullValue)
 {
     if (value == null)
     {
         ReaderValidationUtils.ValidateNullValue(EdmCoreModel.Instance, primitiveTypeReference, messageReaderSettings, validateNullValue, version);
         return(null);
     }
     try
     {
         Type primitiveClrType = EdmLibraryExtensions.GetPrimitiveClrType(primitiveTypeReference.PrimitiveDefinition(), false);
         ODataReaderBehavior readerBehavior = messageReaderSettings.ReaderBehavior;
         string stringValue = value as string;
         if (stringValue != null)
         {
             return(ConvertStringValue(stringValue, primitiveClrType, version));
         }
         if (value is int)
         {
             return(ConvertInt32Value((int)value, primitiveClrType, primitiveTypeReference, (readerBehavior != null) && readerBehavior.UseV1ProviderBehavior));
         }
         if (value is double)
         {
             double num = (double)value;
             if (primitiveClrType == typeof(float))
             {
                 return(Convert.ToSingle(num));
             }
             if (!IsV1PrimitiveType(primitiveClrType) || ((primitiveClrType != typeof(double)) && ((readerBehavior == null) || !readerBehavior.UseV1ProviderBehavior)))
             {
                 throw new ODataException(Microsoft.Data.OData.Strings.ODataJsonReaderUtils_CannotConvertDouble(primitiveTypeReference.ODataFullName()));
             }
             return(value);
         }
         if (value is bool)
         {
             if ((primitiveClrType != typeof(bool)) && ((readerBehavior == null) || (readerBehavior.FormatBehaviorKind != ODataBehaviorKind.WcfDataServicesServer)))
             {
                 throw new ODataException(Microsoft.Data.OData.Strings.ODataJsonReaderUtils_CannotConvertBoolean(primitiveTypeReference.ODataFullName()));
             }
             return(value);
         }
         if (value is DateTime)
         {
             if ((primitiveClrType != typeof(DateTime)) && ((readerBehavior == null) || (readerBehavior.FormatBehaviorKind != ODataBehaviorKind.WcfDataServicesServer)))
             {
                 throw new ODataException(Microsoft.Data.OData.Strings.ODataJsonReaderUtils_CannotConvertDateTime(primitiveTypeReference.ODataFullName()));
             }
             return(value);
         }
         if ((value is DateTimeOffset) && (primitiveClrType != typeof(DateTimeOffset)))
         {
             throw new ODataException(Microsoft.Data.OData.Strings.ODataJsonReaderUtils_CannotConvertDateTimeOffset(primitiveTypeReference.ODataFullName()));
         }
     }
     catch (Exception exception)
     {
         if (!ExceptionUtils.IsCatchableExceptionType(exception))
         {
             throw;
         }
         throw ReaderValidationUtils.GetPrimitiveTypeConversionException(primitiveTypeReference, exception);
     }
     return(value);
 }
        /// <summary>
        /// Converts the given payload value to the type defined in a type definition.
        /// </summary>
        /// <param name="value">The given payload value.</param>
        /// <param name="edmTypeReference">The expected type reference from model.</param>
        /// <returns>The converted value of the type.</returns>
        public virtual object ConvertFromPayloadValue(object value, IEdmTypeReference edmTypeReference)
        {
            IEdmPrimitiveTypeReference primitiveTypeReference = edmTypeReference as IEdmPrimitiveTypeReference;

            Debug.Assert(primitiveTypeReference != null, "primitiveTypeReference != null");
            if (primitiveTypeReference.PrimitiveKind() == EdmPrimitiveTypeKind.PrimitiveType)
            {
                return(value);
            }

            try
            {
                Type targetType = EdmLibraryExtensions.GetPrimitiveClrType(primitiveTypeReference.PrimitiveDefinition(), false);

                string stringValue = value as string;
                if (stringValue != null)
                {
                    return(ConvertStringValue(stringValue, targetType));
                }
                else if (value is Int32)
                {
                    return(ConvertInt32Value((int)value, targetType, primitiveTypeReference));
                }
                else if (value is Decimal)
                {
                    Decimal decimalValue = (Decimal)value;
                    if (targetType == typeof(Int64))
                    {
                        return(Convert.ToInt64(decimalValue));
                    }

                    if (targetType == typeof(Double))
                    {
                        return(Convert.ToDouble(decimalValue));
                    }

                    if (targetType == typeof(Single))
                    {
                        return(Convert.ToSingle(decimalValue));
                    }

                    if (targetType != typeof(Decimal))
                    {
                        throw new ODataException(ODataErrorStrings.ODataJsonReaderUtils_CannotConvertDecimal(primitiveTypeReference.FullName()));
                    }
                }
                else if (value is Double)
                {
                    Double doubleValue = (Double)value;
                    if (targetType == typeof(Single))
                    {
                        return(Convert.ToSingle(doubleValue));
                    }

                    if (targetType != typeof(Double))
                    {
                        throw new ODataException(ODataErrorStrings.ODataJsonReaderUtils_CannotConvertDouble(primitiveTypeReference.FullName()));
                    }
                }
                else if (value is bool)
                {
                    if (targetType != typeof(bool))
                    {
                        throw new ODataException(ODataErrorStrings.ODataJsonReaderUtils_CannotConvertBoolean(primitiveTypeReference.FullName()));
                    }
                }
                else if (value is DateTime)
                {
                    if (targetType != typeof(DateTime))
                    {
                        throw new ODataException(ODataErrorStrings.ODataJsonReaderUtils_CannotConvertDateTime(primitiveTypeReference.FullName()));
                    }
                }
                else if (value is DateTimeOffset)
                {
                    if (targetType != typeof(DateTimeOffset))
                    {
                        throw new ODataException(ODataErrorStrings.ODataJsonReaderUtils_CannotConvertDateTimeOffset(primitiveTypeReference.FullName()));
                    }
                }
            }
            catch (Exception e)
            {
                if (!ExceptionUtils.IsCatchableExceptionType(e))
                {
                    throw;
                }

                throw ReaderValidationUtils.GetPrimitiveTypeConversionException(primitiveTypeReference, e, value.ToString());
            }

            // otherwise just return the value without doing any conversion
            return(value);
        }