/// <summary>
        /// Parses null literals.
        /// </summary>
        /// <param name="expressionLexer">The expression lexer.</param>
        /// <returns>The literal token produced by building the given literal.</returns>
        private static object ParseNullLiteral(this ExpressionLexer expressionLexer)
        {
            Debug.Assert(expressionLexer.CurrentToken.Kind == ExpressionTokenKind.NullLiteral, "this.lexer.CurrentToken.InternalKind == ExpressionTokenKind.NullLiteral");

            expressionLexer.NextToken();
            ODataNullValue nullValue = new ODataNullValue();
            return nullValue;
        }
Exemplo n.º 2
0
        public async Task WriteODataValueAsyncWritesNullValue()
        {
            var value = new ODataNullValue();

            await this.writer.WriteODataValueAsync(value);

            Assert.Equal("null", this.builder.ToString());
        }
Exemplo n.º 3
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));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Parses null literals.
        /// </summary>
        /// <param name="expressionLexer">The expression lexer.</param>
        /// <returns>The literal token produced by building the given literal.</returns>
        private static object ParseNullLiteral(this ExpressionLexer expressionLexer)
        {
            Debug.Assert(expressionLexer.CurrentToken.Kind == ExpressionTokenKind.NullLiteral, "this.lexer.CurrentToken.InternalKind == ExpressionTokenKind.NullLiteral");

            expressionLexer.NextToken();
            ODataNullValue nullValue = new ODataNullValue();

            return(nullValue);
        }
Exemplo n.º 5
0
        internal static object ConvertValue(
            object odataValue,
            Type expectedReturnType,
            IEdmTypeReference propertyType,
            IEdmModel model,
            ApiContext apiContext)
        {
            ODataDeserializerContext readContext = new ODataDeserializerContext
            {
                Model = model
            };

            ODataDeserializerProvider deserializerProvider = apiContext.GetApiService <ODataDeserializerProvider>();

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

            ODataNullValue nullValue = odataValue as ODataNullValue;

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

            ODataComplexValue complexValue = odataValue as ODataComplexValue;

            if (complexValue != null)
            {
                ODataEdmTypeDeserializer deserializer
                    = deserializerProvider.GetEdmTypeDeserializer(propertyType.AsComplex());
                return(deserializer.ReadInline(complexValue, propertyType, readContext));
            }

            ODataEnumValue enumValue = odataValue as ODataEnumValue;

            if (enumValue != null)
            {
                ODataEdmTypeDeserializer deserializer
                    = deserializerProvider.GetEdmTypeDeserializer(propertyType.AsEnum());
                return(deserializer.ReadInline(enumValue, propertyType, readContext));
            }

            ODataCollectionValue collection = odataValue as ODataCollectionValue;

            if (collection != null)
            {
                ODataEdmTypeDeserializer deserializer
                    = deserializerProvider.GetEdmTypeDeserializer(propertyType as IEdmCollectionTypeReference);
                var collectionResult = deserializer.ReadInline(collection, propertyType, readContext);

                return(ConvertCollectionType(collectionResult, expectedReturnType));
            }

            return(odataValue);
        }
Exemplo n.º 6
0
        public ODataResource CreateEntry(Object entity)
        {
            var odataProperties = new ODataProperty[Accessors.Length];

            for (int i = 0; i < Accessors.Length; i++)
            {
                OePropertyAccessor accessor = Accessors[i];
                Object             value    = accessor.Accessor(entity);

                ODataValue odataValue = null;
                if (value == null)
                {
                    odataValue = new ODataNullValue();
                }
                else if (value.GetType().IsEnum)
                {
                    odataValue = new ODataEnumValue(value.ToString());
                }
                else if (value is DateTime dateTime)
                {
                    switch (dateTime.Kind)
                    {
                    case DateTimeKind.Unspecified:
                        value = new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc));
                        break;

                    case DateTimeKind.Utc:
                        value = new DateTimeOffset(dateTime);
                        break;

                    case DateTimeKind.Local:
                        value = new DateTimeOffset(dateTime.ToUniversalTime());
                        break;

                    default:
                        throw new ArgumentOutOfRangeException("unknown DateTimeKind " + dateTime.Kind.ToString());
                    }
                    odataValue = new ODataPrimitiveValue(value);
                }
                else
                {
                    odataValue = new ODataPrimitiveValue(value);
                }

                odataValue.TypeAnnotation = accessor.TypeAnnotation;
                odataProperties[i]        = new ODataProperty()
                {
                    Name = accessor.Name, Value = odataValue
                };
            }

            return(new ODataResource
            {
                TypeName = _typeName,
                Properties = odataProperties
            });
        }
