Exemplo n.º 1
0
        /// <summary>
        /// Determines if the given primitive value is of a basic type where we can rely on just the JSON representation to convey type information.
        /// If so, we don't have to write the type name.
        /// </summary>
        /// <param name="primitiveValue">The primitive value in question.</param>
        /// <param name="valueTypeReference">The type of the primitive value.</param>
        /// <returns>true if the given primitive value is of a basic JSON type, false otherwise.</returns>
        internal static bool ValueTypeMatchesJsonType(ODataPrimitiveValue primitiveValue, IEdmPrimitiveTypeReference valueTypeReference)
        {
#if ODATALIB
#endif

            switch (valueTypeReference.PrimitiveKind())
            {
                // If the value being serialized is of a basic type where we can rely on just the JSON representation to convey type information, then never write the type name.
                case EdmPrimitiveTypeKind.Int32:
                case EdmPrimitiveTypeKind.String:
                case EdmPrimitiveTypeKind.Boolean:
                    return true;

                case EdmPrimitiveTypeKind.Double:
                    double doubleValue = (double)primitiveValue.Value;

                    // If a double value is positive infinity, negative infinity, or NaN, we serialize the double as a string.
                    // Thus the reader can't infer the type from the JSON representation, and we must write the type name explicitly 
                    // (i.e., if the property is open or the property type is assumed to be unknown, as is the case when writing in full metadata mode).
                    return !IsDoubleValueSerializedAsString(doubleValue);
                
                default:
                    return false;
            }
        }
        /// <summary>
        /// Creates an <see cref="ODataPrimitiveValue"/> for the object represented by <paramref name="graph"/>.
        /// </summary>
        /// <param name="graph">The primitive value.</param>
        /// <param name="primitiveType">The EDM primitive type of the value.</param>
        /// <param name="writeContext">The serializer write context.</param>
        /// <returns>The created <see cref="ODataPrimitiveValue"/>.</returns>
        public override ODataPrimitiveValue CreateODataPrimitiveValue(
            object graph,
            IEdmPrimitiveTypeReference primitiveType,
            ODataSerializerContext writeContext)
        {
            // The EDM type of the "graph" would override the EDM type of the property when
            // OData Web API infers the primitiveType. Thus for "graph" of System.DateTime,
            // the primitiveType is always Edm.DateTimeOffset.
            //
            // In EF, System.DateTime is used for SqlDate, SqlDateTime and SqlDateTime2.
            // All of them have no time zone information thus it is safe to clear the time
            // zone when converting the "graph" to a DateTimeOffset.
            if (primitiveType != null && primitiveType.IsDateTimeOffset() && graph is DateTime)
            {
                // If DateTime.Kind equals Local, offset should equal the offset of the system's local time zone
                if (((DateTime)graph).Kind == DateTimeKind.Local)
                {
                    graph = new DateTimeOffset((DateTime)graph, TimeZoneInfo.Local.GetUtcOffset((DateTime)graph));
                }
                else
                {
                    graph = new DateTimeOffset((DateTime)graph, TimeSpan.Zero);
                }
            }

            return base.CreateODataPrimitiveValue(graph, primitiveType, writeContext);
        }
 public void Init()
 {
     this._intType = EdmCoreModel.Instance.GetInt32(false);
     this._value1 = new EdmIntegerConstant(1);
     this._value2 = new EdmIntegerConstant(2);
     this._collection = new ClientEdmCollectionValue(this._intType, new IEdmValue[] { this._value1, this._value2 });
 }
Exemplo n.º 4
0
        /// <summary>
        /// Compute the result type of a binary operator based on the type of its operands and the operator kind.
        /// </summary>
        /// <param name="typeReference">The type reference of the operators.</param>
        /// <param name="operatorKind">The kind of operator.</param>
        /// <returns>The result type reference of the binary operator.</returns>
        internal static IEdmPrimitiveTypeReference GetBinaryOperatorResultType(IEdmPrimitiveTypeReference typeReference, BinaryOperatorKind operatorKind)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(typeReference != null, "type != null");

            switch (operatorKind)
            {
                case BinaryOperatorKind.Or:                 // fall through
                case BinaryOperatorKind.And:                // fall through
                case BinaryOperatorKind.Equal:              // fall through
                case BinaryOperatorKind.NotEqual:           // fall through
                case BinaryOperatorKind.GreaterThan:        // fall through
                case BinaryOperatorKind.GreaterThanOrEqual: // fall through
                case BinaryOperatorKind.LessThan:           // fall through
                case BinaryOperatorKind.LessThanOrEqual:
                    return EdmCoreModel.Instance.GetBoolean(typeReference.IsNullable);

                case BinaryOperatorKind.Add:        // fall through
                case BinaryOperatorKind.Subtract:   // fall through
                case BinaryOperatorKind.Multiply:   // fall through
                case BinaryOperatorKind.Divide:     // fall through
                case BinaryOperatorKind.Modulo:
                    return typeReference;

                default:
                    throw new ODataException(Strings.General_InternalError(InternalErrorCodes.QueryNodeUtils_BinaryOperatorResultType_UnreachableCodepath));
            }
        }
        /// <summary>
        /// Creates an <see cref="ODataPrimitiveValue"/> for the object represented by <paramref name="graph"/>.
        /// </summary>
        /// <param name="graph">The primitive value.</param>
        /// <param name="primitiveType">The EDM primitive type of the value.</param>
        /// <param name="writeContext">The serializer write context.</param>
        /// <returns>The created <see cref="ODataPrimitiveValue"/>.</returns>
        public virtual ODataPrimitiveValue CreateODataPrimitiveValue(object graph, IEdmPrimitiveTypeReference primitiveType,
            ODataSerializerContext writeContext)
        {
            ODataMetadataLevel metadataLevel = writeContext != null ? writeContext.MetadataLevel : ODataMetadataLevel.Default;

            // TODO: Bug 467598: validate the type of the object being passed in here with the underlying primitive type. 
            return CreatePrimitive(graph, primitiveType, metadataLevel);
        }
Exemplo n.º 6
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;
 }