Exemplo n.º 7
0
        private static ODataResource CreateEntry(Object entity, PropertyInfo[] structuralProperties)
        {
            Type clrEntityType   = entity.GetType();
            var  odataProperties = new ODataProperty[structuralProperties.Length];

            for (int i = 0; i < odataProperties.Length; i++)
            {
                Object     value      = structuralProperties[i].GetValue(entity);
                ODataValue odataValue = null;
                if (value == null)
                {
                    odataValue = new ODataNullValue();
                }
                else if (value.GetType().IsEnum)
                {
                    odataValue = new ODataEnumValue(value.ToString());
                }
                else if (value is DateTime dateTime)
                {
                    switch (dateTime.Kind)
                    {
                    case DateTimeKind.Unspecified:
                        value = new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc));
                        break;

                    case DateTimeKind.Utc:
                        value = new DateTimeOffset(dateTime);
                        break;

                    case DateTimeKind.Local:
                        value = new DateTimeOffset(dateTime.ToUniversalTime());
                        break;

                    default:
                        throw new ArgumentOutOfRangeException("unknown DateTimeKind " + dateTime.Kind.ToString());
                    }
                    odataValue = new ODataPrimitiveValue(value);
                }
                else
                {
                    odataValue = new ODataPrimitiveValue(value);
                }

                odataProperties[i] = new ODataProperty()
                {
                    Name = structuralProperties[i].Name, Value = odataValue
                };
            }

            return(new ODataResource
            {
                TypeName = clrEntityType.FullName,
                Properties = odataProperties
            });
        }
Exemplo n.º 8
0
        public static void AddFunctionParameters(IEdmFunction function, string paramName, object paramValue,
                                                 IDictionary <string, object> routeData, IDictionary <string, object> values, IDictionary <string, string> paramMapping)
        {
            Contract.Assert(function != null);

            // using the following codes to support [FromODataUriAttribute]
            IEdmOperationParameter edmParam = function.FindParameter(paramName);

            Contract.Assert(edmParam != null);
            ODataParameterValue parameterValue = new ODataParameterValue(paramValue, edmParam.Type);

            string name = paramName;

            if (paramMapping != null)
            {
                Contract.Assert(paramMapping.ContainsKey(paramName));
                name = paramMapping[paramName];
            }

            string prefixName = ODataParameterValue.ParameterValuePrefix + name;

            values[prefixName] = parameterValue;

            // using the following codes to support [FromUriAttribute]
            if (!routeData.ContainsKey(name))
            {
                routeData.Add(name, paramValue);
            }

            ODataNullValue nullValue = paramValue as ODataNullValue;

            if (nullValue != null)
            {
                routeData[name] = null;
            }

            ODataEnumValue enumValue = paramValue as ODataEnumValue;

            if (enumValue != null)
            {
                // Remove the type name of the ODataEnumValue and keep the value.
                routeData[name] = enumValue.Value;
            }

            IncrementKeyCount(values);
        }
Exemplo n.º 9
0
        public static string ConvertToUriLiteral(object value, ODataVersion version, IEdmModel model)
        {
            if (value == null)
            {
                value = new ODataNullValue();
            }

            if (model == null)
            {
                model = Microsoft.OData.Edm.Library.EdmCoreModel.Instance;
            }

            ODataNullValue nullValue = value as ODataNullValue;

            if (nullValue != null)
            {
                return(ExpressionConstants.KeywordNull);
            }

            ODataCollectionValue collectionValue = value as ODataCollectionValue;

            if (collectionValue != null)
            {
                return(ODataUriConversionUtils.ConvertToUriCollectionLiteral(collectionValue, model, version));
            }

            ODataComplexValue complexValue = value as ODataComplexValue;

            if (complexValue != null)
            {
                return(ODataUriConversionUtils.ConvertToUriComplexLiteral(complexValue, model, version));
            }

            ODataEnumValue enumValue = value as ODataEnumValue;

            if (enumValue != null)
            {
                return(ODataUriConversionUtils.ConvertToUriEnumLiteral(enumValue, version));
            }

            // Try to convert uints to their underlying type first according to the model.
            value = model.ConvertToUnderlyingTypeIfUIntValue(value);

            return(ODataUriConversionUtils.ConvertToUriPrimitiveLiteral(value, version));
        }
        public static string ConvertToUriLiteral(object value, ODataVersion version, IEdmModel model)
        {
            if (value == null)
            {
                value = new ODataNullValue();
            }

            if (model == null)
            {
                model = Microsoft.OData.Edm.Library.EdmCoreModel.Instance;
            }

            ODataNullValue nullValue = value as ODataNullValue;

            if (nullValue != null)
            {
                return(ExpressionConstants.KeywordNull);
            }

            ODataCollectionValue collectionValue = value as ODataCollectionValue;

            if (collectionValue != null)
            {
                return(ODataUriConversionUtils.ConvertToUriCollectionLiteral(collectionValue, model, version));
            }

            ODataComplexValue complexValue = value as ODataComplexValue;

            if (complexValue != null)
            {
                return(ODataUriConversionUtils.ConvertToUriComplexLiteral(complexValue, model, version));
            }

            ODataEnumValue enumValue = value as ODataEnumValue;

            if (enumValue != null)
            {
                return(ODataUriConversionUtils.ConvertToUriEnumLiteral(enumValue, version));
            }

            return(ODataUriConversionUtils.ConvertToUriPrimitiveLiteral(value, version));
        }
Exemplo n.º 11
0
        public ODataResource CreateEntry(Object entity)
        {
            for (int i = 0; i < _accessors.Length; i++)
            {
                OePropertyAccessor accessor = _accessors[i];
                Object             value    = accessor.Accessor(entity);
                if (value is DateTime)
                {
                    value = (DateTimeOffset)(DateTime)value;
                }
                ODataValue odataValue = null;
                if (value == null)
                {
                    odataValue = new ODataNullValue()
                    {
                        TypeAnnotation = accessor.TypeAnnotation
                    }
                }
                ;
                else
                {
                    if (value.GetType().GetTypeInfo().IsEnum)
                    {
                        odataValue = new ODataEnumValue(value.ToString());
                    }
                    else
                    {
                        odataValue = new ODataPrimitiveValue(value);
                    }
                    odataValue.TypeAnnotation = accessor.TypeAnnotation;
                }
                _odataProperties[i].Value = odataValue;
            }

            return(new ODataResource
            {
                TypeName = _typeName,
                Properties = _odataProperties
            });
        }
Exemplo n.º 12
0
 public ODataNullValueTests()
 {
     this.nullValue = new ODataNullValue();
 }
Exemplo n.º 13
0
 public ODataNullValueTests()
 {
     this.nullValue = new ODataNullValue();
 }
Exemplo n.º 14
0
 public void Initialize()
 {
     this.nullValue = new ODataNullValue();
 }