Exemplo n.º 7
0
        /// <summary>
        /// Converts a primitive OData value to the corresponding <see cref="IEdmDelayedValue"/>.
        /// </summary>
        /// <param name="primitiveValue">The primitive OData value to convert.</param>
        /// <param name="type">The <see cref="IEdmTypeReference"/> for the primitive value (if available).</param>
        /// <returns>An <see cref="IEdmDelayedValue"/> for the <paramref name="primitiveValue"/>.</returns>
        internal static IEdmDelayedValue ConvertPrimitiveValue(object primitiveValue, IEdmPrimitiveTypeReference type)
        {
#if !ASTORIA_CLIENT
#endif
            Debug.Assert(primitiveValue != null, "primitiveValue != null");

            TypeCode typeCode = PlatformHelpers.GetTypeCode(primitiveValue.GetType());
            switch (typeCode)
            {
                case TypeCode.Boolean:
                    type = EnsurePrimitiveType(type, EdmPrimitiveTypeKind.Boolean);
                    return new EdmBooleanConstant(type, (bool)primitiveValue);

                case TypeCode.Byte:
                    type = EnsurePrimitiveType(type, EdmPrimitiveTypeKind.Byte);
                    return new EdmIntegerConstant(type, (byte)primitiveValue);

                case TypeCode.SByte:
                    type = EnsurePrimitiveType(type, EdmPrimitiveTypeKind.SByte);
                    return new EdmIntegerConstant(type, (sbyte)primitiveValue);

                case TypeCode.Int16:
                    type = EnsurePrimitiveType(type, EdmPrimitiveTypeKind.Int16);
                    return new EdmIntegerConstant(type, (Int16)primitiveValue);

                case TypeCode.Int32:
                    type = EnsurePrimitiveType(type, EdmPrimitiveTypeKind.Int32);
                    return new EdmIntegerConstant(type, (Int32)primitiveValue);

                case TypeCode.Int64:
                    type = EnsurePrimitiveType(type, EdmPrimitiveTypeKind.Int64);
                    return new EdmIntegerConstant(type, (Int64)primitiveValue);

                case TypeCode.Decimal:
                    IEdmDecimalTypeReference decimalType = (IEdmDecimalTypeReference)EnsurePrimitiveType(type, EdmPrimitiveTypeKind.Decimal);
                    return new EdmDecimalConstant(decimalType, (decimal)primitiveValue);

                case TypeCode.Single:
                    type = EnsurePrimitiveType(type, EdmPrimitiveTypeKind.Single);
                    return new EdmFloatingConstant(type, (Single)primitiveValue);

                case TypeCode.Double:
                    type = EnsurePrimitiveType(type, EdmPrimitiveTypeKind.Double);
                    return new EdmFloatingConstant(type, (double)primitiveValue);

                case TypeCode.String:
                    IEdmStringTypeReference stringType = (IEdmStringTypeReference)EnsurePrimitiveType(type, EdmPrimitiveTypeKind.String);
                    return new EdmStringConstant(stringType, (string)primitiveValue);

                default:
                    return ConvertPrimitiveValueWithoutTypeCode(primitiveValue, type);
            }
        }
Exemplo n.º 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);
        }
Exemplo n.º 9
0
        public void GetClrTypeWorksAsExpectedForSpatialPrimitive(EdmPrimitiveTypeKind kind, Type type)
        {
            // Arrange
            IEdmPrimitiveTypeReference primitiveType1 = EdmCoreModel.Instance.GetPrimitive(kind, true);
            IEdmPrimitiveTypeReference primitiveType2 = EdmCoreModel.Instance.GetPrimitive(kind, false);

            // Act
            Type clrType1 = EdmModel.GetClrType(primitiveType1);
            Type clrType2 = EdmModel.GetClrType(primitiveType2);

            // Assert
            Assert.Same(clrType1, clrType2);
            Assert.Same(type, clrType1);
        }