Exemplo n.º 15
0
        /// <summary>
        /// Creates a new instance of this class by consuming xml from the given input context.
        /// </summary>
        /// <param name="inputContext">The input context to use to create the annotation.</param>
        /// <param name="propertyAndValueDeserializer">The property and value deserializer to use when reading values in the annotation element content.</param>
        /// <returns>The <see cref="AtomInstanceAnnotation"/> populated with the information from the 'm:annotation' XML element, as long as the value is a string. Returns null otherwise.</returns>
        /// <remarks>
        /// Pre-Condition:   XmlNodeType.Element    - The annotation element to read.
        /// Post-Condition:  XmlNodeType.Any        - The node after the end of the annotation element, or the same element as in the pre-condition if the annotation was skipped.
        /// </remarks>
        internal static AtomInstanceAnnotation CreateFrom(ODataAtomInputContext inputContext, ODataAtomPropertyAndValueDeserializer propertyAndValueDeserializer)
        {
            var xmlReader = inputContext.XmlReader;
            Debug.Assert(xmlReader != null, "xmlReader != null");
            Debug.Assert(xmlReader.NodeType == XmlNodeType.Element, "xmlReader must be positioned on an Element");
            Debug.Assert(xmlReader.NameTable != null, "xmlReader.NameTable != null");
            Debug.Assert(xmlReader.LocalName == "annotation", "Must be positioned on an annotation element");

            string termAttributeValue = null;
            string targetAttributeValue = null;
            string typeAttributeValue = null;
            bool nullAttributePresentAndTrue = false;
            bool sawMultipleAttributeValueNotations = false;

            // Notes on "attribute value notation":
            // Empty elements may have the annotation value specified via an attribute on the annotation element.
            // Exactly one of the following attributes must be present if this notation is being used: "string", "int", "bool", "float", "decimal".
            // The value of the annotation is the value of this value-specifying attribute.
            string attributeValueNotationAttributeName = null;
            string attributeValueNotationAttributeValue = null;
            IEdmPrimitiveTypeReference attributeValueNotationTypeReference = null;
            
            XmlNameTable xmlNameTable = xmlReader.NameTable;
            string metadataNamespace = xmlNameTable.Get(AtomConstants.ODataMetadataNamespace);
            string nullAttributeName = xmlNameTable.Get(AtomConstants.ODataNullAttributeName);
            string typeAttributeName = xmlNameTable.Get(AtomConstants.AtomTypeAttributeName);
            string emptyNamespace = xmlNameTable.Get(string.Empty);
            string termAttributeName = xmlNameTable.Get(AtomConstants.ODataAnnotationTermAttribute);
            string targetAttributeName = xmlNameTable.Get(AtomConstants.ODataAnnotationTargetAttribute);

            // Loop through all the attributes and remember the ones specific to annotations.
            while (xmlReader.MoveToNextAttribute())
            {
                if (xmlReader.NamespaceEquals(metadataNamespace))
                {
                    if (xmlReader.LocalNameEquals(typeAttributeName))
                    {
                        typeAttributeValue = xmlReader.Value;
                    }
                    else if (xmlReader.LocalNameEquals(nullAttributeName))
                    {
                        nullAttributePresentAndTrue = ODataAtomReaderUtils.ReadMetadataNullAttributeValue(xmlReader.Value);
                    }

                    // Ignore all other attributes in the metadata namespace.
                    // In general, we only fail on reading if we can't make sense of the document any more. Reader should be loose.
                    // If we choose to start recognizing an additional attribute in the metadata namespace later, be careful not to
                    // fail if it doesn't parse correctly (so that we don't cause a breaking change).
                }
                else if (xmlReader.NamespaceEquals(emptyNamespace))
                {
                    if (xmlReader.LocalNameEquals(termAttributeName))
                    {
                        termAttributeValue = xmlReader.Value;

                        // Before doing any other validation or further reading, check whether or not to read this annotation according to the filter.
                        if (propertyAndValueDeserializer.MessageReaderSettings.ShouldSkipAnnotation(termAttributeValue))
                        {
                            xmlReader.MoveToElement();
                            return null;
                        }
                    }
                    else if (xmlReader.LocalNameEquals(targetAttributeName))
                    {
                        targetAttributeValue = xmlReader.Value;
                    }
                    else
                    {
                        // Check if this attribute is one used by attribute value notation.
                        IEdmPrimitiveTypeReference potentialTypeFromAttributeValueNotation = LookupEdmTypeByAttributeValueNotationName(xmlReader.LocalName);
                        if (potentialTypeFromAttributeValueNotation != null)
                        {
                            // If we've already seen an attribute used for attribute value notation, 
                            // throw since we don't know which type to use (even if the values are the same).
                            // But don't throw yet, because we might not have encountered the term name yet,
                            // and the annotation filter might say to ignore this annotation (and so we shouldn't throw).
                            if (attributeValueNotationTypeReference != null)
                            {
                                sawMultipleAttributeValueNotations = true;
                            }

                            attributeValueNotationTypeReference = potentialTypeFromAttributeValueNotation;
                            attributeValueNotationAttributeName = xmlReader.LocalName;
                            attributeValueNotationAttributeValue = xmlReader.Value;
                        }
                    }

                    // Ignore all other attributes in the empty namespace.
                }

                // Ignore all other attributes in all other namespaces.
            }

            xmlReader.MoveToElement();

            // The term attribute is required.
            if (termAttributeValue == null)
            {
                throw new ODataException(ODataErrorStrings.AtomInstanceAnnotation_MissingTermAttributeOnAnnotationElement);
            }

            if (sawMultipleAttributeValueNotations)
            {
                throw new ODataException(ODataErrorStrings.AtomInstanceAnnotation_MultipleAttributeValueNotationAttributes);
            }
            
            // If this term is defined in the model, look up its type. If the term is not in the model, this will be null.
            IEdmTypeReference expectedTypeReference = MetadataUtils.LookupTypeOfValueTerm(termAttributeValue, propertyAndValueDeserializer.Model);

            ODataValue annotationValue;
            if (nullAttributePresentAndTrue)
            {
                // The m:null attribute has precedence over the content of the element, thus if we find m:null='true' we ignore the content of the element.
                ReaderValidationUtils.ValidateNullValue(
                    propertyAndValueDeserializer.Model, 
                    expectedTypeReference, 
                    propertyAndValueDeserializer.MessageReaderSettings, 
                    /*validateNullValue*/ true,
                    termAttributeValue);
                annotationValue = new ODataNullValue();
            }
            else if (attributeValueNotationTypeReference != null)
            {
                annotationValue = GetValueFromAttributeValueNotation(
                    expectedTypeReference,
                    attributeValueNotationTypeReference,
                    attributeValueNotationAttributeName,
                    attributeValueNotationAttributeValue,
                    typeAttributeValue,
                    xmlReader.IsEmptyElement,
                    propertyAndValueDeserializer.Model,
                    propertyAndValueDeserializer.MessageReaderSettings);
            }
            else
            {
                annotationValue = ReadValueFromElementContent(propertyAndValueDeserializer, expectedTypeReference);
            }

            // Read the end tag (or the start tag if it was an empty element).
            xmlReader.Read();

            return new AtomInstanceAnnotation(
                targetAttributeValue,
                termAttributeValue,
                annotationValue);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Creates a new instance of this class by consuming xml from the given input context.
        /// </summary>
        /// <param name="inputContext">The input context to use to create the annotation.</param>
        /// <param name="propertyAndValueDeserializer">The property and value deserializer to use when reading values in the annotation element content.</param>
        /// <returns>The <see cref="AtomInstanceAnnotation"/> populated with the information from the 'm:annotation' XML element, as long as the value is a string. Returns null otherwise.</returns>
        /// <remarks>
        /// Pre-Condition:   XmlNodeType.Element    - The annotation element to read.
        /// Post-Condition:  XmlNodeType.Any        - The node after the end of the annotation element, or the same element as in the pre-condition if the annotation was skipped.
        /// </remarks>
        internal static AtomInstanceAnnotation CreateFrom(ODataAtomInputContext inputContext, ODataAtomPropertyAndValueDeserializer propertyAndValueDeserializer)
        {
            var xmlReader = inputContext.XmlReader;

            Debug.Assert(xmlReader != null, "xmlReader != null");
            Debug.Assert(xmlReader.NodeType == XmlNodeType.Element, "xmlReader must be positioned on an Element");
            Debug.Assert(xmlReader.NameTable != null, "xmlReader.NameTable != null");
            Debug.Assert(xmlReader.LocalName == "annotation", "Must be positioned on an annotation element");

            string termAttributeValue                 = null;
            string targetAttributeValue               = null;
            string typeAttributeValue                 = null;
            bool   nullAttributePresentAndTrue        = false;
            bool   sawMultipleAttributeValueNotations = false;

            // Notes on "attribute value notation":
            // Empty elements may have the annotation value specified via an attribute on the annotation element.
            // Exactly one of the following attributes must be present if this notation is being used: "string", "int", "bool", "float", "decimal".
            // The value of the annotation is the value of this value-specifying attribute.
            string attributeValueNotationAttributeName  = null;
            string attributeValueNotationAttributeValue = null;
            IEdmPrimitiveTypeReference attributeValueNotationTypeReference = null;

            XmlNameTable xmlNameTable        = xmlReader.NameTable;
            string       metadataNamespace   = xmlNameTable.Get(AtomConstants.ODataMetadataNamespace);
            string       nullAttributeName   = xmlNameTable.Get(AtomConstants.ODataNullAttributeName);
            string       typeAttributeName   = xmlNameTable.Get(AtomConstants.AtomTypeAttributeName);
            string       emptyNamespace      = xmlNameTable.Get(string.Empty);
            string       termAttributeName   = xmlNameTable.Get(AtomConstants.ODataAnnotationTermAttribute);
            string       targetAttributeName = xmlNameTable.Get(AtomConstants.ODataAnnotationTargetAttribute);

            // Loop through all the attributes and remember the ones specific to annotations.
            while (xmlReader.MoveToNextAttribute())
            {
                if (xmlReader.NamespaceEquals(metadataNamespace))
                {
                    if (xmlReader.LocalNameEquals(typeAttributeName))
                    {
                        typeAttributeValue = xmlReader.Value;
                    }
                    else if (xmlReader.LocalNameEquals(nullAttributeName))
                    {
                        nullAttributePresentAndTrue = ODataAtomReaderUtils.ReadMetadataNullAttributeValue(xmlReader.Value);
                    }

                    // Ignore all other attributes in the metadata namespace.
                    // In general, we only fail on reading if we can't make sense of the document any more. Reader should be loose.
                    // If we choose to start recognizing an additional attribute in the metadata namespace later, be careful not to
                    // fail if it doesn't parse correctly (so that we don't cause a breaking change).
                }
                else if (xmlReader.NamespaceEquals(emptyNamespace))
                {
                    if (xmlReader.LocalNameEquals(termAttributeName))
                    {
                        termAttributeValue = xmlReader.Value;

                        // Before doing any other validation or further reading, check whether or not to read this annotation according to the filter.
                        if (propertyAndValueDeserializer.MessageReaderSettings.ShouldSkipAnnotation(termAttributeValue))
                        {
                            xmlReader.MoveToElement();
                            return(null);
                        }
                    }
                    else if (xmlReader.LocalNameEquals(targetAttributeName))
                    {
                        targetAttributeValue = xmlReader.Value;
                    }
                    else
                    {
                        // Check if this attribute is one used by attribute value notation.
                        IEdmPrimitiveTypeReference potentialTypeFromAttributeValueNotation = LookupEdmTypeByAttributeValueNotationName(xmlReader.LocalName);
                        if (potentialTypeFromAttributeValueNotation != null)
                        {
                            // If we've already seen an attribute used for attribute value notation,
                            // throw since we don't know which type to use (even if the values are the same).
                            // But don't throw yet, because we might not have encountered the term name yet,
                            // and the annotation filter might say to ignore this annotation (and so we shouldn't throw).
                            if (attributeValueNotationTypeReference != null)
                            {
                                sawMultipleAttributeValueNotations = true;
                            }

                            attributeValueNotationTypeReference  = potentialTypeFromAttributeValueNotation;
                            attributeValueNotationAttributeName  = xmlReader.LocalName;
                            attributeValueNotationAttributeValue = xmlReader.Value;
                        }
                    }

                    // Ignore all other attributes in the empty namespace.
                }

                // Ignore all other attributes in all other namespaces.
            }

            xmlReader.MoveToElement();

            // The term attribute is required.
            if (termAttributeValue == null)
            {
                throw new ODataException(ODataErrorStrings.AtomInstanceAnnotation_MissingTermAttributeOnAnnotationElement);
            }

            if (sawMultipleAttributeValueNotations)
            {
                throw new ODataException(ODataErrorStrings.AtomInstanceAnnotation_MultipleAttributeValueNotationAttributes);
            }

            // If this term is defined in the model, look up its type. If the term is not in the model, this will be null.
            IEdmTypeReference expectedTypeReference = MetadataUtils.LookupTypeOfValueTerm(termAttributeValue, propertyAndValueDeserializer.Model);

            ODataValue annotationValue;

            if (nullAttributePresentAndTrue)
            {
                // The m:null attribute has precedence over the content of the element, thus if we find m:null='true' we ignore the content of the element.
                ReaderValidationUtils.ValidateNullValue(
                    propertyAndValueDeserializer.Model,
                    expectedTypeReference,
                    propertyAndValueDeserializer.MessageReaderSettings,
                    /*validateNullValue*/ true,
                    termAttributeValue);
                annotationValue = new ODataNullValue();
            }
            else if (attributeValueNotationTypeReference != null)
            {
                annotationValue = GetValueFromAttributeValueNotation(
                    expectedTypeReference,
                    attributeValueNotationTypeReference,
                    attributeValueNotationAttributeName,
                    attributeValueNotationAttributeValue,
                    typeAttributeValue,
                    xmlReader.IsEmptyElement,
                    propertyAndValueDeserializer.Model,
                    propertyAndValueDeserializer.MessageReaderSettings);
            }
            else
            {
                annotationValue = ReadValueFromElementContent(propertyAndValueDeserializer, expectedTypeReference);
            }

            // Read the end tag (or the start tag if it was an empty element).
            xmlReader.Read();

            return(new AtomInstanceAnnotation(
                       targetAttributeValue,
                       termAttributeValue,
                       annotationValue));
        }
Exemplo n.º 17
0
        public static string ConvertToUriLiteral(object value, ODataVersion version, IEdmModel model)
        {
            if (value == null)
            {
                value = new ODataNullValue();
            }

            if (model == null)
            {
                model = Microsoft.OData.Edm.Library.EdmCoreModel.Instance;
            }

            ODataNullValue nullValue = value as ODataNullValue;
            if (nullValue != null)
            {
                return ExpressionConstants.KeywordNull;
            }

            ODataCollectionValue collectionValue = value as ODataCollectionValue;
            if (collectionValue != null)
            {
                return ODataUriConversionUtils.ConvertToUriCollectionLiteral(collectionValue, model, version);
            }

            ODataComplexValue complexValue = value as ODataComplexValue;
            if (complexValue != null)
            {
                return ODataUriConversionUtils.ConvertToUriComplexLiteral(complexValue, model, version);
            }

            ODataEnumValue enumValue = value as ODataEnumValue;
            if (enumValue != null)
            {
                return ODataUriConversionUtils.ConvertToUriEnumLiteral(enumValue, version);
            }

            ODataEntry entry = value as ODataEntry;
            if (entry != null)
            {
                return ODataUriConversionUtils.ConvertToUriEntityLiteral(entry, model);
            }

            ODataEntityReferenceLink link = value as ODataEntityReferenceLink;
            if (link != null)
            {
                return ODataUriConversionUtils.ConvertToUriEntityReferenceLiteral(link, model);
            }

            ODataEntityReferenceLinks links = value as ODataEntityReferenceLinks;
            if (links != null)
            {
                return ODataUriConversionUtils.ConvertToUriEntityReferencesLiteral(links, model);
            }

            var list = value as IEnumerable<ODataEntry>;
            if (list != null)
            {
                return ODataUriConversionUtils.ConvertToUriEntitiesLiteral(list, model);
            }

            // Try to convert uints to their underlying type first according to the model.
            value = model.ConvertToUnderlyingTypeIfUIntValue(value);

            return ODataUriConversionUtils.ConvertToUriPrimitiveLiteral(value, version);
        }
Exemplo n.º 18
0
        public static string ConvertToUriLiteral(object value, ODataVersion version, IEdmModel model)
        {
            if (value == null)
            {
                value = new ODataNullValue();
            }

            if (model == null)
            {
                model = Microsoft.OData.Edm.Library.EdmCoreModel.Instance;
            }

            ODataNullValue nullValue = value as ODataNullValue;

            if (nullValue != null)
            {
                return(ExpressionConstants.KeywordNull);
            }

            ODataCollectionValue collectionValue = value as ODataCollectionValue;

            if (collectionValue != null)
            {
                return(ODataUriConversionUtils.ConvertToUriCollectionLiteral(collectionValue, model, version));
            }

            ODataComplexValue complexValue = value as ODataComplexValue;

            if (complexValue != null)
            {
                return(ODataUriConversionUtils.ConvertToUriComplexLiteral(complexValue, model, version));
            }

            ODataEnumValue enumValue = value as ODataEnumValue;

            if (enumValue != null)
            {
                return(ODataUriConversionUtils.ConvertToUriEnumLiteral(enumValue, version));
            }

            ODataEntry entry = value as ODataEntry;

            if (entry != null)
            {
                return(ODataUriConversionUtils.ConvertToUriEntityLiteral(entry, model));
            }

            ODataEntityReferenceLink link = value as ODataEntityReferenceLink;

            if (link != null)
            {
                return(ODataUriConversionUtils.ConvertToUriEntityReferenceLiteral(link, model));
            }

            ODataEntityReferenceLinks links = value as ODataEntityReferenceLinks;

            if (links != null)
            {
                return(ODataUriConversionUtils.ConvertToUriEntityReferencesLiteral(links, model));
            }

            var list = value as IEnumerable <ODataEntry>;

            if (list != null)
            {
                return(ODataUriConversionUtils.ConvertToUriEntitiesLiteral(list, model));
            }

            // Try to convert uints to their underlying type first according to the model.
            value = model.ConvertToUnderlyingTypeIfUIntValue(value);

            return(ODataUriConversionUtils.ConvertToUriPrimitiveLiteral(value, version));
        }