Exemplo n.º 10
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)
        {
            DebugUtils.CheckNoExternalCallers();
            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;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Asynchronously reads the content of a text reader as string and, if <paramref name="expectedPrimitiveTypeReference"/> is specified and primitive type conversion
        /// is enabled, converts the string to the expected type.
        /// </summary>
        /// <param name="expectedPrimitiveTypeReference">The expected type of the value being read or null if no type conversion should be performed.</param>
        /// <returns>
        /// A task that represents the asynchronous read operation.
        /// The value of the TResult parameter contains the raw value that was read from the text reader
        /// either as string or converted to the provided <paramref name="expectedPrimitiveTypeReference"/>.
        /// </returns>
        private async Task <object> ReadRawValueAsync(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
        {
            string stringFromStream = await this.textReader.ReadToEndAsync()
                                      .ConfigureAwait(false);

            if (expectedPrimitiveTypeReference != null && this.MessageReaderSettings.EnablePrimitiveTypeConversion)
            {
                return(ODataRawValueUtils.ConvertStringToPrimitive(stringFromStream, expectedPrimitiveTypeReference));
            }
            else
            {
                return(stringFromStream);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Try and parse spatial type from the json payload.
        /// </summary>
        /// <param name="jsonReader">The JSON reader to read from.</param>
        /// <param name="insideJsonObjectValue">true if the reader is positioned on the first property of the value which is a JSON Object
        ///     (or the second property if the first one was odata.type).</param>
        /// <param name="inputContext">The input context with all the settings.</param>
        /// <param name="expectedValueTypeReference">Expected edm property type.</param>
        /// <param name="validateNullValue">true to validate null values; otherwise false.</param>
        /// <param name="recursionDepth">The recursion depth to start with.</param>
        /// <param name="propertyName">The name of the property whose value is being read, if applicable (used for error reporting).</param>
        /// <returns>An instance of the spatial type.</returns>
        internal static async Task <ISpatial> ReadSpatialValueAsync(
            IJsonReaderAsync jsonReader,
            bool insideJsonObjectValue,
            ODataInputContext inputContext,
            IEdmPrimitiveTypeReference expectedValueTypeReference,
            bool validateNullValue,
            int recursionDepth,
            string propertyName)
        {
            Debug.Assert(jsonReader != null, "jsonReader != null");
            Debug.Assert(inputContext != null, "inputContext != null");
            Debug.Assert(expectedValueTypeReference != null, "expectedValueTypeReference != null");
            Debug.Assert(expectedValueTypeReference.IsSpatial(), "TryParseSpatialType must be called only with spatial types");

            // Spatial value can be either null constant or a JSON object
            // If it's a null primitive value, report a null value.
            if (!insideJsonObjectValue &&
                await TryReadNullValueAsync(jsonReader, inputContext, expectedValueTypeReference, validateNullValue, propertyName)
                .ConfigureAwait(false))
            {
                return(null);
            }

            ISpatial spatialValue = null;

            if (insideJsonObjectValue || jsonReader.NodeType == JsonNodeType.StartObject)
            {
                Dictionary <string, object> jsonObject = await ReadObjectValueAsync(jsonReader, insideJsonObjectValue, inputContext, recursionDepth)
                                                         .ConfigureAwait(false);

                GeoJsonObjectFormatter jsonObjectFormatter =
                    SpatialImplementation.CurrentImplementation.CreateGeoJsonObjectFormatter();
                if (expectedValueTypeReference.IsGeography())
                {
                    spatialValue = jsonObjectFormatter.Read <Geography>(jsonObject);
                }
                else
                {
                    spatialValue = jsonObjectFormatter.Read <Geometry>(jsonObject);
                }
            }

            if (spatialValue == null)
            {
                throw new ODataException(ODataErrorStrings.ODataJsonReaderCoreUtils_CannotReadSpatialPropertyValue);
            }

            return(spatialValue);
        }
        /// <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));
        }
Exemplo n.º 14
0
        /// <summary>Adds a key property to the specified <paramref name="structuredType"/>.</summary>
        /// <param name="structuredType">The type to add the property to.</param>
        /// <param name="name">The name of the property to add.</param>
        /// <param name="propertyType">The CLR type of the property to add. This can be only a primitive type.</param>
        /// <param name="concurrencyMode">Concurrency mode of the property to add.</param>
        private IEdmStructuralProperty AddPrimitiveProperty(IEdmStructuredType structuredType, string name, Type propertyType, EdmConcurrencyMode concurrencyMode)
        {
            PropertyInfo propertyInfo = null;

            if (propertyType == null)
            {
                //TODO: Fix this so GetInstanceType works
                //propertyInfo = structuredType.GetInstanceType(this).GetProperty(name);
                propertyType = propertyInfo != null ? propertyInfo.PropertyType : null;
            }

            IEdmPrimitiveTypeReference typeReference = MetadataUtils.GetPrimitiveTypeReference(propertyType);

            return(AddStructuralProperty(structuredType, name, concurrencyMode, typeReference));
        }
        public void CreateODataValue_PrimitiveValue()
        {
            // Arrange
            IEdmPrimitiveTypeReference edmPrimitiveType = typeof(int).GetEdmPrimitiveTypeReference();
            var serializer = new ODataPrimitiveSerializer();

            // Act
            var odataValue = serializer.CreateODataValue(20, edmPrimitiveType, writeContext: null);

            // Assert
            Assert.NotNull(odataValue);
            ODataPrimitiveValue primitiveValue = Assert.IsType <ODataPrimitiveValue>(odataValue);

            Assert.Equal(20, primitiveValue.Value);
        }
        public void CreateODataValue_ReturnsDateTimeOffset_ForDateTime_ByDefault()
        {
            // Arrange
            IEdmPrimitiveTypeReference edmPrimitiveType = typeof(DateTime).GetEdmPrimitiveTypeReference();
            ODataPrimitiveSerializer   serializer       = new ODataPrimitiveSerializer();
            DateTime dt = new DateTime(2014, 10, 27);

            // Act
            ODataValue odataValue = serializer.CreateODataValue(dt, edmPrimitiveType, new ODataSerializerContext());

            // Assert
            ODataPrimitiveValue primitiveValue = Assert.IsType <ODataPrimitiveValue>(odataValue);

            Assert.Equal(new DateTimeOffset(dt), primitiveValue.Value);
        }
        public void AddTypeNameAnnotationAsNeeded_AddsAnnotation_InJsonLightMetadataMode()
        {
            // Arrange
            IEdmPrimitiveTypeReference edmPrimitiveType = typeof(short).GetEdmPrimitiveTypeReference();
            ODataPrimitiveValue        primitive        = new ODataPrimitiveValue((short)1);

            // Act
            ODataPrimitiveSerializer.AddTypeNameAnnotationAsNeeded(primitive, edmPrimitiveType, ODataMetadataLevel.Full);

            // Assert
            ODataTypeAnnotation annotation = primitive.TypeAnnotation;

            Assert.NotNull(annotation); // Guard
            Assert.Equal("Edm.Int16", annotation.TypeName);
        }
Exemplo n.º 18
0
        private static bool TryParse <T>(string input, IEdmPrimitiveTypeReference asType, out T realResult)
        {
            realResult = default(T);

            object result;
            UriLiteralParsingException exception;
            bool parseSuceeded = UriPrimitiveTypeParser.Instance.TryParseUriStringToType(input, asType, out result, out exception);

            if (parseSuceeded)
            {
                realResult = (T)result;
            }

            return(parseSuceeded);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Gets the type name from the given <paramref name="value"/>.
        /// </summary>
        /// <param name="value">The value to get the type name from. This can be an ODataPrimitiveValue, an ODataCollectionValue or a Clr primitive object.</param>
        /// <returns>The type name for the given <paramref name="value"/>.</returns>
        protected static string GetTypeNameFromValue(object value)
        {
            Debug.Assert(value != null, "value != null");

            ODataPrimitiveValue primitiveValue = value as ODataPrimitiveValue;

            if (primitiveValue != null)
            {
                // primitiveValueTypeReference == null means: the EDM type of the primitive value cannot be determined.
                // This could possibly be due to value being an unsigned int.
                // In this case, simply return null because:
                //   - If the property is regular property, the type is not needed since service model knows its exact type.
                //   - If the property is dynamic property, ODL does not support dynamic property containing unsigned int value
                //     since we don't know its underlying type as well as how to serialize it.
                IEdmPrimitiveTypeReference primitiveValueTypeReference = EdmLibraryExtensions.GetPrimitiveTypeReference(primitiveValue.Value.GetType());
                return(primitiveValueTypeReference == null ? null : primitiveValueTypeReference.FullName());
            }

            ODataEnumValue enumValue = value as ODataEnumValue;

            if (enumValue != null)
            {
                return(enumValue.TypeName);
            }

            ODataResourceValue resourceValue = value as ODataResourceValue;

            if (resourceValue != null)
            {
                return(resourceValue.TypeName);
            }

            ODataCollectionValue collectionValue = value as ODataCollectionValue;

            if (collectionValue != null)
            {
                return(EdmLibraryExtensions.GetCollectionTypeFullName(collectionValue.TypeName));
            }

            IEdmPrimitiveTypeReference primitiveTypeReference = EdmLibraryExtensions.GetPrimitiveTypeReference(value.GetType());

            if (primitiveTypeReference == null)
            {
                throw new ODataException(Strings.ValidationUtils_UnsupportedPrimitiveType(value.GetType().FullName));
            }

            return(primitiveTypeReference.FullName());
        }
        public void CreateODataValue_ReturnsDate_ForDateTime()
        {
            // Arrange
            IEdmPrimitiveTypeReference edmPrimitiveType = EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(typeof(Date));
            ODataPrimitiveSerializer   serializer       = new ODataPrimitiveSerializer();
            DateTime dt = new DateTime(2014, 10, 27);

            // Act
            ODataValue odataValue = serializer.CreateODataValue(dt, edmPrimitiveType, new ODataSerializerContext());

            // Assert
            ODataPrimitiveValue primitiveValue = Assert.IsType <ODataPrimitiveValue>(odataValue);

            Assert.IsType <Date>(primitiveValue.Value);
            Assert.Equal(new Date(dt.Year, dt.Month, dt.Day), primitiveValue.Value);
        }
Exemplo n.º 21
0
        private static IEdmPrimitiveTypeReference CreateSpatialTypeReference(IEdmPrimitiveTypeReference primitiveTypeReference, bool nullableFacet, List <KeyValuePair <string, object> > annotations)
        {
            object obj2;

            if ((annotations.Count == 0) || !TryFindAndRemoveAnnotation(annotations, "SRID", out obj2))
            {
                if (primitiveTypeReference.IsNullable != nullableFacet)
                {
                    return(new EdmSpatialTypeReference(primitiveTypeReference.PrimitiveDefinition(), nullableFacet, null));
                }
                return(primitiveTypeReference);
            }
            int num = ConvertAnnotationValue <int>(obj2, "SRID");

            return(new EdmSpatialTypeReference(primitiveTypeReference.PrimitiveDefinition(), nullableFacet, new int?(num)));
        }
Exemplo n.º 22
0
        private static IEdmPrimitiveTypeReference CreateBinaryTypeReference(IEdmPrimitiveTypeReference primitiveTypeReference, bool nullableFacet, List <KeyValuePair <string, object> > annotations)
        {
            bool flag;

            if (annotations.Count == 0)
            {
                if (primitiveTypeReference.IsNullable != nullableFacet)
                {
                    return(new EdmBinaryTypeReference(primitiveTypeReference.PrimitiveDefinition(), nullableFacet));
                }
                return(primitiveTypeReference);
            }
            int?maxLengthAnnotation = GetMaxLengthAnnotation(annotations, out flag);

            return(new EdmBinaryTypeReference(primitiveTypeReference.PrimitiveDefinition(), nullableFacet, flag, maxLengthAnnotation, GetFixedLengthAnnotation(annotations)));
        }
        /// <summary>
        /// Maps a CLR type to standard CLR type.
        /// </summary>
        /// <param name="clrType">The potential non-standard CLR type.</param>
        /// <returns>The standard CLR type or the input CLR type itself.</returns>
        public virtual Type MapTo(Type clrType)
        {
            if (clrType == null)
            {
                return(null);
            }

            IEdmPrimitiveTypeReference edmTypeRef = GetEdmPrimitiveType(clrType);

            if (edmTypeRef != null)
            {
                return(GetClrPrimitiveType(edmTypeRef));
            }

            return(clrType);
        }
        public ODataCollectionSerializerTests()
        {
            _model = SerializationTestsHelpers.SimpleCustomerOrderModel();
            _customerSet = _model.FindDeclaredEntityContainer("Default.Container").FindEntitySet("Customers");
            _edmIntType = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Int32, isNullable: false);
            _customer = new Customer()
            {
                FirstName = "Foo",
                LastName = "Bar",
                ID = 10,
            };

            ODataSerializerProvider serializerProvider = new DefaultODataSerializerProvider();
            _collectionType = new EdmCollectionTypeReference(new EdmCollectionType(_edmIntType), isNullable: false);
            _serializer = new ODataCollectionSerializer(serializerProvider);
        }
Exemplo n.º 25
0
        public void ReadSpatialProperty(string propertyName, string payload, IEdmPrimitiveTypeReference edmPrimitiveTypeReference, Action <ISpatial> assertAction)
        {
            using (var reader = CreateJsonReader(payload))
            {
                var spatialValue = ODataJsonReaderCoreUtils.ReadSpatialValue(
                    jsonReader: reader,
                    insideJsonObjectValue: false,
                    inputContext: this.inputContext,
                    expectedValueTypeReference: edmPrimitiveTypeReference,
                    validateNullValue: false,
                    recursionDepth: -1,
                    propertyName: propertyName);

                assertAction(spatialValue);
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Returns the instance type for the specified <paramref name="typeReference"/> or null if none exists.
        /// </summary>
        /// <param name="typeReference">The type reference to get the instance type for.</param>
        /// <param name="model">The model containing annotations.</param>
        /// <returns>The instance type for the <paramref name="typeReference"/> or null if no instance type exists.</returns>
        /// <remarks>All primitive type references are guaranteed to have an instance type.</remarks>
        public static Type GetInstanceType(this IEdmTypeReference typeReference, IEdmModel model)
        {
            ExceptionUtils.CheckArgumentNotNull(typeReference, "typeReference");
            ExceptionUtils.CheckArgumentNotNull(model, "model");

            if (typeReference.TypeKind() == EdmTypeKind.Primitive)
            {
                IEdmPrimitiveTypeReference primitiveTypeReference = typeReference.AsPrimitive();

                return(EdmLibraryExtensions.GetPrimitiveClrType(primitiveTypeReference));
            }

            ODataQueryEdmTypeAnnotation annotation = model.GetAnnotationValue <ODataQueryEdmTypeAnnotation>(typeReference.Definition);

            return(annotation == null ? null : annotation.InstanceType);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Read a top-level value.
        /// </summary>
        /// <param name="expectedPrimitiveTypeReference">The expected primitive type for the value to be read; null if no expected type is available.</param>
        /// <returns>An <see cref="object"/> representing the read value.</returns>
        private object ReadValueImplementation(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
        {
            // if an expected primitive type is specified it trumps the content type/reader payload kind
            bool readBinary = ReadAsBinary(expectedPrimitiveTypeReference);

            if (readBinary)
            {
                return(this.ReadBinaryValue());
            }
            else
            {
                Debug.Assert(this.textReader == null, "this.textReader == null");
                InitializeTextReader();
                return(this.ReadRawValue(expectedPrimitiveTypeReference));
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Figures out if the given clr type is nonstandard edm primitive like uint, ushort, char[] etc.
        /// and returns the corresponding clr type to which we map like uint => long.
        /// </summary>
        /// <param name="clrType">The potential non-standard CLR type.</param>
        /// <param name="isNonstandardEdmPrimitive">A boolean value out to indicate whether the input CLR type is standard OData primitive type.</param>
        /// <returns>The standard CLR type or the input CLR type itself.</returns>
        public static Type IsNonstandardEdmPrimitive(this Type clrType, out bool isNonstandardEdmPrimitive)
        {
            IEdmPrimitiveTypeReference edmType = clrType?.GetEdmPrimitiveTypeReference();

            if (edmType == null)
            {
                isNonstandardEdmPrimitive = false;
                return(clrType);
            }

            Type reverseLookupClrType = edmType.GetClrPrimitiveType();

            isNonstandardEdmPrimitive = (clrType != reverseLookupClrType);

            return(reverseLookupClrType);
        }
Exemplo n.º 29
0
        // figures out if the given clr type is nonstandard edm primitive like uint, ushort, char[] etc.
        // and returns the corresponding clr type to which we map like uint => long.
        public static Type IsNonstandardEdmPrimitive(Type type, out bool isNonstandardEdmPrimitive)
        {
            IEdmPrimitiveTypeReference edmType = GetEdmPrimitiveTypeReferenceOrNull(type);

            if (edmType == null)
            {
                isNonstandardEdmPrimitive = false;
                return(type);
            }

            Type reverseLookupClrType = GetClrType(edmType, EdmCoreModel.Instance);

            isNonstandardEdmPrimitive = (type != reverseLookupClrType);

            return(reverseLookupClrType);
        }
        public void CreateODataValue_ReturnsTimeOfDay_ForTimeSpan()
        {
            // Arrange
            IEdmPrimitiveTypeReference edmPrimitiveType = typeof(TimeOfDay).GetEdmPrimitiveTypeReference();
            ODataPrimitiveSerializer   serializer       = new ODataPrimitiveSerializer();
            TimeSpan ts = new TimeSpan(0, 10, 11, 12, 13);

            // Act
            ODataValue odataValue = serializer.CreateODataValue(ts, edmPrimitiveType, new ODataSerializerContext());

            // Assert
            ODataPrimitiveValue primitiveValue = Assert.IsType <ODataPrimitiveValue>(odataValue);

            Assert.IsType <TimeOfDay>(primitiveValue.Value);
            Assert.Equal(new TimeOfDay(ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds), primitiveValue.Value);
        }
Exemplo n.º 31
0
        internal static bool CanConvertTo(IEdmTypeReference sourceReference, IEdmTypeReference targetReference)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(sourceReference != null, "sourceReference != null");
            Debug.Assert(targetReference != null, "targetReference != null");

            //// Copy of the ResourceQueryParser.ExpressionParser.IsCompatibleWith method.

            if (sourceReference.IsEquivalentTo(targetReference))
            {
                return(true);
            }

            if (targetReference.IsODataComplexTypeKind() || targetReference.IsODataEntityTypeKind())
            {
                // for structured types, use IsAssignableFrom
                return(EdmLibraryExtensions.IsAssignableFrom(
                           (IEdmStructuredType)targetReference.Definition,
                           (IEdmStructuredType)sourceReference.Definition));
            }

            // NOTE: this is to deal with open types that are not yet supported.
            if (IsOpenPropertyType(targetReference))
            {
                return(true);
            }

            //// This rule stops the parser from considering nullable types as incompatible
            //// with non-nullable types. We have however implemented this rule because we just
            //// access underlying rules. C# requires an explicit .Value access, and EDM has no
            //// nullablity on types and (at the model level) implements null propagation.
            ////
            //// if (sourceReference.IsNullable && !targetReference.IsNullable)
            //// {
            ////     return false;
            //// }

            IEdmPrimitiveTypeReference sourcePrimitiveTypeReference = sourceReference.AsPrimitiveOrNull();
            IEdmPrimitiveTypeReference targetPrimitiveTypeReference = targetReference.AsPrimitiveOrNull();

            if (sourcePrimitiveTypeReference == null || targetPrimitiveTypeReference == null)
            {
                return(false);
            }

            return(MetadataUtilsCommon.CanConvertPrimitiveTypeTo(sourcePrimitiveTypeReference.PrimitiveDefinition(), targetPrimitiveTypeReference.PrimitiveDefinition()));
        }
        public static DataType ConvertToTaupoPrimitiveDataType(IEdmPrimitiveTypeReference edmPrimitiveTypeReference)
        {
            PrimitiveDataType    result        = null;
            EdmPrimitiveTypeKind primitiveKind = edmPrimitiveTypeReference.PrimitiveKind();

            if (!facetlessDataTypeLookup.TryGetValue(primitiveKind, out result))
            {
                switch (primitiveKind)
                {
                case EdmPrimitiveTypeKind.Binary:
                    var edmBinary = edmPrimitiveTypeReference.AsBinary();
                    result = EdmDataTypes.Binary(edmBinary.MaxLength);
                    break;

                case EdmPrimitiveTypeKind.DateTimeOffset:
                    var edmDateTimeOffset = edmPrimitiveTypeReference.AsTemporal();
                    result = EdmDataTypes.DateTimeOffset(edmDateTimeOffset.Precision);
                    break;

                case EdmPrimitiveTypeKind.Decimal:
                    var edmDecimal = edmPrimitiveTypeReference.AsDecimal();
                    result = EdmDataTypes.Decimal(edmDecimal.Precision, edmDecimal.Scale);
                    break;

                case EdmPrimitiveTypeKind.String:
                    var edmString = edmPrimitiveTypeReference.AsString();
                    var maxLength = edmString.MaxLength;
                    if (edmString.IsUnbounded == true)
                    {
                        maxLength = MaxLengthMaxTaupoDefaultValue;
                    }

                    result = EdmDataTypes.String(maxLength, edmString.IsUnicode);
                    break;

                case EdmPrimitiveTypeKind.Duration:
                    var edmTime = edmPrimitiveTypeReference.AsTemporal();
                    result = EdmDataTypes.Time(edmTime.Precision);
                    break;

                default:
                    throw new TaupoInvalidOperationException("unexpected Edm Primitive Type Kind: " + primitiveKind);
                }
            }

            return(result.Nullable(edmPrimitiveTypeReference.IsNullable));
        }
        public static DataType ConvertToTaupoPrimitiveDataType(IEdmPrimitiveTypeReference edmPrimitiveTypeReference)
        {
            PrimitiveDataType result = null;
            EdmPrimitiveTypeKind primitiveKind = edmPrimitiveTypeReference.PrimitiveKind();
            if (!facetlessDataTypeLookup.TryGetValue(primitiveKind, out result))
            {
                switch (primitiveKind)
                {
                    case EdmPrimitiveTypeKind.Binary:
                        var edmBinary = edmPrimitiveTypeReference.AsBinary();
                        result = EdmDataTypes.Binary(edmBinary.MaxLength);
                        break;

                    case EdmPrimitiveTypeKind.DateTimeOffset:
                        var edmDateTimeOffset = edmPrimitiveTypeReference.AsTemporal();
                        result = EdmDataTypes.DateTimeOffset(edmDateTimeOffset.Precision);
                        break;

                    case EdmPrimitiveTypeKind.Decimal:
                        var edmDecimal = edmPrimitiveTypeReference.AsDecimal();
                        result = EdmDataTypes.Decimal(edmDecimal.Precision, edmDecimal.Scale);
                        break;

                    case EdmPrimitiveTypeKind.String:
                        var edmString = edmPrimitiveTypeReference.AsString();
                        var maxLength = edmString.MaxLength;
                        if (edmString.IsUnbounded == true)
                        {
                            maxLength = MaxLengthMaxTaupoDefaultValue; 
                        }

                        result = EdmDataTypes.String(maxLength, edmString.IsUnicode);
                        break;

                    case EdmPrimitiveTypeKind.Duration:
                        var edmTime = edmPrimitiveTypeReference.AsTemporal();
                        result = EdmDataTypes.Time(edmTime.Precision);
                        break;

                    default:
                        throw new TaupoInvalidOperationException("unexpected Edm Primitive Type Kind: " + primitiveKind);
                }
            }

            return result.Nullable(edmPrimitiveTypeReference.IsNullable);
        }
Exemplo n.º 34
0
        public override ODataPrimitiveValue CreateODataPrimitiveValue(object graph,
                                                                      IEdmPrimitiveTypeReference primitiveType, ODataSerializerContext writeContext)
        {
            ODataPrimitiveValue result = base.CreateODataPrimitiveValue(graph, primitiveType, writeContext);

            if (result?.Value is DateTimeOffset date)
            {
                IDependencyResolver dependencyResolver = writeContext.Request.GetOwinContext()
                                                         .GetDependencyResolver();

                ITimeZoneManager timeZoneManager = dependencyResolver.Resolve <ITimeZoneManager>();

                result = new ODataPrimitiveValue(timeZoneManager.MapFromServerToClient(date));
            }

            return(result);
        }
Exemplo n.º 35
0
        /// <summary>
        /// Converts a primitive data type to type.
        /// </summary>
        /// <param name="primitiveType">The primitive data type to convert.</param>
        /// <returns>The corresponding primitive type.</returns>
        private static IEdmPrimitiveTypeReference GetPrimitiveTypeReference(PrimitiveDataType primitiveType)
        {
            Debug.Assert(primitiveType != null, "primitiveType != null");

            Type systemType = EntityModelUtils.GetPrimitiveClrType(primitiveType);

            // NOTE: if the primitiveType is not nullable but the type reference constructed from the CLR type is,
            //       adjust the nullability if necessary.
            IEdmPrimitiveTypeReference primitiveTypeReference = MetadataUtils.GetPrimitiveTypeReference(systemType);

            if (primitiveType.IsNullable != primitiveTypeReference.IsNullable)
            {
                primitiveTypeReference = (IEdmPrimitiveTypeReference)primitiveTypeReference.Clone(primitiveType.IsNullable);
            }

            return(primitiveTypeReference);
        }
Exemplo n.º 36
0
        /// <summary>
        /// Parses typed literals.
        /// </summary>
        /// <param name="targetTypeReference">Expected type to be parsed.</param>
        /// <returns>The literal token produced by building the given literal.</returns>
        private object ParseTypedLiteral(IEdmPrimitiveTypeReference targetTypeReference)
        {
            object targetValue;

            if (!UriPrimitiveTypeParser.TryUriStringToPrimitive(this.CurrentToken.Text, targetTypeReference, out targetValue))
            {
                string message = o.Strings.UriQueryExpressionParser_UnrecognizedLiteral(
                    targetTypeReference.FullName(),
                    this.CurrentToken.Text,
                    this.CurrentToken.Position,
                    this.ExpressionText);
                throw ParseError(message);
            }

            this.NextToken();
            return(targetValue);
        }
Exemplo n.º 37
0
        private void VisitPrimitiveTypeReference(IEdmPrimitiveTypeReference reference)
        {
            string qualifiedName = reference.FullName();

            if (_types.ContainsKey(qualifiedName))
            {
                return;
            }

            IEdmPrimitiveType primitiveType = reference.PrimitiveDefinition();

            MetaPrimitiveType metaPrimitiveType = new MetaPrimitiveType();

            metaPrimitiveType.QualifiedName = qualifiedName;
            metaPrimitiveType.Name          = primitiveType.Name;
            _types[qualifiedName]           = metaPrimitiveType;
        }
Exemplo n.º 38
0
        public ODataCollectionSerializerTests()
        {
            _model       = SerializationTestsHelpers.SimpleCustomerOrderModel();
            _customerSet = _model.EntityContainer.FindEntitySet("Customers");
            _edmIntType  = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.Int32, isNullable: false);
            _customer    = new Customer()
            {
                FirstName = "Foo",
                LastName  = "Bar",
                ID        = 10,
            };

            ODataSerializerProvider serializerProvider = new DefaultODataSerializerProvider();

            _collectionType = new EdmCollectionTypeReference(new EdmCollectionType(_edmIntType));
            _serializer     = new ODataCollectionSerializer(serializerProvider);
        }
        public void ReadInline_Calls_ReadPrimitive()
        {
            // Arrange
            IEdmPrimitiveTypeReference        primitiveType = EdmCoreModel.Instance.GetInt32(isNullable: true);
            Mock <ODataPrimitiveDeserializer> deserializer  = new Mock <ODataPrimitiveDeserializer>();
            ODataProperty            property    = new ODataProperty();
            ODataDeserializerContext readContext = new ODataDeserializerContext();

            deserializer.Setup(d => d.ReadPrimitive(property, readContext)).Returns(42).Verifiable();

            // Act
            var result = deserializer.Object.ReadInline(property, primitiveType, readContext);

            // Assert
            deserializer.Verify();
            Assert.Equal(42, result);
        }
Exemplo n.º 40
0
        /// <summary>
        /// Reads the content of a text reader as string and, if <paramref name="expectedPrimitiveTypeReference"/> is specified and primitive type conversion
        /// is enabled, converts the string to the expected type.
        /// </summary>
        /// <param name="expectedPrimitiveTypeReference">The expected type of the value being read or null if no type conversion should be performed.</param>
        /// <returns>The raw value that was read from the text reader either as string or converted to the provided <paramref name="expectedPrimitiveTypeReference"/>.</returns>
        private object ReadRawValue(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
        {
            string stringFromStream = this.textReader.ReadToEnd();

            object rawValue;

            if (expectedPrimitiveTypeReference != null && !this.MessageReaderSettings.DisablePrimitiveTypeConversion)
            {
                rawValue = AtomValueUtils.ConvertStringToPrimitive(stringFromStream, expectedPrimitiveTypeReference);
            }
            else
            {
                rawValue = stringFromStream;
            }

            return(rawValue);
        }
Exemplo n.º 41
0
        /// <summary>
        /// Try and parse spatial type from the json payload.
        /// </summary>
        /// <param name="jsonReader">The JSON reader to read from.</param>
        /// <param name="insideJsonObjectValue">true if the reader is positioned on the first property of the value which is a JSON Object 
        ///     (or the second property if the first one was odata.type).</param>
        /// <param name="inputContext">The input context with all the settings.</param>
        /// <param name="expectedValueTypeReference">Expected edm property type.</param>
        /// <param name="validateNullValue">true to validate null values; otherwise false.</param>
        /// <param name="recursionDepth">The recursion depth to start with.</param>
        /// <param name="propertyName">The name of the property whose value is being read, if applicable (used for error reporting).</param>
        /// <returns>An instance of the spatial type.</returns>
        internal static ISpatial ReadSpatialValue(
            BufferingJsonReader jsonReader,
            bool insideJsonObjectValue,
            ODataInputContext inputContext,
            IEdmPrimitiveTypeReference expectedValueTypeReference,
            bool validateNullValue,
            int recursionDepth,
            string propertyName)
        {
            Debug.Assert(jsonReader != null, "jsonReader != null");
            Debug.Assert(inputContext != null, "inputContext != null");
            Debug.Assert(expectedValueTypeReference != null, "expectedValueTypeReference != null");
            Debug.Assert(expectedValueTypeReference.IsSpatial(), "TryParseSpatialType must be called only with spatial types");

            // Spatial value can be either null constant or a JSON object
            // If it's a null primitive value, report a null value.
            if (!insideJsonObjectValue && TryReadNullValue(jsonReader, inputContext, expectedValueTypeReference, validateNullValue, propertyName))
            {
                return null;
            }

            Microsoft.Spatial.ISpatial spatialValue = null;
            if (insideJsonObjectValue || jsonReader.NodeType == JsonNodeType.StartObject)
            {
                IDictionary<string, object> jsonObject = ReadObjectValue(jsonReader, insideJsonObjectValue, inputContext, recursionDepth);
                Microsoft.Spatial.GeoJsonObjectFormatter jsonObjectFormatter =
                    Microsoft.Spatial.SpatialImplementation.CurrentImplementation.CreateGeoJsonObjectFormatter();
                if (EdmLibraryExtensions.IsGeographyType(expectedValueTypeReference))
                {
                    spatialValue = jsonObjectFormatter.Read<Microsoft.Spatial.Geography>(jsonObject);
                }
                else
                {
                    spatialValue = jsonObjectFormatter.Read<Microsoft.Spatial.Geometry>(jsonObject);
                }
            }

            if (spatialValue == null)
            {
                throw new ODataException(ODataErrorStrings.ODataJsonReaderCoreUtils_CannotReadSpatialPropertyValue);
            }

            return spatialValue;
        }
        public override ODataPrimitiveValue CreateODataPrimitiveValue(object graph, IEdmPrimitiveTypeReference primitiveType,
            ODataSerializerContext writeContext)
        {
            var dbGeographyValue = graph as DbGeography;
            if (dbGeographyValue != null)
            {
                // The logic is not included in Restier as publisher layer does not touch provider layer type
                if (dbGeographyValue.SpatialTypeName == GeographyTypeNamePoint)
                {
                    graph = dbGeographyValue.ToGeographyPoint();
                }
                else if (dbGeographyValue.SpatialTypeName == GeographyTypeNameLineString)
                {
                    graph = dbGeographyValue.ToGeographyLineString();
                }
                else if (dbGeographyValue.SpatialTypeName == GeographyTypeNamePolygon)
                {
                    // TODO, convert original value and return converted value
                }
            }

            return base.CreateODataPrimitiveValue(graph, primitiveType, writeContext);
        }
        internal static void AddTypeNameAnnotationAsNeeded(ODataPrimitiveValue primitive, IEdmPrimitiveTypeReference primitiveType,
            ODataMetadataLevel metadataLevel)
        {
            // ODataLib normally has the caller decide whether or not to serialize properties by leaving properties
            // null when values should not be serialized. The TypeName property is different and should always be
            // provided to ODataLib to enable model validation. A separate annotation is used to decide whether or not
            // to serialize the type name (a null value prevents serialization).

            // Note that this annotation should not be used for Atom or JSON verbose formats, as it will interfere with
            // the correct default behavior for those formats.

            Contract.Assert(primitive != null);

            object value = primitive.Value;

            // Only add an annotation if we want to override ODataLib's default type name serialization behavior.
            if (ShouldAddTypeNameAnnotation(metadataLevel))
            {
                string typeName;

                // Provide the type name to serialize (or null to force it not to serialize).
                if (ShouldSuppressTypeNameSerialization(value, metadataLevel))
                {
                    typeName = null;
                }
                else
                {
                    typeName = primitiveType.FullName();
                }

                primitive.SetAnnotation<SerializationTypeNameAnnotation>(new SerializationTypeNameAnnotation
                {
                    TypeName = typeName
                });
            }
        }
Exemplo n.º 44
0
        internal static void AddTypeNameAnnotationAsNeeded(ODataPrimitiveValue primitive, IEdmPrimitiveTypeReference primitiveType,
            ODataMetadataLevel metadataLevel)
        {
            // ODataLib normally has the caller decide whether or not to serialize properties by leaving properties
            // null when values should not be serialized. The TypeName property is different and should always be
            // provided to ODataLib to enable model validation. A separate annotation is used to decide whether or not
            // to serialize the type name (a null value prevents serialization).

            Contract.Assert(primitive != null);

            object value = primitive.Value;
            string typeName = null; // Set null to force the type name not to serialize.

            // Provide the type name to serialize.
            if (!ShouldSuppressTypeNameSerialization(value, metadataLevel))
            {
                typeName = primitiveType.FullName();
            }

            primitive.SetAnnotation<SerializationTypeNameAnnotation>(new SerializationTypeNameAnnotation
            {
                TypeName = typeName
            });
        }
 private object ReadPrimitiveValueImplementation(IEdmPrimitiveTypeReference expectedValueTypeReference, bool validateNullValue)
 {
     if ((expectedValueTypeReference != null) && expectedValueTypeReference.IsSpatial())
     {
         return this.ReadSpatialValue(expectedValueTypeReference, validateNullValue);
     }
     object obj2 = base.JsonReader.ReadPrimitiveValue();
     if ((expectedValueTypeReference != null) && !base.MessageReaderSettings.DisablePrimitiveTypeConversion)
     {
         obj2 = ODataJsonReaderUtils.ConvertValue(obj2, expectedValueTypeReference, base.MessageReaderSettings, base.Version, validateNullValue);
     }
     return obj2;
 }
 public ODataPrimitiveSerializer(IEdmPrimitiveTypeReference edmPrimitiveType)
     : base(edmPrimitiveType, ODataPayloadKind.Property)
 {
 }
        internal static ODataPrimitiveValue CreatePrimitive(object value, IEdmPrimitiveTypeReference primitveType,
            ODataMetadataLevel metadataLevel)
        {
            if (value == null)
            {
                return null;
            }

            object supportedValue = ConvertUnsupportedPrimitives(value);
            ODataPrimitiveValue primitive = new ODataPrimitiveValue(supportedValue);
            AddTypeNameAnnotationAsNeeded(primitive, primitveType, metadataLevel);
            return primitive;
        }
Exemplo n.º 48
0
        /// <summary>
        /// Reads the content of a text reader as string and, if <paramref name="expectedPrimitiveTypeReference"/> is specified and primitive type conversion
        /// is enabled, converts the string to the expected type.
        /// </summary>
        /// <param name="expectedPrimitiveTypeReference">The expected type of the value being read or null if no type conversion should be performed.</param>
        /// <returns>The raw value that was read from the text reader either as string or converted to the provided <paramref name="expectedPrimitiveTypeReference"/>.</returns>
        private object ReadRawValue(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
        {
            string stringFromStream = this.textReader.ReadToEnd();

            object rawValue;
            if (expectedPrimitiveTypeReference != null && !this.MessageReaderSettings.DisablePrimitiveTypeConversion)
            {
                rawValue = AtomValueUtils.ConvertStringToPrimitive(stringFromStream, expectedPrimitiveTypeReference);
            }
            else
            {
                rawValue = stringFromStream;
            }

            return rawValue;
        }
Exemplo n.º 49
0
        /// <summary>
        /// Read a top-level value.
        /// </summary>
        /// <param name="expectedPrimitiveTypeReference">The expected primitive type for the value to be read; null if no expected type is available.</param>
        /// <returns>An <see cref="object"/> representing the read value.</returns>
        private object ReadValueImplementation(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
        {
            // if an expected primitive type is specified it trumps the content type/reader payload kind
            bool readBinary;
            if (expectedPrimitiveTypeReference == null)
            {
                readBinary = this.readerPayloadKind == ODataPayloadKind.BinaryValue;
            }
            else
            {
                if (expectedPrimitiveTypeReference.PrimitiveKind() == EdmPrimitiveTypeKind.Binary)
                {
                    readBinary = true;
                }
                else
                {
                    readBinary = false;
                }
            }

            if (readBinary)
            {
                return this.ReadBinaryValue();
            }
            else
            {
                Debug.Assert(this.textReader == null, "this.textReader == null");
                this.textReader = this.encoding == null ? new StreamReader(this.stream) : new StreamReader(this.stream, this.encoding);
                return this.ReadRawValue(expectedPrimitiveTypeReference);
            }
        }
Exemplo n.º 50
0
        /// <summary>
        /// Asynchronously read a top-level value.
        /// </summary>
        /// <param name="expectedPrimitiveTypeReference">The expected type reference for the value to be read; null if no expected type is available.</param>
        /// <returns>Task which when completed returns an <see cref="object"/> representing the read value.</returns>
        internal override Task<object> ReadValueAsync(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
        {
            DebugUtils.CheckNoExternalCallers();

            // Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message.
            return TaskUtils.GetTaskForSynchronousOperation(() => this.ReadValueImplementation(expectedPrimitiveTypeReference));
        }
Exemplo n.º 51
0
 /// <summary>
 /// Read a top-level value.
 /// </summary>
 /// <param name="expectedPrimitiveTypeReference">The expected primitive type for the value to be read; null if no expected type is available.</param>
 /// <returns>An <see cref="object"/> representing the read value.</returns>
 internal override object ReadValue(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
 {
     DebugUtils.CheckNoExternalCallers();
     return this.ReadValueImplementation(expectedPrimitiveTypeReference);
 }
Exemplo n.º 52
0
 /// <summary>
 /// Creates an <see cref="ODataPrimitiveValue"/> for the object represented by <paramref name="graph"/>.
 /// </summary>
 /// <param name="graph">The primitive value.</param>
 /// <param name="primitiveType">The EDM primitive type of the value.</param>
 /// <param name="writeContext">The serializer write context.</param>
 /// <returns>The created <see cref="ODataPrimitiveValue"/>.</returns>
 public virtual ODataPrimitiveValue CreateODataPrimitiveValue(object graph, IEdmPrimitiveTypeReference primitiveType,
     ODataSerializerContext writeContext)
 {
     // TODO: Bug 467598: validate the type of the object being passed in here with the underlying primitive type. 
     return CreatePrimitive(graph, primitiveType, writeContext);
 }
Exemplo n.º 53
0
        internal static ODataPrimitiveValue CreatePrimitive(object value, IEdmPrimitiveTypeReference primitveType,
            ODataSerializerContext writeContext)
        {
            if (value == null)
            {
                return null;
            }

            object supportedValue = ConvertUnsupportedPrimitives(value);
            ODataPrimitiveValue primitive = new ODataPrimitiveValue(supportedValue);

            if (writeContext != null)
            {
                AddTypeNameAnnotationAsNeeded(primitive, primitveType, writeContext.MetadataLevel);
            }

            return primitive;
        }
Exemplo n.º 54
0
 internal override Task<object> ReadValueAsync(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
 {
     return TaskUtils.GetTaskForSynchronousOperation<object>(() => this.ReadValueImplementation(expectedPrimitiveTypeReference));
 }
 private ISpatial ReadSpatialValue(IEdmPrimitiveTypeReference expectedValueTypeReference, bool validateNullValue)
 {
     ODataVersionChecker.CheckSpatialValue(base.Version);
     if (this.TryReadNullValue(expectedValueTypeReference, validateNullValue))
     {
         return null;
     }
     ISpatial spatial = null;
     if (base.JsonReader.NodeType == JsonNodeType.StartObject)
     {
         IDictionary<string, object> source = this.ReadObjectValue(base.JsonReader);
         GeoJsonObjectFormatter formatter = SpatialImplementation.CurrentImplementation.CreateGeoJsonObjectFormatter();
         if (expectedValueTypeReference.IsGeographyType())
         {
             spatial = formatter.Read<Geography>(source);
         }
         else
         {
             spatial = formatter.Read<Geometry>(source);
         }
     }
     if (spatial == null)
     {
         throw new ODataException(Microsoft.Data.OData.Strings.ODataJsonPropertyAndValueDeserializer_CannotReadSpatialPropertyValue);
     }
     return spatial;
 }
Exemplo n.º 56
0
 private object ReadRawValue(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
 {
     string text = this.textReader.ReadToEnd();
     if ((expectedPrimitiveTypeReference != null) && !base.MessageReaderSettings.DisablePrimitiveTypeConversion)
     {
         return AtomValueUtils.ConvertStringToPrimitive(text, expectedPrimitiveTypeReference);
     }
     return text;
 }
Exemplo n.º 57
0
 internal override object ReadValue(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
 {
     return this.ReadValueImplementation(expectedPrimitiveTypeReference);
 }
        /// <summary>
        /// Read a primitive value from the reader.
        /// </summary>
        /// <param name="actualValueTypeReference">The type of the value to read.</param>
        /// <returns>The value read from the payload and converted as appropriate to the target type.</returns>
        /// <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.
        ///                  
        /// Note that this method will not read null values, those should be handled by the caller already.
        /// </remarks>
        private object ReadPrimitiveValue(IEdmPrimitiveTypeReference actualValueTypeReference)
        {
            Debug.Assert(actualValueTypeReference != null, "actualValueTypeReference != null");
            Debug.Assert(actualValueTypeReference.TypeKind() == EdmTypeKind.Primitive, "Only primitive values can be read by this method.");
            this.AssertXmlCondition(XmlNodeType.Element, XmlNodeType.Attribute);

            object result = AtomValueUtils.ReadPrimitiveValue(this.XmlReader, actualValueTypeReference);

            this.AssertXmlCondition(true, XmlNodeType.EndElement);
            Debug.Assert(result != null, "The method should never return null since it doesn't handle null values.");

            return result;
        }
Exemplo n.º 59
0
 private object ReadValueImplementation(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
 {
     bool flag;
     if (expectedPrimitiveTypeReference == null)
     {
         flag = this.readerPayloadKind == ODataPayloadKind.BinaryValue;
     }
     else if (expectedPrimitiveTypeReference.PrimitiveKind() == EdmPrimitiveTypeKind.Binary)
     {
         flag = true;
     }
     else
     {
         flag = false;
     }
     if (flag)
     {
         return this.ReadBinaryValue();
     }
     this.textReader = (this.encoding == null) ? new StreamReader(this.stream) : new StreamReader(this.stream, this.encoding);
     return this.ReadRawValue(expectedPrimitiveTypeReference);
 }
Exemplo n.º 60
0
		public EdmFloatingConstant(IEdmPrimitiveTypeReference type, double value) : base(type)
		{
			this.@value = value;
		}